How to insert multi select records?

How to insert multi select records?

by Mian Omer -
Number of replies: 2

Hi,

I want to insert multi select list courses in the courseid column in separate table, a custom functionality i am working on.

Here's the code:

$options = array();
$allcourses = coursecat::get(0)->get_courses(array('recursive' => true));
foreach ($allcourses as $course) {$options[$course->id] = $course->fullname;}
$mform->addElement('select', 'courseid', get_string('course'), $options)->setMultiple(true);

i fail to insert list of courses in courseid column. Any help will be much appreciated.

Thanks

 

 

Average of ratings: -
In reply to Mian Omer

Re: How to insert multi select records?

by Chris Wharton -
Hi Mian

The form data is return as an object:
object(stdClass)[1204]
  public 'courseid' => 
    array (size=2)
      0 =>  '3' (length=1)
      1 =>  '2' (length=1)
  public 'planid' =>  '0' (length=1)
  public 'username' =>  'admin' (length=5)
  public 'submitbutton' =>  'submit' (length=6)
The selected courses are in an array, which can't be directly inserted into the database. You need to process this data first.
This is often done with an explicitly created object for insertion into the database. For example:
$todb = new stdClass();
$todb->courses = implode(',', $formdata->courseid);
$todb->username = $formdata->username;
$DB->insert_record('table', $todb);
There are examples of this throughout core Moodle code, which you should examine to figure out ways to improve your code.
In reply to Mian Omer

Re: How to insert multi select records?

by sarendar vennapureddy -

Hi Omer,

Add the multiple select field in 'edit_form.php'. Selected fields fetch from database.


$partnerRecords=$DB->get_records('partner_logo');                    // get records from database
         
    foreach($partnerRecords as $partnerRecord)
    { 
        $multipartner[$partnerRecord->id] = $partnerRecord->partner_name;
                  }
                 
 $select = $mform->addElement('select','partner_logo', get_string('partnername'),$multipartner);
 $select->setMultiple(true);
 $mform->addHelpButton('partner_logo', 'partnername');


These selected values gathered else if condition in 'edit.php' file 

$editform = new course_edit_form(null, $args);
if ($editform->is_cancelled()) {
    // The form has been cancelled, take them back to what ever the return to is.
    redirect($returnurl);
} else if ($data = $editform->get_data()) {         /// code apper upto here in file
    $set = $data->partner_logo;            
    $setd = implode(',',$set);                      // implode ids with comma
    $data->partner_logo = $setd;            // stored in database table.