Drupal 8 update entity field collection fields programmatically

Submitted by august on Tue, 07/25/2017 - 23:59
  /**
   * Responds to entity PATCH requests.
   *
   * @param \Drupal\Core\Entity\EntityInterface $original_entity
   *   The original entity object.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity.
   *
   * @return \Drupal\rest\ModifiedResourceResponse
   *   The HTTP response object.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   */
  public function patch(EntityInterface $original_entity, EntityInterface $entity = NULL) {
    
    ....
    
    foreach ($entity->_restSubmittedFields as $field_name) {
      $field = $entity->get($field_name);

      ....

      if (!$original_entity->get($field_name)->access('edit')) {
        throw new AccessDeniedHttpException("Access denied on updating field '$field_name'.");
      }

      // handle the field collection type field.
      if ($field->getFieldDefinition()->get('field_type') == 'field_collection') {
        $original_values = $original_entity->$field_name->getValue();
        $original_entity->set($field_name, []);
        if (!empty($original_values)) {
          foreach ($original_values as $original_value) {
            $original_fc = FieldCollectionItem::load($original_value['value']);
            if ($original_fc) {
              $original_fc->delete();
            }
          }
        }

        $field_values = $field->getValue();
        foreach ($field_values as $key => $values) {
          $fc = FieldCollectionItem::create([
            'field_name' => $field_name
          ]);
          foreach ($values as $name => $value) {
             $fc->set($name, $value);
          }
          $fc->setHostEntity($original_entity);
          $fc->save();
        }
      }
      else {
        $original_entity->set($field_name, $field->getValue());
      }
    }

    ....
  }

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.