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 *

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.

You May Also Like…