1

I am currently porting a custom field module from Drupal 7 to 8. The field (Topic Access) has 3 select fields, typically about 10 to 20 items per field, and uses a custom widget. When the form is loaded, I typically insert several "inherited" items to the field before displaying it. When saving, only the items that vary from the inherited ones are actually saved to the database.

In Drupal 7, I used hook_field_load() to add these "inherited" items to the form. As explained on Dynamic/Virtual field values using computed field property classes, that hook has been removed from Drupal 8 in favor of computed field properties.

I can't see an elegant way to manipulate the list of items. I could use hook_form_alter() on the forms that contain the field to update $form['field_topic_access']['widget']. However, it would end up duplicating code from the widget and have to specifically pick out the fields by name.

Is there a hook that could manipulate the list of field items before the field is built?

3
  • In Drupal 8, the hooks to alter entity fields are only to alter fields implemented by other modules. The module implementing an entity field should not use them.
    – apaderno
    Feb 15 at 15:40
  • Thanks for the reply kiamlaluno. So in short, if not using hooks then, how do I programmatically modify the list of items in a form field? The instances of the field belong to a "tree shaped" taxonomy. The list of items in an instance of my custom field are programmatically generated from not just the field items explicitly stored in the DB against that term, but also "inherited" field items from "ancestor" terms. So, if a parent field item is changed then the "default" for that field item automatically filters thru to descendants unless the descendant has overwritten the the defaults.
    – Brett S
    Feb 15 at 22:23
  • I was referring to the hooks for altering fields, for example hook_field_widget_form_alter(). From where are the inherited values taken from?
    – apaderno
    Feb 16 at 10:03
0

What about hook_entity_prepare_form()? This simple example loaded an extra item into the form.

function mymodule_entity_prepare_form($entity, $operation, $form_state){
  if ($entity->bundle() == 'domain_groups') {
    $items = $entity->get('field_topic_access')->getValue();
    //just a hardcoded item for test purposes
    $demo_item=['topic_tid'=>'74','available_to_group'=>'1', 'publish_to_group'=>'0'];
    $items[] = $demo_item;
    $entity->set('field_topic_access', $items);
  }
}

There may be a more elegant solution but I could use this hook to show my inherited items and hook_entity_presave() to remove inherited values before saving.

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.