简体   繁体   中英

Saving multiple new relations with validation (Codeigniter/DataMapper)

I am building an application with codeigniter that involves adding a "carer" with multiple telephone numbers to a database. From the UI side of things, there is an add button next to each telephone field that uses some javascript magic to clone itself in order for the user to input another number. When the form is submitted, the telephone numbers are submitted as an array.

I have two models setup: carer and carer_telephone . Each model has it's own respective table.

I have been racking my brains for a way that I can get datamapper to validate all the relations before saving them. For example at the moment, only the validation errors for the carer fields are displayed, none for the carer_telephone fields.

Also, I'm not sure if this is the most memory efficient way of dealing with this ie creating a new carer_telephone object for every number.

This must be a common setup for many applications but I can't seem to find any documentation on the subject. I am looking for the most standard way of doing this with regards to DataMapper.

The controller so far

function add() {

    //Create carer object
    $c = new carer();

    //Create carer telephone object
    $t = new carer_telephone();

    //Form submitted
    if($this->input->post('add_carer')) {

        //Set carer data
        $c->title           = $this->input->post('title');
        $c->first_name      = $this->input->post('first_name');
        $c->family_name = $this->input->post('family_name');
        $c->display_name    = $this->input->post('display_name');
        $c->date_of_birth   = $this->input->post('date_of_birth');
        $c->email_address   = $this->input->post('email_address');
        $c->street_address  = $this->input->post('street_address');
        $c->town            = $this->input->post('town');
        $c->county          = $this->input->post('county');
        $c->postcode        = $this->input->post('postcode');

        //Set and save telephones
        foreach($this->input->post('telephone') as $tel) {
            $t = new carer_telephone();
            $t->type    = 'test';
            $t->number  = $tel;
            $c->save($t);
        }

    }

    //Store carer object
    $this->_data['content']['carer'] = $c;

    //Load view
    $this->load->view('carers/add',$this->_data);

}

Any help on this would be greatly appreciated. Even just a link to an example where somebody has worked on this situation.

Best regards, Dan

DataMapper附带有一个数组扩展,可能对您有用http ://datamapper.wanwizard.eu/pages/extensions/array.html-使您可以将数组数据保存到数据库等。

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