Course format date_selector

Re: Course format date_selector

by Artur Welp -
Number of replies: 0

Wow, this was kind hard. Things went a little more deep than i expected. :p


So first, you need to recover the data from the database, in this case, it is not automatic. I use this SQL to bring it.


//In the begin of the function, load database and course data

//global $DB, $COURSE;

// Some other code..

$sql = "SELECT *
          FROM {course_format_options}
          WHERE courseid = ? AND
                        name = ?";
              
$args = array($COURSE->id, 'enddate');



With the data, now we need to load a instance of the moodle calendar and past the value to it.

$my_date = 0;
if($cfo = $DB->get_record_sql($sql, $args)){
    $calendartype = \core_calendar\type_factory::get_calendar_instance();
    $currentdate = $calendartype->timestamp_to_date_array($cfo->value);
    $my_date = array(
         'day' => $currentdate['mday'],
         'month' => $currentdate['mon'],
         'year' => $currentdate['year']);
}
 
With this, we have a formatted array, with the date in Moodle format.
Now, we need to add a value in the courseformatoptions. We will define the default value as the formated array listed above and the type PARAM_RAW. Date is not a defined type, so let it be as it is. With RAW.

'my_date_field'=> array(
'default' => $my_date,
'type' => PARAM_RAW,
),

Now, we also need to define this value in the courseformatoptionsedit array.

    'my_date_field' => array(
'label' => new lang_string('key_value', 'string_file'),
'element_type' => 'date_selector',
'element_attributes' => array(
array('optional' => true)
)
),


This solved my problem for now. I will attach a zip with a example.