Yii Delete 400 Error

Hello,

A month ago I ran into Yii. When I first used it I was amazed. Now I’m trying to build my first webapp with Yii. But I have run into some problems with the CRUD generator. I created a simple database table and added a model with Gii.

After I created the model I created the interface to create, update and delete via the CRUD generator. I can add items to database via the interface created. But when I want to delete something I get an Error 400 your request is invalid. I have searched the forum and via Google and I understand it has something to do with POST but I can’t find a solution for this problem. Can someone help me? Thanks!

Please post your model, controller, and view code.

The Controller


<?php


class ActieController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='//layouts/column2';


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

			'postOnly + delete', // we only allow deletion via POST request

		);

	}


	/**

	 * Specifies the access control rules.

	 * This method is used by the 'accessControl' filter.

	 * @return array access control rules

	 */

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'users'=>array('admin'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 * @param integer $id the ID of the model to be displayed

	 */

	public function actionView($id)

	{

		$this->render('view',array(

			'model'=>$this->loadModel($id),

		));

	}


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new Actie;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Actie']))

		{

			$model->attributes=$_POST['Actie'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}


	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 * @param integer $id the ID of the model to be updated

	 */

	public function actionUpdate($id)

	{

		$model=$this->loadModel($id);


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Actie']))

		{

			$model->attributes=$_POST['Actie'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}


		$this->render('update',array(

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'admin' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	public function actionDelete($id)

	{

		$this->loadModel($id)->delete();


		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

		if(!isset($_GET['ajax']))

			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('Actie');

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new Actie('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['Actie']))

			$model->attributes=$_GET['Actie'];


		$this->render('admin',array(

			'model'=>$model,

		));

	}


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 * @param integer the ID of the model to be loaded

	 */

	public function loadModel($id)

	{

		$model=Actie::model()->findByPk($id);

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='actie-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}

}



The Model


<?php


/**

 * This is the model class for table "tbl_actie".

 *

 * The followings are the available columns in table 'tbl_actie':

 * @property integer $id

 * @property string $titel

 * @property string $omschrijving

 * @property integer $status

 * @property string $create_time

 * @property string $deadline

 * @property integer $user_id

 * @property integer $klant_id

 */

class Actie extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return Actie the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'tbl_actie';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('titel, omschrijving, status, create_time, deadline, user_id, klant_id', 'required'),

			array('status, user_id, klant_id', 'numerical', 'integerOnly'=>true),

			array('titel', 'length', 'max'=>255),

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('id, titel, omschrijving, status, create_time, deadline, user_id, klant_id', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'id' => 'ID',

			'titel' => 'Titel',

			'omschrijving' => 'Omschrijving',

			'status' => 'Status',

			'create_time' => 'Create Time',

			'deadline' => 'Deadline',

			'user_id' => 'User',

			'klant_id' => 'Klant',

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('id',$this->id);

		$criteria->compare('titel',$this->titel,true);

		$criteria->compare('omschrijving',$this->omschrijving,true);

		$criteria->compare('status',$this->status);

		$criteria->compare('create_time',$this->create_time,true);

		$criteria->compare('deadline',$this->deadline,true);

		$criteria->compare('user_id',$this->user_id);

		$criteria->compare('klant_id',$this->klant_id);


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}

}

The View (admin.php)


<?php

/* @var $this ActieController */

/* @var $model Actie */


$this->breadcrumbs=array(

	'Acties'=>array('index'),

	'Manage',

);


$this->menu=array(

	array('label'=>'List Actie', 'url'=>array('index')),

	array('label'=>'Create Actie', 'url'=>array('create')),

);


Yii::app()->clientScript->registerScript('search', "

$('.search-button').click(function(){

	$('.search-form').toggle();

	return false;

});

$('.search-form form').submit(function(){

	$.fn.yiiGridView.update('actie-grid', {

		data: $(this).serialize()

	});

	return false;

});

");

?>


<h1>Manage Acties</h1>


<p>

You may optionally enter a comparison operator (<b>&lt;</b>, <b>&lt;=</b>, <b>&gt;</b>, <b>&gt;=</b>, <b>&lt;&gt;</b>

or <b>=</b>) at the beginning of each of your search values to specify how the comparison should be done.

</p>


<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<div class="search-form" style="display:none">

<?php $this->renderPartial('_search',array(

	'model'=>$model,

)); ?>

</div><!-- search-form -->


<?php $this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'actie-grid',

	'dataProvider'=>$model->search(),

	'filter'=>$model,

	'columns'=>array(

		'id',

		'titel',

		'omschrijving',

		'status',

		'create_time',

		'deadline',

		/*

		'user_id',

		'klant_id',

		*/

		array(

			'class'=>'CButtonColumn',

		),

	),

)); ?>



Maybe it has something to do with the missing jQuery files in the assets directory.

I’m missing the following files:

/assets/b70c11ab/jquery.js

/assets/b70c11ab/jquery.yii.js

I can’t find these files in the Yii Framwork Directory. Where can I find these files?

Could anybody help me please?

If your app does not load jquery then this is the problem for sure. Check and be sure that jQuery is loaded.

Try to delete everything in your assets folder so that it gets re-populated from scratch.

Your code looks like the default one generated by Gii so no problem there. I agree with Domba, delete all sub folders in assets directory and reload page. Also, your AccessControl filter specifies that admin and delete actions need user to have an admin role - are you logged in as an admin? Can you reach the admin action?

[i]

[/i]

Matt

I removed the assets folder completely and repopulated it when I reloaded the webapp. Still there is no sign of jQuery in the assets folder. I also search within the Yii framework directory. I couldn’t find any reference to jQuery of even a jquery.js or jquery.yii.js.

So the question is how does the framework get jquery in the assets folder when it doesn’t have the files in the framework itself?

I’m loggedin in the webapp as Admin, no problems there.

Note that the assets folder gets repopulated automatically it’s not up to you to repopulate it.

When you download the yii framework and unpack it, jQuery is located in framework/web/js/source folder.

Note that jQuery can be prevented to be automatically used by configuring scriptMap - http://www.yiiframework.com/doc/api/1.1/CClientScript#scriptMap-detail

How are you logged on the webapp should not have anything to do with using jQuery by Yii.

I think that something went wrong with copying the framework to my webroot directory. jQuery wasn’t in the framework at all.

So I copied the files from the zip that I downloaded from the yii website again, deleted everything in the assets folder and reloaded the webapp. Now jQuery is in the assets folder and the delete function works!

Thanks guys for your support!