1

Is there a way to automatically/dynamically set all the attributes for a datamapper object instead of assigning them one for one?

So my form field names are exactly the same as the attributes from the datamapper model.

So is there a shorter way to do this:

function add() {
 if( $this->input->post('client-add')) {
 $c = new Client();
 $c->name = $this->input->post('name');
 $c->email = $this->input->post('email');
 // and so on for about 20 more properties

 $c->save();
  }}
Simon
  • 1,643
  • 7
  • 30
  • 61

2 Answers2

1

You should simply run it in a loop:

function add() {
    if ( $this->input->post('client-add') ) {
        $c = new Client();
        $fields = array('name', 'email', 'and', 'so', 'on');

        foreach ( $fields as $field ) {
            $c->$field = $this->input->post( $field );
        }

        $c->save();
    }
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
1

well, you allways can use the post without any parameter, like:

function add()
{
    if($this->input->post('client-add')) {
        $c = new Client($this->input->post());
    }
    $c->save();
}

The main problem that you can have is that the client loader also gets the 'client-add' field in the array. But you should control the inputs in the class loaders.

Patroklo
  • 516
  • 4
  • 15
  • 1
    I ended up with installing the arrays helper from codeigniter datamapper and ended up doing $c = from_array($this->input->post()); $c->save(); – Simon Mar 26 '12 at 22:03