Question

A have a lot of controllers where I must to save/create new models, it looks like this:

public Controller_Test extends Controller_Template {

    if ($post = $this->request->post()) {

        $model = ORM::factory('model');
        $model->param1 = $post['Param1'];
        $model->param2 = $post['Param26'];
        $model->param3 = $post['Param31'];
        $model->param4 = $post['Param13'];
        $model->param5 = $post['Param2'];
        $model->param6 = $post['Param35'];
        $model->param7 = $post['Param10'];
        $model->param8 = $post['Param22'];
        $model->param9 = $post['Param3'];
        $model->save();
    }    

}

Is it possible to unify (create a method) thats will save all array?

I know about $model->values($post)->create();, but still can't understand how really same it works, as u can see I have different keys of posted parameteres and this might be considered.

In many examples all the data assignemnts take place in controller, but they're really small, in my case I'll suppose to have a huge controllers with a lot of data assignment strings and it will be a bad style coding I think.

Was it helpful?

Solution

Whatever you do you need to map the key names in your $_POST variable to model property names.

$model_post_map = array(
    'param1' => 'Param1',
    'param2' => 'Param26',
    'param3' => 'Param31',
    'param4' => 'Param13',
    'param5' => 'Param2',
    'param6' => 'Param35',
    'param7' => 'Param10',
    'param8' => 'Param22',
    'param9' => 'Param3',
);
$post_model_map = array_flip($model_post_map);

function rekey($arr, $map) {
    $newarr = array();
    foreach ($arr as $k => $v) {
        if (isset($map[$k])) {
            $newarr[$map[$k]] = $v;
        }
    }
    return $newarr;
}
$modeldata = rekey($post, $post_model_map);
$model->values($modeldata);

You should name your form fields the way you do your models to reduce the impedance mismatch.

You should also use the second argument to $model->values() to restrict what a form can change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top