Controller actions when composite primary key is involved

I have a many-to-many relationship between a Trip table and a User table, using a Trip_User table with a composite primary key of trip_id and user_id.

I generated my Model and Controller for the Trip_User table using Gii, but I am aware of the limitations in generating a CRUD when a composite primary key is involved. So, instead, I have duplicated the views that were generated for my Trip table and modified the code to accommodate for the Trip User controller and its fields. I also created action functions in my TripUserController based on the ones in TripController.

When I click on the Update icon for a specific record in the Manage Trip User screen, it loads a page with the message: Error 404 Your request is invalid.

Here is my actionUpdate function:


	public function actionUpdate($id)

	{

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


		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}



The URL in my browser address bar looks like this:


http://localhost/tripventory/index.php?r=tripuser/update&id[trip_id]=1&id[user_id]=4

In this case, id is obviously an array. Do I need to adjust my code to accommodate an array (the composite key) as the $id parameter of actionUpdate?

First, add this function to your model:


public function primaryKey()

{

        return array('trip_id', 'user_id');

}

OK, done. Is there something else? I am still getting an Error 400.

I apologize for my impatience, but I’m in a bind with a project that needs to get done. Can anyone help with this?

I have done what jacmoe suggested, but that alone didn’t change anything. In fact, I don’t think primaryKey() is being called. From what I remember reading in the documentation at some point, I think primaryKey() only gets called if no primary key is defined. In my case, I have a composite primary key defined.

I don’t know if this will work, but it’s worth a try




  public function init()

  {

    $this->getMetaData()->tableSchema->primaryKey = array('trip_id', 'user_id');

  }



/Tommy

Unfortunately, that didn’t work either. This is getting really frustrating. It shouldn’t be this difficult to use composite primary keys.

I am providing my Model and Controller below, in hopes that someone can help me figure this out.


<?php


/**

 * This is the model class for table "{{trip_user}}".

 *

 * The followings are the available columns in table '{{trip_user}}':

 * @property integer $trip_id

 * @property integer $user_id

 * @property string $comments

 * @property string $cdate

 * @property integer $cuser_id

 * @property string $udate

 * @property integer $uuser_id

 * @property integer $f_user_admin

 */

class TripUser extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @return TripUser the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


  //The following two functions added by myself to try and get composite key working

	public function init()

  {

    $this->getMetaData()->tableSchema->primaryKey = array('trip_id', 'user_id');

  }

	

	public function primaryKey()

	{

		return array('trip_id', 'user_id');

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return '{{trip_user}}';

	}


	/**

	 * @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('cdate, cuser_id, udate, uuser_id', 'required'),

			array('trip_id, user_id, cuser_id, uuser_id, f_user_admin', 'numerical', 'integerOnly'=>true),

			array('comments', 'safe'),

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

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

			array('trip_id, user_id, comments, cdate, cuser_id, udate, uuser_id, f_user_admin', '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(

			'tblUserx' => array(self::HAS_ONE, 'User', 'user_id'),

			'tblTripx' => array(self::HAS_ONE, 'Trip', 'trip_id'),

		);

	}


	/**

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

	 */

	public function attributeLabels()

	{

		return array(

			'trip_id' => 'Trip',

			'user_id' => 'User',

			'comments' => 'Comments',

			'cdate' => 'Cdate',

			'cuser_id' => 'Cuser',

			'udate' => 'Udate',

			'uuser_id' => 'Uuser',

			'f_user_admin' => 'F User Admin',

		);

	}


	/**

	 * 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('trip_id',$this->trip_id);

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

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

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

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

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

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

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


		return new CActiveDataProvider(get_class($this), array(

			'criteria'=>$criteria,

		));

	}

}


<?php


class TripUserController 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

		);

	}


	/**

	 * 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 TripUser;


		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if($model->save())

				$this->redirect(array('view','id'=>$model->trip_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['TripUser']))

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

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

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

	 */

	public function actionDelete($id)

	{

		if(Yii::app()->request->isPostRequest)

		{

			// we only allow deletion via POST request

			$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'));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('TripUser');

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

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new TripUser('search');

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

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

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


		$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=TripUser::model()->findByPk((int)$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']==='trip-form')

		{

			echo CActiveForm::validate($model);

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

		}

	}

}



Tell us more about the error you get. Error 400 - bad request!? It seems like you don’t have debugging enabled.

/Tommy

I do have debugging enabled. I have attached a screenshot to show you exactly how the error appears.

The issue seems to be with the fact that the Update button in my CGridView is calling the following URL:


http://localhost/tripventory/index.php?r=tripuser/update&id[trip_id]=1&id[user_id]=4

As you can see, the id is being passed as an array that contains the trip_id and user_id composite primary key. Then, in the controller, the function looks like this:


	public function actionUpdate($id)

	{

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


		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}



The fact that an array is being passed as an argument seems to be the problem. If I change the function declaration to this


	public function actionUpdate(array $id)



and change the loadModel function from


	public function loadModel($id)

	{

		$model=TripUser::model()->findByPk((int)$id);

		if($model===null)

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

		return $model;

	}



to


	public function loadModel(array $id)

	{

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

		if($model===null)

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

		return $model;

	}



it works. But, is all of this necessary? I’ve seen jacmoe’s suggestion of overriding primaryKey(). Is that supposed to be a solution in itself?

I’ve also tried what is [post=‘39873’]suggested here[/post], which produces instead a URL like this (trip_id and user_id are no longer in an array), but still getting the Error 400:


http://localhost/tripventory/index.php?r=tripuser/update&trip_id=1&user_id=4

So essentially, I am just looking for the "right" way of accomplishing what I am trying to do. By "right", I mean there must be an efficient, pre-determined way of accomplishing this through the framework.

Thanks again to anyone for helping out. Once I get this straightened out, I will be well on my way!

Sorry, I forgot the attachment. Here it is.

Obviously your problem can be concluded to "how to pass a pk array to the controller". You stated that you got it working by modifying two argument declarations in the Gii-generated controller? That sounds very reasonable to me. The generated code should be seen as a starting point and customizations most probably will have to be added.

(It’s also possible to customize/extend the Gii templates and generators, should you find it worth the effort.)

/Tommy

maybe somthing error that the controller didn’t receive a ID.

u try alter this code at user/view

array(‘label’=>‘Update Item’, ‘url’=>array(‘update’, ‘id’=>$model->id,‘pid’=>$model->tripuser->id)),

Thanks for your suggestion. What I did, is I changed my links as [post=‘39873’]suggested here[/post] and modified my controller’s actions, and the loadModel function, to accept two parameters: my trip_id and user_id, which make up the composite primary key.

It works that way, but I guess my constant struggle as a newbie is to make sure that I’m not coding around something that the framework could achieve more efficiently.