Creating a Drupal 8 Route to a User Page with Dynamic User Object
It took me some time to figure out the right combination of properties to make this work.
My goal was to create a form that lives at /user/UID/photo (think /user/1/edit).
I wanted the user object to be passed into the form as an argument.
Here’s the mymodule.routing.yml file:
1 2 3 4 5 6 7 8 9 10 11 12 |
mymodule.profile_photo: path: '/user/{user}/photo' defaults: _form: '\Drupal\mymodule\Form\ProfilePhoto' _title: 'ProfilePhoto' options: parameters: user: type: entity:user requirements: user: \d+ _entity_access: 'user.update' |
Here’s the src/Form/ProfilePhoto.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?php namespace Drupal\mymodule\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; /** * Class ProfilePhoto. * * @package Drupal\mymodule\Form */ class ProfilePhoto extends FormBase { /** * {@inheritdoc} */ public function getFormId() { return 'profile_photo'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $user = NULL) { // Build the form here return $form; } /** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { parent::validateForm($form, $form_state); } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // Do something with the results } } |