1

I have a content type "A" (Node entity type). In it's node form (new/edit) I need to check if some fields are empty or not (which are not required in general). My first intention was to use FormState "getValue", "isValueEmpty", "hasValue" functions, but I can't figure out how to easily solve this problem:

  • Text fields has value: array("value"=> "") if they are empty, and it's not considered empty by the functions above (so I can't use them)
  • I could check by myself for isset($field['value']), but there are also file fields and entity reference fields which has a whole different "value" structure.

So what would be a clean way to achieve this?

0

I think I found what I was looking for, ContentEntityForm does it like this:

/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $this->buildEntity($form, $form_state);
$violations = $entity->validate();

All I have to do is building the entity, after that I have to just check the right field, which has already the ability to tell per fields if they are empty or not. (since each field is knowing it's type and also how to check if there is a value or not)

  • For some reason it's not working. The following exception is thrown: InvalidArgumentException: Value is not a valid entity. in Drupal\Core\Entity\Plugin\DataType\EntityReference->setValue() (line 104 of core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php). Drupal\Core\Field\FieldItemBase->writePropertyValue('entity', Array) (Line: 229) Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem->onChange('target_id', ) (Line: 178) Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem->setValue(Array, ) (Line: 69) – ssibal Jan 19 '17 at 15:08

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.