Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

array_merge with getAttributes()

I'm creating the following form element:

$notify = new Check('notify', [

    'value' => (int)$user->AccountsSettings->product_notify,
    'class' => 'form-control',
]));

if((bool)$user->AccountsSettings->product_notify)
    array_merge($notify->getAttributes(), array('checked' => ''));

But array_merge seems not working.

What I'm missing?? Or there is more simpler solution??

Thanks!



6.2k
Accepted
answer
edited Feb '17

I guess your product_notify property can be either 1 or 0, if that's right you can do it simpler, with ternary operator inside attributes array.

$notify = new Check('notify', [
    'checked' => ($user->AccountsSettings->product_notify == 1)?1:null;
    'class' => 'form-control',
]));

PS: To use merge_array properly I guess you should do $notify->getAttributes()->toArray()

Aaaaaahhh, my first try was ternary operator, which I set to return either true or false and checkbox was allways checked. Didn't tried to use null!

That solved my problem!

P.S.: $notify->getAttributes() returns pure array, so no need use of toArray().

P.S.S.: why array_merge doesn't work - mysterious. Maybe of protected _attributes.

Thanks!!