Dave
Dave

Reputation: 29141

CakePHP - edit loses URL variable when trying validation fails on save

User starts here:

/admin/cuisines/edit/16

User types something in that is against validation rules and clicks Submit. User is taken here:

/admin/cuisines/edit/16

User thinks it IS valid and clicks submit again - they're then taken here:

/admin/cuisines/edit/

User corrects their mistake, clicks submit, and instead of an edit, it saves this as a new item in the table, since there's no id.

My code:

    function admin_edit($id = null) { // EDIT ***********

    if (!$id && empty($this->data)) {
        $this->Session->setFlash(__('Invalid cuisine', true));
        $this->redirect(array('action' => 'index'));
    }
    if (!empty($this->data)) {
        if ($this->Cuisine->save($this->data)) {
            $this->Session->setFlash(__('The edits to this cuisine have been saved', true));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The edits to this cuisine could not be saved. Please, try again.', true));
        }
    }
    if (empty($this->data)) {
        $this->data = $this->Cuisine->read(null, $id);
    }
}

Any thoughts on what I'm doing wrong? I thought I did it just like the tutorial, but - I would have to guess Cake is smart enough to not let this happen - ie - my assumption is I'm doing something wrong.

Upvotes: 1

Views: 418

Answers (1)

joeytrapp
joeytrapp

Reputation: 46

To avoid the saving of new items when the edit form is submitted, make sure that a form field for the id is present.

<?php echo $this->Form->input('id'); ?>

This field will be hidden automatically because it is the models primary key.

Also check the form action attribute in the HTML. I sometimes have to set it manually to avoid it being wrong.

<?php echo $this->Form->create('Cuisine', array(
  'url' => array(
    'action' => 'edit',
    $this->Form->value('id')
   )
)); ?>

Upvotes: 3

Related Questions