0

I m learning Cakephp concepts, below is the code for my controller in cakephp, save happens successful but cancel adds empty row to database.

<?php
   echo $this->Form->create('Customer');
    echo $this->Form->input('customer_name');
    .....
    echo $this->Form->button(
            'Save', 
            array('class' => 'button save')
        );

    echo $this->Form->button(
            'Cancel', 
            array('class' => 'button cancel')
        );

    echo $this->Form->end();

?>

And below is my view form

<?php
public function add() {
    if ($this->request->is('post')) {

        $this->Customer->create();
        if ($this->Customer->save($this->request->data)) {
            $this->Session->setFlash(__('Your customer has been saved.'));
            return $this->redirect(array('action' => 'index'));
        }
        elseif ($this->Customer->cancel('')) {
            $this->Session->setFlash(__('Customer info has not been saved'));
            return $this->redirect(array('action' => 'index'));
        }
    }

}

?>
empiric
  • 7,825
  • 7
  • 37
  • 48
Sandeep Kumar
  • 25
  • 1
  • 8

1 Answers1

1

You are creating a button in your view. In Cakephp the button-tag act like a submit-button. Therefore you have to either creating a link (redirecting to the previous site):

$this->Html->link('Cancel', array('controller' => 'customer', 'action' => 'index'));

or preventing the button to submit the form e.g. via javascript (jQuery):

$('.button cancel').on('click', function(e)){
    e.preventDefault();
}

According to this site there is another option:

echo $this->Form->button(
        'Cancel', 
        array('type' => 'button', 'class' => 'btn button cancel')
);
empiric
  • 7,825
  • 7
  • 37
  • 48