S
S
Sergey Beloventsev2018-05-22 08:54:42
Yii
Sergey Beloventsev, 2018-05-22 08:54:42

How to get all properties (attributes) of a model in an attached behavior?

Actually here is the behavior

use yii\base\Behavior;
class ExportBehavior extends  Behavior
{
    public $attributes;

    public function export(){
        return $this->attributes;
    }
}

this is how I connect
public function behaviors() {
    return [
      'export'=>[
        'class'=>ExportBehavior::class,
        'attributes'=>$this->attributes,
      ]
    ];
  }

I get this array
array (size=10)
  'id' => null
  'firstname' => null
  'lastname' => null
  'middlename' => null
  'phone' => null
  'state' => null
  'date' => null
  'comment' => null
  'created_at' => null
  'updated_at' => null

I would like all attributes to be filled with the data of a particular model. What am I doing wrong ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-05-22
@Sergalas

You are passing the attributes at the moment you attach the behavior to the model, and at that time they are not populated. If you want to get up-to-date data, refer to the model attributes in the behavior itself using the owner
property , for example:

class ExportBehavior extends  Behavior
{
    public $attributes;

    public function export(){
        return $this->owner->attributes;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question