I'm trying to display the user edit form on a custom page with limited fields. Submitting my form works well, but if I have the Administrator role, roles are reset. I don't understand why this is happening.
This is the routing file custom_user_profile.routing.yml.
my_module.default_controller_view:
path: '/my_module'
defaults:
_controller: '\Drupal\my_module\Controller\DefaultController::view'
_title: 'Account'
requirements:
_user_is_logged_in: 'TRUE'
options:
no_cache: 'TRUE'
In the controller DefaultController.php I have
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\user\Entity\User;
class DefaultController extends ControllerBase
{
public function view()
{
$user = User::load(\Drupal::currentUser()->id());
$html = '';
$html .= '<p>Current email is ' . $user->mail->value . '</p>';
$data['html'] = [
'#type' => 'markup',
'#markup' => $html,
];
$user = User::load(\Drupal::currentUser()->id());
$formObject = \Drupal::entityTypeManager()
->getFormObject('user', 'default')
->setEntity($user);
$form = \Drupal::formBuilder()->getForm($formObject);
$data['form'] = [
'form' => $form,
];
return $data;
}
}
In the my_module.module I have following code.
use Drupal\Core\Form\FormStateInterface;
function my_module_theme($existing, $type, $theme, $path)
{
$templates = array(
'my_module_about_form' => [
'render element' => 'form',
],
);
return $templates;
}
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
if ($form_id == 'user_form') {
$form['#theme'] = ['my_module_about_form'];
}
}
In the template file my-module-about-form.html.twig I have the following lines.
{{ form.timezone }}
{{ form.form_build_id }}
{{ form.form_token }}
{{ form.form_id }}
{{ form.actions.submit }}