CakePHP 2 Displaying Validation Errors

Written by James McDonald

August 18, 2019

# 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 *

You May Also Like…

How to Research a CPU Upgrade

How to Research a CPU Upgrade

Upgrade Time! Doing a lot of VMWare Workstation virtualization to create labs for self-study and training. Finding...