accessing post variables

Let’s say I have a form as follows:


<form method="post" action="">

<input type="text" name="Application[name]">

<input type="submit" value="Submit">

</form>

Now in my controller I want to access the POST variables. Normally you can do this:


echo $_POST['Application']['name'];

But I want to do it the shorthand way, I tried it like this:


$app=$this->loadApplication();

$app->attributes=$_POST['Application'];

echo $app->name;

But this does not work.

What kind of method is ‘loadApplication’? If it doesnt return an instance of CModel or its childclass it wont work since the ‘setAttributes’ method is not implemented.

In all honesty I don’t think I should be using loadApplication() but the only reason I’m using it is because I can’t do $app->attributes without initialising the object first.

I was under the impression that $app->attributes assigns all the POST variables to a $app object…

Make sure your attributes are declared safe.

Well in my model I did:

public $name;

Now when I post the form and var_dump $app->name; I get NULL

I’m using version 1.0.10 BTW.

http://www.yiiframework.com/doc/guide/form.model#securing-attribute-assignments

Read it (and pay attention to the differences in 1.0 and 1.1). You probably haven’t declared your attributes safe yet.

Cool. But is there no way to do this without declaring the attributes as safe? The thing is I have other forms that use the same Model and now those forms have stopped working.

use scenarios

Hi jayrulez,

I tried using scenarios but that doesn’t seem to work. The page URL is:

/mysite/index.php?r=admin/admin

And the code I used in my model is as follows:


public $name;

	

public function safeAttributes()

{

	return array(

		'admin'=>'name',

	);

}

I’m using version 1.0.10

To be honest I’m not too bothered about safe or unsafe attributes - all I want to to is access my POST variables by doing $app->name rather than $_POST[‘Application’][‘name’].

manually define your field names, and manually assign your model properties to the variables or override method of your model that assigns to attributes to do so.

when you use an active field eg: activeTextField, the name of the field evaluates to Model[attribute],

use a textField instead of activeTextField then you can make the name of your field attribute instead of Model[attribute].

In your controller, you can the assign your post values like $model->attribute = $_POST[‘attribute’];

if you override the function that sets model properties properly, you should still be able to use massive assignment.

I was under the impression Yii would do this for me? Ideally we should be able to easily have access to our post variables by referencing the object/model in Yii.

I managed to figure this out myself:

My ‘Application’ model extends CActiveRecord, so I created another model that extends CFormModel