DrupalEasy: Using ECA to pre-populate a form field from a query string variable

There’s no doubt that the ECA module is changing the way Drupal sites are built  – at least for those of us that use it regularly. I recently used it to pre-populate a form field on a node add page and it turned out to be easier than I figured it would be.

The task was to pass the value I wanted to pre-populate into the form via a query string variable. Something like:

https://mysite.ddev.site/node/add/article?myvalue=1

On the node add page, there exists an entity reference field whose value I’d like to pre populate with a value of 1 (myvalue). 

Screenshot showing the task.

Modules required

Modules used in the following solution are:

  • Token
  • BPMN.iO for ECA
  • ECA BPMN (part of ECA module)
  • ECA Form (part of ECA module)
  • ECA UI (part of ECA module)
  • ECA Core (part of ECA module)

The Token module is required because the ECA model will access the myvalue query string value via a token. 

ECA components

The ECA Form module (a sub-module of ECA) provides the necessary components to achieve the goal. 

Screenshot of Build Form component configuration.

The Build Form event and the Form Field: Set Default Value task components are all that are needed. Configuration as follows:

Build Form event

  • Restrict by form id: node-article-form
  • Restrict by entity type ID: node
  • Restrict by entity bundle: article

Screenshot of form field configuration.Form Field: Set Default Value task 

  • Field name: field_linked_content
  • Value: [current-page:query:myvalue]
     

Once the model is created and saved, enjoy the fruits of your labor!

Screenshot showing final result.

Other potential solutions

Was ECA the only way to complete this task? Certainly not. A small custom module could be written to achieve the same goal. In addition, there’s the Pre-populate and Entity prepopulate modules.

Why use an ECA-based solution then? If you’re already using ECA on the project for something else, then I’d recommend this type of ECA solution in order to avoid adding an additional contrib module just for your pre-populating needs.