keeg
keeg

Reputation: 3978

yii CHtml::button and POST request to controller

Is there a way to have CHtml::button send a post request to the controller

<?php echo CHtml::button('Button Text', array('submit' => array('controller/action'))); ?>

I'm looking to replicate the CHtml::linkfunctionality and POST to the controller

<?php echo CHtml::link('Delete',"#", array("submit"=>array('delete', 'id'=>$data->ID), 'confirm' => 'Are you sure?')); ?>

EDIT:

The button is NOT submitting a form

Upvotes: 6

Views: 25948

Answers (1)

bool.dev
bool.dev

Reputation: 17478

Try this:

echo CHtml::button('Delete',
    array(
        'submit'=>array('controllername/actionname',array('id'=>$id)),
        'confirm' => 'Are you sure?'
        // or you can use 'params'=>array('id'=>$id)
    )
);

As you'll see button also takes the special htmlOptions attribute clientChange.

Update Clarification of submit, from the doc link ():

submit: string, specifies the URL to submit to. If the current element has a parent form, that form will be submitted, and if 'submit' is non-empty its value will replace the form's URL. If there is no parent form the data listed in 'params' will be submitted instead (via POST method), to the URL in 'submit' or the currently requested URL if 'submit' is empty. Please note that if the 'csrf' setting is true, the CSRF token will be included in the params too.

emphasis mine

As you mentioned that you want to hit the delete action, the default gii generated actionDelete expects the id in the url, hence I passed the id in the url, i.e submit option.

Upvotes: 14

Related Questions