CakePHP 2 Displaying Validation Errors

by | Aug 18, 2019 | IT Tips | 0 comments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# app/Controller/ShipmentsController.php
    public function toggleShipped($id = null)
    {
        if (!$this->Shipment->exists($id)) {
            throw new NotFoundException(__('Invalid shipment'));
        }
 
        if ($this->request->is(['post', 'put'])) {
            $shipment = $this->Shipment->find(
                'first', [
                    'conditions' => [
                        'Shipment.id' => $id
                    ]
                ]
            );
 
            $data = [
                'shipped' => !(bool) $shipment['Shipment']['shipped'],
                'id' => $id
            ];
 
            //unset($this->Shipment->validate['shipped']);
            $this->Shipment->set($shipment);
            if ($this->Shipment->save($data)) {
                $this->Flash->success("Successfully toggled shipped state");
 
            } else {
                $errorText = '';
                // get Validation errors and append them into a string
                $ve = $this->Shipment->validationErrors;
                foreach (array_keys($ve) as $ak) {
                    $errorText .= join(' ', $ve[$ak]);
                };
                $this->Flash->error('Failed to toggle shipped state. ' . $errorText);
            }
            $this->redirect(['action' => 'index']);
        }
 
    }

This is just how I handle and display potentially multiple CakePHP 2 Validation Errors by looping through them and concatenating them together before displaying them with the Flash element

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.