Change record status: 
Project: 
Introduced in branch: 
8.x
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:

<?php
/**
 * 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:

<?php
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
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done

Comments

johnv’s picture

This is now superseded by OptionsProviderInterface