Automatic Binding Of Parameters

This stumped me for a while and is a good heads up.

I was trying to do an Ajax POST, and even though my data was being passed fine I was getting a 400 Bad Request in Chrome.

Yii only binds parameters automatically with a GET. So if in your controller you have an action called public function actionDoSomething($id) then you can only call it if your URL has this format:../my_app?index.php?r=doSomething&id=1

If you want to POST to this function (for example deleting should only be done via POST) but still want to take advantage of the automatic parameter binding or having the parameter appear in your php document hints there are two solutions:


[*]Set the $id with a default value i.e. actionDoSomething($id=null) and then in your method do:

[*]$id = $_POST["id"]



[*]Or if you are POSTing with Ajax then include the data in the url AND in the data variable



[*]url: "index.php?r=tripLocations/delete&id="+id,

[*]data: {id:id},

[*]type: "POST",


This is not evident at first. For example at first glance it seems that the Yii admin delete icon is a GET since when you mouse over it you see the url with id=1 but on the backend it must make an Ajax call with a POST while still including the data in the URL.

POST indicates that the request is going to make permanent changes in the storage at the server backend. The POST payload represent the resource state to be saved. GET is for data retrieval, it is often used just to identify resources to fetch. When you want to modify something, you need to identify it first.

You rarely change the identity of a resource, that is you don’t change the id of a record. So you don’t send them in the POST payload, you just include them in the GET part.

In your example the ‘data’ key could be empty or not specified at all.

We can overide method getActionParams of CController to bind POST parameters as well.

public function getActionParams()


		return $_GET+$_POST;


hmm makes sense… it might be weird but I like having the data that I am passing in, in the parameter list. This way anybody looking at the code knows directly what needs to be passed in to a certain function.

If in the method body you assign the variable from the POST array it is not as evident.

I like this solution a lot! Thanks for the heads up. I know Yii only automatically binds with GET, so this is a nice trick to get around that :)