5

I have a my_job_board.routing.yml:

my_job_board.user_register_form:
  path: '/my-job-board/register/{user_role}'
  defaults:
    _form: '\Drupal\my_job_board\Form\UserRegisterForm'
    _title: 'Register for My Job Board'
  requirements:
    _access_user_register: 'TRUE'

(this is nearly identical to the route defined at line 56 of User module's user.routing.yml),

and a src/Form/UserRegisterForm.php:

<?php

namespace Drupal\my_job_board\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\RoleInterface;

class UserRegisterForm extends FormBase {

  public function getFormId() {
    return 'my_job_board_user_register';
  }

  public function buildForm(array $form, FormStateInterface $form_state, RoleInterface $user_role = NULL) {
    var_dump($user_role);
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

}

(my buildForm() has an identical signature to that of Drupal\user\Form\UserPermissionRoleSpecificForm which corresponds to the route I mentioned above).

Visiting /my-job-board/register/employer gives me the following error:

TypeError: Argument 3 passed to Drupal\my_job_board\Form\UserRegisterForm::buildForm() must be an instance of Drupal\user\RoleInterface, string given in Drupal\my_job_board\Form\UserRegisterForm->buildForm() (line 31 of modules/custom/my_job_board/src/Form/UserRegisterForm.php).

If i visit the same path with string instead of RoleInterface as the 3rd typehint for buildForm(), I see the output of var_dump($user_role): string(8) "employer".

Why am I not getting a RoleInterface passed into buildForm()? What am I missing?

1 Answer 1

5

It seems entity routes (beginning entity.), like those in the user module, get the Drupal\Core\ParamConverter\EntityConverter converter automatically applied; other routes don't.

You should be able to apply it yourself easily enough:

my_job_board.user_register_form:
  path: '/my-job-board/register/{user_role}'
  defaults:
    _form: '\Drupal\my_job_board\Form\UserRegisterForm'
    _title: 'Register for My Job Board'
  requirements:
    _access_user_register: 'TRUE'
  options:
    parameters:
      user_role:
        type: entity:user_role

See Parameter upcasting in routes for more info.

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.