By klausi on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.x
Issue links:
Description:
Data types (fields) that want to limit values to a list of available options have to implement the \Drupal\Core\TypedData\AllowedValuesInterface. Validation constraints will be automatically added to detect values that are not suitable. See also the documentation on the class and its methods.
Drupal 7:
/**
* Implements hook_options_list().
*/
mymodule_options_list() {
return array(
t('First group') => array(
0 => t('Zero'),
),
t('Second group') => array(
1 => t('One'),
2 => t('Two'),
),
3 => t('Three'),
);
}
Drupal 8:
class MyModuleData implements AllowedValuesInterface {
/**
* {@inheritdoc}
*/
public function getPossibleValues(AccountInterface $account = NULL) {
return array(0, 1, 2, 3);
}
/**
* {@inheritdoc}
*/
public function getPossibleOptions(AccountInterface $account = NULL) {
return array(
t('First group') => array(
0 => t('Zero'),
),
t('Second group') => array(
1 => t('One'),
2 => t('Two'),
),
3 => t('Three'),
);
}
/**
* {@inheritdoc}
*/
public function getSettableValues(AccountInterface $account = NULL) {
if ($account && $account->hasPermission('set mymodule data')) {
return array(0, 1, 2, 3);
}
return array(0, 3);
}
/**
* {@inheritdoc}
*/
public function getSettableOptions(AccountInterface $account = NULL) {
if ($account && $account->hasPermission('set mymodule data')) {
return $this->getPossibleOptions();
}
return array(
t('First group') => array(
0 => t('Zero'),
),
3 => t('Three'),
);
}
}
Impacts:
Module developers
Comments
OptionsProviderInterface
This is now superseded by OptionsProviderInterface