Score:0

Custom reference field saving empty values

ph flag

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;
  }
cn flag
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?
Lambic avatar
ph flag
@Clive added. I'll do some debugging around that on Monday unless someone offers a solution in the mean time.
Score:0
ph flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.