Automatic Parameter Binding to Post Variables in Yii2

I've been working a lot with the alpha of Yii2 recently and have been loving it, but have run into a few issues. I'm going to try to post them here as a help to those of you who may have the same issues down the line.

Automatic Parameter Binding

What is automatic parameter binding? If you read the Yii 1.1 guide to Controllers, you'll see that if you define an action with a parameter of $id, and then add a querystring of ?id=1 to your request, that parameter will automatically be bound to the $id parameter. It's a nice convenience. For some reason, Yii2 only automatically binds GET variables, not POST. I wanted restrict certain actions to POST verbs and pass data through and have it be automatically be bound. But it only binds GET vars. Dang.

Fixing It.

It's super easy, actually. All you have to do is intercept the runAction method in your controller of choice and do a little tweaking. Here's the code: 

public function runAction($id, $params=array()){
$params = array_merge($_POST, $params);
parent::runAction($id, $params);
}

You can either add this to your particular controller that you'd like to automatically bind POST vars to, or you can create a base controller and extend all your other controllers off of that.

 

Happy coding. 

Google+