3

How to a add a button in the crud _form for actionUpdate?

so i can delete the saved file, and upload a new one

i had this function in the model

    public function deleteImage()
    { 
        unlink(Yii::app()->basePath.'/../uploads/'.$this->image);
    }

so how to trigger this with a button like this?

<input type="button" value="delete image"/>

1 Answer 1

6

In MVC, the controller generally takes care of interaction from the user, so the user does not directly access the model, but does it through the controller. The controller intercepts user actions and does the work by calling model(s). Therefore it is best not to call the model function directly, even though it is possible.

Now, to do what you want to do, we can create a function(action) in the controller which in turn will call the model's function.

To call a function(action) in the controller we can associate a url that will be called when the button is clicked, this can be done by using the onclick event. I'm guessing that you don't want the browser to navigate to a new url, hence we call this url with ajax.

Example, 1) in controller:

public function actionMyaction($id){
    $sampleMod=SampleModel::model()->findByPk($id);
    $sampleMod->deleteImage();
    Yii::app()->end();
}

2) in view with button: instead of <input type="button" value="delete image"/> use CHtml helper class's ajaxButton.

echo CHtml::ajaxButton('Delete Image',Yii::app()->createUrl('controllername/actionname',array('id'=>$id)));

Take care in passing the right $id.

1
  • also remember to delete things only with POST method, you can see this answer for non ajax requests. for ajax requests, simply add ajax options with 'type'=>'POST', details can be found in the documentation links given in answer.
    – bool.dev
    Aug 23, 2012 at 4:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.