0

I have a custom form in which referenced field needs to be displayed.

Here is the structure: Content-Type: Project

Reference Field in Project Content-Type: POD Details(Fields- MemberName: User reference, MemberRole: Reference taxonomy term)

How can we get fields for Project content type with its widget into custom form?

Here is what I have tried:

class ProjectFormAlter extends FormBase {

/**
 * {@inheritdoc}
 */
public function getFormId() {
    return 'member_form';
}

/**
 * {@inheritdoc}
 */
public function buildForm(array $form, FormStateInterface $form_state) {
    $entity = \Drupal::entityManager()->getStorage('paragraph')->create(['type' => 'pod_infromation']);
    $form_state->set('paragraph', $paragraph);
    $form_display = \Drupal::entityManager()->getStorage('entity_form_display')->load('paragraph.pod_infromation.default');
    $form_state->set('form_display', $form_display);
    foreach ($form_display->getComponents() as $name => $component) {
        $widget = $form_display->getRenderer($name);
        if (!$widget) {
            continue;
        }
        $items = $entity->get($name);
        $items->filterEmptyItems();

        $form[$name] = $widget->form($items, $form, $form_state);

        $form[$name]['#access'] = $items->access('edit');
        $form[$name]['#access'];
        $form['#parents'] = [];
    }
    return $form;
}

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

}

/**
 * {@inheritdoc}
 */
public function submitForm(array &$form, FormStateInterface $form_state) {
    }

}

Also, I am getting an error with above code as:

TypeError: Argument 1 passed to Drupal\Core\Field\WidgetBase::getWidgetState() must be of the type array, null given

Any suggestion or roadmap that I can get the node field into my custom form.

Links which I followed for this are below.

  1. https://www.webomelette.com/how-render-entity-field-widgets-inside-custom-form-drupal-8
  2. https://hotexamples.com/examples/drupal.core.field/FieldItemListInterface/setValue/php-fielditemlistinterface-setvalue-method-examples.html
  3. https://www.foreach.be/blog/how-select-fields-entities-forms
  4. https://www.drupal.org/forum/support/module-development-and-code-questions/2015-09-05/drupal-8-equivalent-to-field_attach#comment-11278197

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.