AttributeBehaviour - current attribute value

I’d like to use AttributeBehaviour for format a date from d-m-Y to Y-m-d before saving in db.

In the value function callback, there is some parameter like $attribute to get value of $model->$attribute?


public function behaviors()

    {

        return [

            [

                'class' => AttributeBehavior::className(),

                'attributes' => [

                    ActiveRecord::EVENT_BEFORE_INSERT => ['date1','date2'], 

                    ActiveRecord::EVENT_BEFORE_UPDATE => ['date1','date2']

                ],

                'value' => function ($event, ??$attribute-caller??) {

                    return Yii::$app->formatter($model->??$attribute-caller??, "php:Y-m-d)

                },

            ],

        ];

    }

Thanks,

Mattia

Hi,

I think the way you want to do it is not possible.

Read for details:

But if I’m not wrong you could access the variable values for example with:

$this->owner->date1

$this->owner->date2

or

$event->sender->date1

$event->sender->date2

Best Regards

thank you MetaCrawler,

I’d like to use one behaviour declaration and manage more attributes, so the top was if I can parameterize del name of the attribute:




$this->owner->$attribute-name // the name of the attribute on process



1 Like

Hello again,

The problem is that you are writing the behavior as closure directly inside your model.

There it is not possible the way you want to do it.

If you want to have the behavior more dynamically and want to access "$this->owner->$attribute"…

I suggest you study both files:

yii/behaviors/AttributeBehavior.php

yii/base/Behavior.php

After that create your own Behavior for example extending from AttributeBehavior.

Inside the Behavior you should be able to access "$this->owner->$attribute".

(Just take a look in AttributeBehavior->evaluateAttributes … row 121)

Regards

1 Like

I moved line 121 inside the foreach , I pass $attribute in getValue and modified the method.

            foreach ($attributes as $attribute) {
                $value = $this->getValue($event, $attribute);
                ....

/**
     * Returns the value for the current attributes.
     * This method is called by [[evaluateAttributes()]]. Its return value will be assigned
     * to the attributes corresponding to the triggering event.
     * @param Event $event the event that triggers the current attribute updating.
     * @param string $attribute the event that triggers the current attribute updating.
     * @return mixed the attribute value
     */
    protected function getValue($event, $attribute)
    {
        if ($this->value instanceof Closure || (is_array($this->value) && is_callable($this->value))) {
            return call_user_func($this->value, $event, $attribute);
        }

        return $this->value;
    }