buildEntity example

// Ensure numeric values.     if ($form_state->hasValue('weight') && !is_numeric($form_state->getValue('weight'))) {
      $form_state->setErrorByName('weight', $this->t('Weight value must be numeric.'));
    }
  }

  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    $term = parent::buildEntity($form$form_state);

    // Prevent leading and trailing spaces in term names.     $term->setName(trim($term->getName()));

    // Assign parents with proper delta values starting from 0.     $term->parent = array_values($form_state->getValue('parent'));

    return $term;
  }

  /** * {@inheritdoc} */
$element['submit']['#button_type'] = 'primary';
    $element['delete']['#access'] = $this->entity->access('delete');

    return $element;
  }

  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
    $entity = parent::buildEntity($form$form_state);

    [$menu_name$parent] = explode(':', $form_state->getValue('menu_parent'), 2);

    $entity->parent->value = $parent;
    $entity->menu_name->value = $menu_name;
    $entity->enabled->value = (!$form_state->isValueEmpty(['enabled', 'value']));
    $entity->expanded->value = (!$form_state->isValueEmpty(['expanded', 'value']));

    return $entity;
  }

  
$form = [];
    $form_state = new FormState();
    $display->buildForm($entity$form$form_state);

    // Pretend the form has been built.     $form_state->setFormObject(\Drupal::entityTypeManager()->getFormObject($entity_type, 'default'));
    \Drupal::formBuilder()->prepareForm('field_test_entity_form', $form$form_state);
    \Drupal::formBuilder()->processForm('field_test_entity_form', $form$form_state);

    // Validate the field constraint.     $form_state->getFormObject()->setEntity($entity)->setFormDisplay($display$form_state);
    $entity = $form_state->getFormObject()->buildEntity($form$form_state);
    $display->validateFormValues($entity$form$form_state);

    $errors = $form_state->getErrors();
    $this->assertEquals('Widget constraint has failed.', $errors['name'], 'Constraint violation at the field items list level is generated correctly');
    $this->assertEquals('Widget constraint has failed.', $errors['test_field'], 'Constraint violation at the field items list level is generated correctly for an advanced widget');
  }

  /** * Gets the form errors for a given entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity * @param array $hidden_fields * (optional) A list of hidden fields. * * @return array * The form errors. */

    $form_object->setEntity($entity->reveal());

    $form = [
      '#fields' => array_keys($field_values),
      '#extra' => [],
    ];
    $form_state = new FormState();
    $form_state->setValues(['fields' => $field_values]);
    $form_state->setProcessInput();

    $form_object->buildEntity($form$form_state);
    $form_state->setSubmitted();

    // Flag one field for updating plugin settings.     $form_state->set('plugin_settings_update', 'field_plugin_settings_update');
    // During form submission, buildEntity() will be called twice. Simulate that     // here to prove copyFormValuesToEntity() is idempotent.     $form_object->buildEntity($form$form_state);
  }

}
// Alternate description for the container parent.     $form['parent'][0]['#description'] = $this->t('Containers are usually placed at the top (root) level, but may also be placed inside another container or forum.');
    $this->forumFormType = $this->t('forum container');
    return $form;
  }

  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    $entity = parent::buildEntity($form$form_state);
    $entity->forum_container = TRUE;
    return $entity;
  }

}
->onlyMethods(['getPluginCollections'])
      ->getMock();
    $entity->expects($this->atLeastOnce())
      ->method('getPluginCollections')
      ->willReturn(['key_controlled_by_plugin_collection' => NULL]);
    $this->entityForm->setEntity($entity);

    $form_state = (new FormState())->setValues([
      'regular_key' => 'foo',
      'key_controlled_by_plugin_collection' => 'bar',
    ]);
    $result = $this->entityForm->buildEntity([]$form_state);

    $this->assertSame($entity_id$result->id());
    // The regular key should have a value, but the one controlled by a plugin     // collection should not have been set.     $this->assertSame('foo', $result->get('regular_key'));
    $this->assertNull($result->get('key_controlled_by_plugin_collection'));
  }

  /** * Tests EntityForm::getEntityFromRouteMatch() for edit and delete forms. * * @covers ::getEntityFromRouteMatch */
