This article demonstrates building a multi-step form in Drupal 8 using two separate forms and Drupal's core temporary data storage. Let's streamline the explanation and improve the flow.
Key Concepts:
PrivateTempStore
ensures data persistence across multiple requests, enabling the multi-step process.Implementation Details:
The solution involves:
MultistepFormBase.php: This abstract base class handles common tasks:
PrivateTempStoreFactory
, SessionManagerInterface
, and AccountInterface
.PrivateTempStore
to store form data (multistep_data
key).saveData()
): A placeholder for the actual data saving logic (implementation depends on your specific needs).deleteStore()
): Removes stored data after successful submission.MultistepOneForm.php: The first form:
MultistepFormBase
.name
and email
.PrivateTempStore
for pre-population.demo.multistep_two
upon submission.MultistepTwoForm.php: The second form:
MultistepFormBase
.age
and location
.PrivateTempStore
.demo.multistep_one
.saveData()
from the base class upon submission and then redirects.demo.routing.yml: Defines routes for demo.multistep_one
and demo.multistep_two
, associating them with the respective form classes.
Illustrative Screenshots:
Code Snippets (Illustrative):
(MultistepFormBase.php - Excerpt):
protected function saveData() { // Save data (e.g., create a configuration entity) $this->deleteStore(); drupal_set_message($this->t('Form saved!')); }
(MultistepOneForm.php - Excerpt):
$form['name'] = [ '#type' => 'textfield', '#title' => $this->t('Your name'), '#default_value' => $this->store->get('name') ?: '', ];
Conclusion:
This approach provides a clean and efficient way to create multi-step forms in Drupal 8, leveraging the power of the PrivateTempStore
for cross-request data management. The use of an abstract base class promotes code organization and reusability. This structure can easily be extended to accommodate more steps. The FAQ section is omitted here for brevity, as the article body already covers the essential aspects.
The above is the detailed content of How to Build Multi-step Forms in Drupal 8. For more information, please follow other related articles on the PHP Chinese website!