Cakephp call action through button

actioncakephpcontrollerview

i wish to call a controller's action through form->button.
I have following things in the web page:

  • a search form
  • a table with delte option as postLink
  • 2 buttons that should call the same action onclick.
    My problem is that when i click on any of the buttons, the post request isn't fired. Below is my code:
    view.ctp

    echo $this->Form->create('Search', array(
    'type' => 'file',
    'url' => array(
    'controller' => 'artists',
    'action' => 'index',
    ),
    ));
    echo $this->Form->input('name');
    echo $this->Form->end(array(
    'label' => 'Search Artist',
    'class' => 'btn btn-info controls'
    ));

    echo $this->For….

    echo '' . $this->Form->postlink('',
                        array('action' => 'delete',
                            $row['Artist']['id']),
                        array('confirm' => 'Are you sure?')
                    );
    

    echo $this->Form->button('Featured', array(
    'name' => 'submit',
    'value' => 'Featured',
    'type' => 'submit',
    'url' => array(
    'controller' => 'artists',
    'action' => 'index',
    ),
    ));

    echo $this->Form->button('Unfeatured', array(
    'name' => 'submit',
    'value' => 'Unfeatured',
    'type' => 'submit',
    'url' => array(
    'controller' => 'artists',
    'action' => 'index',
    ),
    ));

controller:

public function isFeatured() {
    if ($this->params->data['submit'] == 'Featured') {
        //code
    } else if($this->params->data['submit'] == 'Unfeatured') {
        //code
    }
    $this->redirect(array('action' => 'index'));
}

where am i getting wrong?

Best Answer

Your form declaration doesn't point the action to your 'isFeatured' function in your controller. You should rewrite your buttons to be actual forms. Buttons themselves don't submit.

echo $this->Form->create('Search', array('action'=>'isFeatured'));
echo $this->Form->hidden('featured', array('value'=>'1'));
echo $this->Form->end('Featured');

echo $this->Form->create('Search', array('action'=>'isFeatured'));
echo $this->Form->hidden('featured', array('value'=>'0'));
echo $this->Form->end('Not Featured');

Controller:

public function isFeatured() {
   if($this->request->data){
      if($this->request->data['Search']['featured'] == '1'){
         //..Set the artist as featured
      }
      if($this->request->data['Search']['featured'] == '0'){
         //..Set the artist as not featured
      }
   }
}
Related Topic