Flanklin
Flanklin

Reputation: 11

How to set attribute in yii model

In my yii application. I write code as below:

OTP::model()->attributes['name'] = value;

But it doesn't work. Can anyone please explain why its not working?

Upvotes: 1

Views: 14489

Answers (7)

Niral Shakya
Niral Shakya

Reputation: 1

Set attribute in yii model

$obj = OTP::model();
$obj->name = $value;

Now if we pass this model to view then only these value will be displayed with name = $value

$this->render('view',array('model'=>$obj));

How can we set multiple value ? Like so that value displayed be:

name = value1 or name= value2 ...

 $obj->name= 'value1' 
  //  or
 $obj->name= 'value2' 

Upvotes: 0

user4153245
user4153245

Reputation:

if you have created model using gii you can set your attributes of your table's fields like below.

public function attributeLabels()
    {
        return array(
            'customer_first_name' => 'First Name',
            ...
            ...
        );
    }

in controller action put this code

$model = new Customer; // Use your model insterad of Customer

if you want to use it as a lable then just you need to put this code.

<?php echo $form->labelEx($model, 'customer_first_name', array('class' => 'control-label')); ?>

Upvotes: 0

user3469016
user3469016

Reputation: 1

$model = new OPT();
$model->attr = value

Upvotes: -1

user4153245
user4153245

Reputation:

When you define or extend a class, you can create class variables and methods in Yii just like you can in any other PHP system:

class Comment extends CActiveRecord {

    public $helperVariable;

    public function rules() { ... }
    ...
}

and then use them in the obvious way:

$var   = $model->helperVariable;

$rules = $model->rules();

This part everybody understands.

Upvotes: 0

Yatin Mistry
Yatin Mistry

Reputation: 100

This also works

 $model->setAttribute("name","value");

Upvotes: 1

CreatoR
CreatoR

Reputation: 1652

Setting value $value for attribute $name you just need:

$obj = OTP::model();
$obj->name = $value;

Upvotes: 2

mjalajel
mjalajel

Reputation: 2201

In order to be able to set attributes this way, the attribute should be marked as 'safe' in your validation rules (See: Yii Model rules validation)

Something like this should do the trick:

Class OTP{
  public function rules() {
    return array(
      array('name','safe')
    );
  }
}

Upvotes: 3

Related Questions