2

I am setting attributes on my record using a models' attributes (that has validated successfully). I cannot figure out why the values aren't assigned. I can manually assign each one but that's redundant.

// Set attributes
// Massive assignment will only be made for fields which have passed some explicit validation rule.
if ($model->validate())
{
    $purchaseRecord->setAttributes($model->getAttributes());
    var_dump($model->snipInvoiceNumber); // works
    var_dump($purchaseRecord->snipInvoiceNumber); // null value
    $purchaseRecord->snipInvoiceNumber = $model->snipInvoiceNumber; // works
} 

UPDATE: Per comments on this thread I looped through and set the attributes individually. Anyone have insight on why setAttributes didn't work? Save contact form data to database

This is what I used instead of setAttributes (plural).

foreach ($model->getAttributes() as $key => $value ) {
    $purchaseRecord->setAttribute($key, $value);
}
1
  • It would seem while several of these columns will not be assigned values successfully a handful of others are working fine. Not sure if the issue is related but the ones working are all ones defined in my record defineRelations(). Commented Mar 14, 2018 at 18:06

1 Answer 1

3

There is a second parameter in your setAttributes() function. This parameter is true per default and checks if the attribute is safe so you either have to declare all safe attributes in your records rules or you set the parameter to false.

3
  • Thank you Robin! That was precisely the issue! I'll have to learn more about what the 'safe' rules are but in the meantime false fixed it up. Commented Mar 14, 2018 at 21:39
  • The craft docs on setAttributes did not have the value but looking at yii docs I see it yiiframework.com/doc/api/1.1/CModel#setAttributes-detail Commented Mar 14, 2018 at 21:47
  • Don't get me wrong, I love Craft and I love to work with it but the online documentation is pretty bad. Most things are well explained in the code, so you should look there first but nearly 70% is not even mentioned in the online documentation. As for the safe attributes, you can learn more about that here yiiframework.com/doc-2.0/… Commented Mar 14, 2018 at 22:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.