简体   繁体   中英

changing object in loop in Datamapper ORM

I'm trying to save a long form in Codeigniter's Datamapper. I'm able to save the form if I pass the value like this

$t->brandName = $this->input->post('brandName');  
$t->specialNotes = $this->input->post('specialNotes');
$t->name = $this->input->post('name');

Now if I call save method it works

 $t->save();

Since the form is big I tried to add object values in foreach

 $a = get_object_vars($t);
 foreach ($a['stored'] as $k => $val){
      $t->$k = $this->input->post("$k"); 
 }

however if I call the $t->save() it doesn't work.

I'm not sure what $a['stored'] represents, but it's nothing that's default in Datamapper.

Why don't you do it the opposite way, looping through the post keys?

foreach ($_POST as $key => $val)
{
    $t->$key = $this->input->post($key); 
}
$t->save();

Note: Any columns that don't exist will just be ignored by Datamapper.


I actually wrote a Datamapper extension for this:

class DM_Data {

    function assign_postdata($object, $fields = NULL)
    {
        // You can pass a different field array if you want
        if ( ! $fields)
        {
            $fields = $object->validation;
        }
        foreach ($fields as $k => $data)
        {
            $rules = isset($data['rules']) ? $data['rules'] : array();

            if ( ! isset($_POST[$k])) continue;

            // Cast value to INT, usually for an empty string.
            if (in_array('integer', $rules))
            {
                $object->$k = (integer) $_POST[$k];
            }
            // Do other manipulation here if desired
            else
            {
                $object->$k = $_POST[$k];
            }

        }
        return $object;
    }

}

You can use $t->assign_postdata()->save() , and optionally pass an array of fields to update to the function (in the datamapper validation format). However, I forget why I use that... but I removed some of the custom stuff. This should be useful for you if you are doing this a lot. It definitely saves me time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM