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.
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.
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.
drush entup
. I think this is the relevant code for Sql content entities - api.drupal.org/api/drupal/…
Commented
Sep 6, 2016 at 15:22
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.
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);
}
}