validateReferenceableEntities example

// Add violations on deltas with a target_id that is not valid.     if ($target_ids) {
      // Get a list of pre-existing references.       $previously_referenced_ids = [];
      if ($value->getParent() && ($entity = $value->getEntity()) && !$entity->isNew()) {
        $existing_entity = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
        foreach ($existing_entity->{$value->getFieldDefinition()->getName()}->getValue() as $item) {
          $previously_referenced_ids[$item['target_id']] = $item['target_id'];
        }
      }

      $valid_target_ids = $handler->validateReferenceableEntities($target_ids);
      if ($invalid_target_ids = array_diff($target_ids$valid_target_ids)) {
        // For accuracy of the error message, differentiate non-referenceable         // and non-existent entities.         $existing_entities = $this->entityTypeManager->getStorage($target_type_id)->loadMultiple($invalid_target_ids);
        foreach ($invalid_target_ids as $delta => $target_id) {
          // Check if any of the invalid existing references are simply not           // accessible by the user, in which case they need to be excluded from           // validation           if (isset($previously_referenced_ids[$target_id]) && isset($existing_entities[$target_id]) && !$existing_entities[$target_id]->access('view')) {
            continue;
          }

          
// Check that the referenced entities are valid, if needed.       if ($element['#validate_reference'] && !empty($value)) {
        // Validate existing entities.         $ids = array_reduce($valuefunction D$return$item) {
          if (isset($item['target_id'])) {
            $return[] = $item['target_id'];
          }
          return $return;
        });

        if ($ids) {
          $valid_ids = $handler->validateReferenceableEntities($ids);
          if ($invalid_ids = array_diff($ids$valid_ids)) {
            foreach ($invalid_ids as $invalid_id) {
              $form_state->setError($elementt('The referenced entity (%type: %id) does not exist.', ['%type' => $element['#target_type'], '%id' => $invalid_id]));
            }
          }
        }

        // Validate newly created entities.         $new_entities = array_reduce($valuefunction D$return$item) {
          if (isset($item['entity'])) {
            $return[] = $item['entity'];
          }
Home | Imprint | This part of the site doesn't use cookies.