6

How do I make a field in a content entity required in Drupal 8?

I tried FieldConfigInterface::setRequired(), but it doesn't seem to work.

2
  • The field is an entity reference dropdown, if that helps Commented Sep 1, 2016 at 18:53
  • it should work, did you reinstall the module?
    – 4uk4
    Commented Sep 1, 2016 at 19:07

3 Answers 3

6

You need to use the ->setRequired(TRUE) option on the field. IE

$fields['source_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Thingy'))
      ->setDescription(t('Pick a thingy'))
      ->setSetting('target_type','thingy')
      ->setRequired(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'options_select',
        'weight' => 5,
      ))
      ->setDisplayConfigurable('form', TRUE);

You will also need to uninstall and then reinstall your module to have the change reflected in the database before this will work.

3
  • 1
    Won't an entity schema update also work?
    – mradcliffe
    Commented Sep 1, 2016 at 20:42
  • Quite possibly! Are you talking about this? drupal.org/node/2535476 Commented Sep 6, 2016 at 14:45
  • I think that's doing it manually. It should be automagic when running drush entup. I think this is the relevant code for Sql content entities - api.drupal.org/api/drupal/…
    – mradcliffe
    Commented Sep 6, 2016 at 15:22
3

If you have an existing field that is optional and you want to make it required, use code similar to the following, in example.install. (Replace example with the machine name of the module you created.)

/**
 * Make the "bar" field required.
 */
function example_update_8101(&$sandbox) {
  $entityType = 'foo';
  $fieldName = 'bar';
  $manager = \Drupal::entityDefinitionUpdateManager();
  $field = $manager->getFieldStorageDefinition($fieldName, $entityType);
  $field->setRequired(TRUE);
  $manager->updateFieldStorageDefinition($field);
}

This allows you to update a base field definition in Drupal 8. In this example, it's for a custom content entity type foo and its bar field.

Don't forget to update your baseFieldDefinitions() implementation in your entity.

0

If you need to change it programmatically then use:

/**
 * Implements hook_entity_base_field_info_alter().
 */
function mymodule_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'entitytype_id' && isset($fields['body'])) {
    $fields['body']->setRequired(TRUE);
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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