0

I have a custom entity (foo) which contains an entity reference field to another custom entity (bar). I would like to create a URL on the bar's unique page to create a new foo entity, where the entity reference is pre-populated with the correct target_id.

For example, a link to /admin/structure/my_module/foo/add?target_id=2501

Is this feature already available? Can I add something to the entity buildForm method to prepopulate my value?

class FooForm extends ContentEntityForm {
  public function buildForm(array $form, FormStateInterface $form_state) {
    //SOMETHING LIKE THIS?
    //if (isset(REQUEST::get('target_id'))) {
    //  $form_state['edit-bar-id-0-target-id'] = REQUEST::get('target_id');
    //}
    /* @var $entity \Drupal\my_module\Entity\Foo */
    $form = parent::buildForm($form, $form_state);
    $entity = $this->entity;
    return $form;
  }
}

I'm not familiar enough with the structure of the $form_state or best practices on get() to be comfortable testing this.

2
  • 1
    drupal.org/project/prepopulate ?
    – Kevin
    Commented Dec 20, 2017 at 15:51
  • Thanks for the find. However, it's alpha phase and has several outstanding bugs, including the possibility of having a major refactor in the future. Not good for production. Ignoring DI, the solution I came up with is just two lines of code. Although, I'm waiting on accepting my answer since it's possible there's a better way. Commented Dec 20, 2017 at 16:31

1 Answer 1

0

After adding dependency injection of a requestStack, this works.

/**
 * @var Symfony\Component\HttpFoundation\RequestStack
 */
protected $requestStack;

/**
 * Constructor.
 *
 * @param Symfony\Component\HttpFoundation\RequestStack $request_stack
 */
public function __construct(RequestStack $request_stack) {
  $this->requestStack = $request_stack;
}

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container) {
  return new static(
    $container->get('request_stack')
  );
}

public function buildForm(array $form, FormStateInterface $form_state)
  /* @var $entity \Drupal\my_module\Entity\Foo */
  $target_id = $this->requestStack->getCurrentRequest()->query->get('target_id');
  $this->entity->set('bar_id', $target_id);
  $form = parent::buildForm($form, $form_state);
  $entity = $this->entity;

  return $form;
}

Your Answer

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

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