I add new attr. with setAttributes()

Hi,

in my controller I use the setAttributes() method to add NEW attributes (these attributes are not my table fields) to my model.

Now I use attributeNames() method to get all my model attributes, unfortunatelly the attributeNames() method does not return my NEW attributes.

These NEW attributes are in the ‘safeAttributes’ array.

Any idea?

Hi,

you may use getSafeAttributeNames() to get the names of all safe attributes.

The docu says for attributeNames():

If you also need the names of non-safe attributes bundled, well i don’t know how to retrieve them all together…

A dirty and not really good performing solution would be sth. like:


$attrNames = array_unique(array_merge(MyModel::model()->getSafeAttributeNames(),MyModel::model()->attributeNames()));

Regards

That is waht I need.

MyModel::model()->attributeNames(); does not give me attributes I added using setAttributes(). That is tha problem!

But getSafeAttributeNames() does so, doesn’t it?

hello im trying to add rule for non attribute element of a model.

i did not try to add it as a new attribute discussed as here.

anyway,

i added a checkbox in a registration form. i defined a new public property for it:


public $policy;

then i defined a new rule in rules method


...

array('policy', 'terms', 'val'=>1),

...

i saw this in docs:


class MyValidator extends CValidator

{

    protected function validateAttribute($model,$attribute)

    {

        $value=$model->$attribute;

        if($value has error)

            $model->addError($attribute,$errorMessage);

    }

}

then i wrote a similar code:




class terms extends CValidator

{

    public $val;

    protected function validateAttribute($model, $attribute)

    {

        $errorMessage = "You must agree with the Terms and Conditions!";

        $value = $model->$attribute;

        if($value !== $this->val)

            $model->addError($attribute, $errorMessage);

    }

}



the problem is:

since this is a non attribute element


$model->$attribute

is returning null.

i tried several things but i could not come up with something meaningful (shame on me :-[ )

but funny thing is i can see the error message now. in every submit whether checkbox checked or not :)

ok

sorry for the previous post

after a coffee break i solved the problem.

i added


'register'=>'policy',

to safeAttributes method

also i have trying to compare string with integer :blink:

after replacing


if ($value !== $this->val)

with


if ($value != $this->val)

problem is solved!