I am using Yii2 and I have the virtual attribute notes2
(that is used by the GUI functions instead of database attribute notes):
class Order extends \yii\db\ActiveRecord
{
public function getnotes2() {
return iconv('UTF-16LE', 'UTF-8', $this->notes);
}
public function setnotes2($value) {
$this->notes = iconv('UTF-8', 'UTF-16LE', $value);
}
}
In this case both the following codes $order->notes2
and $order->Notes2
calls the setter and returns the right value.
But I have to use $order->getAttributes()
function and default implementation of it does not include the virtual attributes. So I tried to override this function with:
public function attributes() {
$attributes = parent::attributes();
$attributes['notes2'] = 'notes2';
return $attributes;
}
And now json_encode($order->getAttributes())
includes empty notes2
field, but $order->notes2
(obviously - this causes the notes2
field to become empty) has no value, but $order->Notes2
has value!
Why such flip-flop of the register of the first character happens? How to declare correctly the virtual field that is available in getAttributes()
as well?
But the following code (instead of override of attributes()
)
public function getAttributes($names = null, $except = []) {
return array_merge(['notes2'], parent::getAttributes($names, $except));
}
behaves as nothing has been overrides - both $order->notes2
and $order->Notes2
are calculated and there is no notes2
(or Notes2
) inside the json_encode($order->getAttributes())