0

I've created a custom field based on entity reference field but the target_id it saves comes from an external system.

I have the field type, field widget and autocomplete element defined and working and the correct values are being saved to the associated database table for valid values.

The bit I'm stuck on is that if the field is left blank it still saves a record to the database but with an empty target_id. How should I stop it doing that?

Here's my implementation of isEmpty(), which I cribbed from the EntityReference field definition. I'm guessing this is the culprit but I'm not sure how to fix it:

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $target_id = isset($this->target_id) ? $this->target_id : NULL;
    if ($target_id !== NULL) {
      return FALSE;
    }
    return TRUE;
  }
2
  • Could you post your implementation of isEmpty()? If you don't have one, is the base implementation (EntityReferenceItem::isEmpty()) compatible with the changes your class makes?
    – Clive
    Dec 17, 2021 at 20:53
  • @Clive added. I'll do some debugging around that on Monday unless someone offers a solution in the mean time.
    – Lambic
    Dec 18, 2021 at 18:37

1 Answer 1

0

isEmpty() was the culprit here, for some reason that I don't fully understand $this->target_id was set to an empty string instead of NULL, so changing if ($target_id !== NULL) to just if ($target_id) fixed it.

Thanks @Clive for the clue.

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.