D
D
Dmitry Petrik2015-11-04 19:52:30
Yii
Dmitry Petrik, 2015-11-04 19:52:30

Yii2. How to change the attribute value through behavior before rendering?

I am writing a behavior that changes the content of the content attribute before saving it to the database and before rendering it on the page. For example, the user wrote the text "11111", pressed the "save" button, before saving to the database, behavior changes this text to "12221" and saves it to the database. Then, when the user wants to see the behavior text, the text from the database should be replaced with "13331". I did the first part of the puzzle. But with the substitution of text for output to the user, I can not figure it out. Help advice!
First part:

class ContentBehavior extends Behavior
{
    public $attribute; //здесь будет задан атрибут content

public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
        ];
    }

public function beforeValidate($event)
    {
        if ( !empty( $this->owner->{$this->attribute} ) ) {
            $this->owner->{$this->attribute} = '12221';
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2015-11-05
@Flexo

afterFind()?

V
Vladimir Shapovalov, 2015-11-05
@Nexen2

same, repeat for EVENT_AFTER_FIND event

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question