J
J
jekahm2015-09-22 01:17:10
Yii
jekahm, 2015-09-22 01:17:10

How and where is the isNewRecord property of the BaseActiveRecord class defined in Yii2?

Good day!
I'm currently learning Yii2 and I've run into this problem.
When generating CRUD through Gii according to the office. The documentation found in the views/country/_form.php view include file that the state of the Create/Update button changes based on the value of the isNewRecord property of the BaseActiveRecord class .

Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'])

As I understand it, this causes the corresponding getter getIsNewRecord () to be called,
public function getIsNewRecord()
    {
        return $this->_oldAttributes === null;
    }

where, in turn, the next $_oldAttributes property is checked.
But where and how the last property is set, I did not figure it out.
I would be very grateful if someone could explain what happens next in this chain.
Thanks in advance for your reply!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
SilverSlice, 2015-09-22
@jekahm

Sergey Protko described everything correctly. The _oldAttributes property is used to implement dirty attributes .

  • When fetching data, for example by the findOne() method, a row from the database is converted into an AR object by the BaseActiveRecord::populateRecord() method . The value of the _attributes and _oldAttributes properties contains the data received from the database in the form ['columnName' => 'value'].
  • When setting attributes ($customer->name = 'James'), the BaseActiveRecord::__set() magic method modifies the _attributes property .
  • When saving a record, the BaseActiveRecord::updateInternal() method gets only the changed attributes (comparing the _attributes and _oldAttributes properties ) in order to update only the required fields in the database.
  • By default , the _oldAttributes property is null . When a new object is created ($customer = new Customer()), it does not change, so based on it, it is determined whether the record is new or not.

S
Sergey, 2015-09-22
Protko @Fesor

this property is supposedly set immediately after the data is loaded from the database (in oldAttributes and attributes). So, before saving, we can check what we have changed, since only attributes will be subject to changes. Well, for the newly minted model, oldAttributes will always be empty.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question