1

In a MenuLinkContent entity I've a list_string field populated with a $key => $value array of a custom config entity. When I add or delete a config entity the values in my field are not updated until I rebuild the cache.

I think I should set a cache tag, but I can not figure out where I should add the tag and which tag should I use.

Edit: The array is created in a static method on my entity class.

public static function getConfigList() {

  $entities = SvgIcon::loadMultiple();
  $config_list = array();

  /** @var SvgIconInterface $entity */
  foreach ($entities as $entity) {
    $config_list[$entity->get('id')] = $entity->get('label');
  }

  return $config_list;
}

The field is defined via hook_entity_base_field_info().

function svg_icon_menu_link_entity_base_field_info(EntityTypeInterface $entity_type) {

  $fields = array();

  if ( $entity_type->get('id') !== 'menu_link_content' ) {
    return $fields;
  }

  $fields['svg'] = BaseFieldDefinition::create('list_string')
    ->setLabel('SVG sprite')
    ->setDescription('Select the SVG sprite file.')
    ->setSettings(array(
      'allowed_values' => SvgIcon::getConfigList()
    ))
    ->setDisplayOptions('form', array(
      'type' => 'select',
      'weight' => 0,
      'settings' => array(
        'display_label' => TRUE
      )
    ));

  return $fields;
}
  • How are you defining that list of key/value options? – Berdir Mar 2 '17 at 19:17
  • I've edited my question to get proper formatting. – Matteo Palazzo Mar 3 '17 at 8:54
1

List fields support an allowed_values_callback setting, if you use that, then you don't need to worry about cache invalidation.

See https://api.drupal.org/api/drupal/core!modules!options!options.api.php/function/callback_allowed_values_function/8.2.x and

  • Thanks Berdir. It took me a while to understand how to use that callback. – Matteo Palazzo Mar 8 '17 at 10:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.