I need to check if a multi-valued reference field (referencing other nodes) in a node has a specific value already present to avoid duplicates.

here is the code:

$portFolioNode =  \Drupal\node\Entity\Node::load( $form_state->getValues()['portfolios'] );

//now save location id to reference field.
//$portFolioNode->field_portfolio_locations[] = ['target_id' =>  $form_state->getValues()['location_nid']  ];

// how can I check if location_nid is present already?
$portFolioNode->field_portfolio_locations[]  = $form_state->getValues()['location_nid'] ;


Any help will be appreciated greatly. Thanks!

  • Where you did that code, which class / hook, file ?
    – berramou
    Dec 21, 2019 at 16:58
  • it is in a modal ajax form's submit callback function Dec 21, 2019 at 17:00

1 Answer 1


You can check the field's values before saving:

// Id to check if exists.
$query_id = 123;

// Create array of existing ids in field.
$existing_ids = array_column($entity->my_entity_reference_field->getValue(), 'target_id');

// Check if the $query_id is not in the existing ids.
if (!in_array($query_id, $existing_ids)) {
  // In here means your $query_id doesn't already exist in the field's values.

Your code updated:

// Load portfolio node id and new location id from form_state.
$portfolioId = $form_state->getValue('portfolios');
$newLocationId = $form_state->getValue('location_nid');
if (!empty($portfolioId) && !empty($newLocationId)) {
  // Load portfolio node.
  $portfolioNode = \Drupal::entityTypeManager()

  // Get existing location ids from portfolio node.
  $existingPortfolioLocationIds = array_column($portfolioNode->field_portfolio_locations->getValue(), 'target_id');
  // If new location id is not an existing location id, add to node and save.
  if (!in_array($newLocationId, $existingPortfolioLocationIds)) {
    $portfolioNode->field_portfolio_locations[] = $newLocationId;
  • Thank you! it worked. My mind stopped working there :) Dec 21, 2019 at 21:57

Your Answer

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

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