本文整理汇总了PHP中field::cast_data方法的典型用法代码示例。如果您正苦于以下问题:PHP field::cast_data方法的具体用法?PHP field::cast_data怎么用?PHP field::cast_data使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类field
的用法示例。
在下文中一共展示了field::cast_data方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: set_for_context_and_field
/**
* Sets the custom field data for a specified context and field.
*
* @param object $context the context to set the data for
* @param field $field the field object to set the data for
* @param mixed $data a single value or an array depending on whether
* $field is multivalued or not
* @param string $plugin
* @return boolean whether or not the data was modified
*/
public static function set_for_context_and_field($context, field $field, $data)
{
global $DB;
$data = $field->cast_data($data);
// ELIS-3829
if ($context) {
$contextid = $context->id;
} else {
$contextid = null;
}
$data_table = $field->data_table();
// FIXME: check exclude, unique, etc
if ($field->multivalued) {
if (!is_array($data)) {
$data = array($data);
}
// find what data already exists (excluding default value if we have a context, including if we don't)
$include_default = is_null($contextid) ? true : false;
$records = self::get_for_context_and_field($context, $field, $include_default);
$records = $records ? $records : array();
$todelete = array();
$existing = array();
foreach ($records as $rec) {
$val = $field->cast_to_type($rec->data);
if (in_array($val, $data)) {
$existing[] = $val;
} else {
$todelete[] = $rec;
}
}
// delete obsolete data
foreach ($todelete as $rec) {
$rec->delete();
}
// add new data
$toadd = array_diff($data, $existing);
foreach ($toadd as $value) {
$fielddatatype = "field_data_{$field->data_type()}";
$rec = new $fielddatatype();
$rec->contextid = $contextid;
$rec->fieldid = $field->id;
$rec->data = $value;
$rec->save();
}
return !empty($toadd) || !empty($todelete);
} else {
if ($rec = $DB->get_record($data_table, array('contextid' => $contextid, 'fieldid' => $field->id))) {
// $fielddata = new field_data($rec, $field->data_type());
$fielddatatype = "field_data_{$field->data_type()}";
$fielddata = new $fielddatatype($rec);
if ($data === null) {
$fielddata->delete();
return true;
}
if ($fielddata->data == $data) {
return false;
}
$fielddata->contextid = $contextid;
// needed, or else NULL becomes 0
$fielddata->data = $data;
$fielddata->save();
return true;
} else {
if ($data !== null) {
$fielddatatype = "field_data_{$field->data_type()}";
$rec = new $fielddatatype();
$rec->contextid = $contextid;
$rec->fieldid = $field->id;
$rec->data = $data;
$rec->save();
return true;
}
}
}
}