Basic CRUD operations with Codeigniter and Datamapper

1.9k views Asked by At

I'm totally new at Codeigniter and Datamapper and i have a very fundamental question that can't be answered by myself searching in the documentation.

I have a very simple database with 3 tables:

 student
 courses
 student_courses

Now, i understand how works the relationships, do CRUD operation with CI, etc.....but how can i stablish the relationship between students and courses using a form that have to be fill it by an user?

Imagine i have a form where an user have to fill the name of an student and select two or more courses...how the controller have to look like?

Thank you very much

1

There are 1 answers

1
TerryMatula On

First off, using Datamapper with CI, it will be easier if you named the 'student' table 'students'. Then the join table 'courses_students' (thanks Shauna). Your models would then be 'student' and 'course'.

The controller for the form could be something like this (ideally, you'd put the form in the View):

function form() {
     echo "<form method='post' action='submitForm'>";
     echo "<input type='text' name='student_name'>";
     echo "<select name='courses[]' multiple='multiple'>";
     $c = new Course();
     $c->get();
     foreach($c as $course) {
         echo "<option value='{$course->id}'>{$course->name}</option>";
     }
     echo "</select>";
     echo "<input type='submit' value='Submit'>";
}

The controller to submit the form (without validation or XSS checks):

function submitForm() {
     $s = new Student();
     $s->name = $this->input->post('student_name');
     // an initial save to the Students table, might be omitted
     $s->save();
     $course_array = $this->input->post('courses');
     // loop through the Courses, get them from db, and save the relationship
     foreach($course_array as $k=>$v) {
          $c = new Course($v);
          $s->save($c);
     }
}

A couple of notes: this is a quick, dirty example. Doing those multiple saves could slow things down if there are many Courses select, and there's probably a way using Datamapper to save the array in one statement, but I'd need to research that.