How can I prepopulate a field's value when creating a new entity

by Kevin Nowaczyk   Last Updated December 19, 2017 22:07 PM

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) {
    //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.

Tags : 8 forms entities

Related Questions

Validate File Extension In Drupal 8 Entity Form

Updated March 03, 2016 05:03 AM

Get the Entity form value from radio button

Updated July 31, 2017 21:07 PM