$form['parent'][0] = $this->forumParentSelect($this->entity->id()$this->t('Parent'));

    $form['#theme_wrappers'] = ['form__forum'];
    $this->forumFormType = $this->t('forum');
    return $form;
  }

  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    $term = parent::buildEntity($form$form_state);

    // Assign parents from forum parent select field.     $term->parent = [$form_state->getValue(['parent', 0])];

    return $term;
  }

  /** * {@inheritdoc} */
  public function save(array $form, FormStateInterface $form_state) {
    
/** * {@inheritdoc} */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form$form_state);

    // Before proceeding validation, rebuild the entity to make sure it's     // up-to-date. This is needed because element validators may update form     // state, and other validators use the entity for validating the field.     // @todo remove in https://www.drupal.org/project/drupal/issues/3372934.     $this->entity = $this->buildEntity($form$form_state);

    if (isset($form['default_value']) && (!isset($form['set_default_value']) || $form_state->getValue('set_default_value'))) {
      $items = $this->getTypedData($form['#entity']);
      $items->defaultValuesFormValidate($form['default_value']$form$form_state);
    }
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    
/** * Form element #after_build callback: Updates the entity with submitted data. * * Updates the internal $this->entity object with submitted values when the * form is being rebuilt (e.g. submitted via AJAX), so that subsequent * processing (e.g. AJAX callbacks) can rely on it. */
  public function afterBuild(array $element, FormStateInterface $form_state) {
    // Rebuild the entity if #after_build is being called as part of a form     // rebuild, i.e. if we are processing input.     if ($form_state->isProcessingInput()) {
      $this->entity = $this->buildEntity($element$form_state);
    }

    return $element;
  }

  /** * Returns the action form element for the current entity form. */
  protected function actionsElement(array $form, FormStateInterface $form_state) {
    $element = $this->actions($form$form_state);

    
public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form$form_state);
    // Update the changed timestamp of the entity.     $this->updateChangedTime($this->entity);
  }

  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = parent::buildEntity($form$form_state);

    // Mark the entity as requiring validation.     $entity->setValidationRequired(!$form_state->getTemporaryValue('entity_validated'));

    // Save as a new revision if requested to do so.     if ($this->showRevisionUi() && !$form_state->isValueEmpty('revision')) {
      $entity->setNewRevision();
      if ($entity instanceof RevisionLogInterface) {
        // If a new revision is created, save the current user as         // revision author.         $entity->setRevisionUserId($this->currentUser()->id());
        
'#submit' => ['::submitForm', '::preview'],
    ];

    return $element;
  }

  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\comment\CommentInterface $comment */
    $comment = parent::buildEntity($form$form_state);
    if (!$form_state->isValueEmpty('date') && $form_state->getValue('date') instanceof DrupalDateTime) {
      $comment->setCreatedTime($form_state->getValue('date')->getTimestamp());
    }
    else {
      $comment->setCreatedTime(REQUEST_TIME);
    }
    // Empty author ID should revert to anonymous.     $author_id = $form_state->getValue('uid');
    if ($comment->id() && $this->currentUser->hasPermission('administer comments')) {
      // Admin can leave the author ID blank to revert to anonymous.       $author_id = $author_id ?: 0;
    }
'#weight' => -900,
    ];
  }

  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    // \Drupal\Core\Entity\EntityForm::buildEntity() clones the entity object.     // Keep it in sync with the one used by the section storage.     $this->setEntity($this->sectionStorage->getContextValue('display'));
    $entity = parent::buildEntity($form$form_state);
    $this->sectionStorage->setContextValue('display', $entity);
    return $entity;
  }

  /** * {@inheritdoc} */
  public function getEntityFromRouteMatch(RouteMatchInterface $route_match$entity_type_id) {
    $route_parameters = $route_match->getParameters()->all();

    return $this->entityTypeManager->getStorage('entity_view_display')->load($route_parameters['entity_type_id'] . '.' . $route_parameters['bundle'] . '.' . $route_parameters['view_mode_name']);
  }


  /** * {@inheritdoc} */
  public function buildEntity(array $form, FormStateInterface $form_state) {
    // Save field cardinality.     if (!$this->getEnforcedCardinality() && $form_state->getValue('cardinality') === 'number' && $form_state->getValue('cardinality_number')) {
      $form_state->setValue('cardinality', $form_state->getValue('cardinality_number'));
    }

    return parent::buildEntity($form$form_state);
  }

  /** * {@inheritdoc} */
  public function save(array $form, FormStateInterface $form_state) {
    $field_label = $form_state->get('field_config')->label();
    try {
      $this->entity->save();
      $this->messenger()->addStatus($this->t('Updated field %label field settings.', ['%label' => $field_label]));
      $request = $this->getRequest();
      
// Store the field whose settings are currently being edited.         $field_name = $trigger['#field_name'];
        $form_state->set('plugin_settings_edit', $field_name);
        break;

      case 'update':
        // Set the field back to 'non edit' mode, and update $this->entity with         // the new settings fro the next rebuild.         $field_name = $trigger['#field_name'];
        $form_state->set('plugin_settings_edit', NULL);
        $form_state->set('plugin_settings_update', $field_name);
        $this->entity = $this->buildEntity($form$form_state);
        break;

      case 'cancel':
        // Set the field back to 'non edit' mode.         $form_state->set('plugin_settings_edit', NULL);
        break;

      case 'refresh_table':
        // If the currently edited field is one of the rows to be refreshed, set         // it back to 'non edit' mode.         $updated_rows = explode(' ', $form_state->getValue('refresh_rows'));
        
// Change the roles array to a list of enabled roles.     // @todo Alter the form state as the form values are directly extracted and     // set on the field, which throws an exception as the list requires     // numeric keys. Allow to override this per field. As this function is     // called twice, we have to prevent it from getting the array keys twice.
    if (is_string(key($form_state->getValue('roles')))) {
      $form_state->setValue('roles', array_keys(array_filter($form_state->getValue('roles'))));
    }

    /** @var \Drupal\user\UserInterface $account */
    $account = parent::buildEntity($form$form_state);

    // Translate the empty value '' of language selects to an unset field.     foreach (['preferred_langcode', 'preferred_admin_langcode'] as $field_name) {
      if ($form_state->getValue($field_name) === '') {
        $account->$field_name = NULL;
      }
    }

    // Set existing password if set in the form state.     $current_pass = trim($form_state->getValue('current_pass', ''));
    if (strlen($current_pass) > 0) {
      
Home | Imprint | This part of the site doesn't use cookies.