Reputation: 2001
So this is what i want to do and this is what my fields
table looks like :
|-----------------------------|
|id | field | is_required|
|-----------------------------|
|1 | email | yes |
|-----------------------------|
|2 | phone | no |
|-----------------------------|
now i have created a view for this table using gii, which has an option to delete field value
, now what i want to do is in my actionDelete()
i want to check if the value that the user is trying to delete is required or not (if the table's is_required
field is yes
or no
, if it is yes
then the field is required, if it is no
then the field is not required), if the field is required i want to show an alert that "this field can't be deleted as it is a required field" else delete.
And this is what i have done so far in my controller:
public function actionDelete($id)
{
$check=Fields::model()->findByAttributes(array('id'=>$id));
$required=$check->is_required;
if($required =='no'){
$this->loadModel($id)->delete();
}elseif($required =='yes'){
echo "<script>alert('This field cannot be deleted.!');</script>";
}
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
but this is not working can any of you point me in the right direction..? Thanks in advance.
Upvotes: 0
Views: 2378
Reputation: 2001
So, I found a way to do this, here it is:
public function actionDelete($id)
{
$check = Fields::model()->findByAttributes(array('id'=>$id));
$required = $check->is_required;
if($required == 'no') {
$check->delete();
} elseif($required == 'yes') {
throw new CHttpException(400, "This is a required field and cannot be deleted");
}
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
There might be better ways of doing this, please let me know if you guys find any..thanks a lot stackoverflow. :)
Upvotes: 0
Reputation: 14860
Here's a better way of doing this.
First, put the condition for deletion in your model instead of the controller. You can use beforeDelete
to do this.
public function beforeDelete(){
if($this->is_required=='no'){
return true;
}
return false;
}
Next update your action to a) use POST instead of GET and b) check whether the record exists
public function actionDelete($id){
if($this->request->isPostRequest){ //enforce use of POST
$model=$this->loadModel($id); // loadModel throws an exception if the record doesn't exist
if($model->delete()){
// do your redirects here
}else{
// do something else
}
}else{
throw new CHttpException(400,'Invalid Request');
}
}
Upvotes: 2