Question

I'm using DATAMAPPER ORM V1.8.2. I have a question for from_array method:

Firstly, I have a dropdown with *name="group_id"*

<select name="group_id" class="small-input">
      <option value="1">Guest</option>
      <option value="2" selected="selected">Member</option>
      <option value="3">Manager</option>
       <option value="4">Administrator</option>
</select>

In table users (database), I have a field named: group_id.

In controller:

....
$user->from_array($_POST, array('username', 'email', 'status', 'group_id'));
....
// then save
....

All things is OK.

But when I pass third parameter of from_array() is TRUE to save immediately, like:

$user->from_array($_POST, array('username', 'email', 'status', 'group_id', TRUE));

It can't get group_id from $_POST. Please help me, thank you.

Was it helpful?

Solution

Rename the group_id form field to the relation name in either $has_one (so probably group) or in the $has_many (probably groups) and add that name to the $fields array when calling the from_array(). So something like this:

// $_POST = array('group' => 3); // let's say this is what's coming in    
$user->from_array($_POST, array('username', 'email', 'status', 'group', TRUE));

Notice the symmetry:

  • the relation called group
  • the input parameter called group
  • the field called group

This is what's happening:

  1. You have a required on your User model's group field, which is the relation's name.
  2. You try to update and save a User instance and with an input field named group_id, however the relation is named group.
  3. Inside the array extension's from_array() method the code checks every key is its a has_one or a has_many relation to gather the related objects for the final save. Since your data have group_id but your relation is named group they don't match, the related group instance is not fetched.
  4. At the end of the from_array() save is called with the related objects gathered while looping trough the fields, in your case with no objects.
  5. The validation kicks in, and tries to _count_related() for your user's groups but it won't find the group and the "and take these with you too" second array is empty (this is where the objects gathered in step 3. would appear)
  6. The related_required validation fails and stops the save process.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top