I'm trying to render limited user edit form on custom page using Drupal Controller. In the routing.yml I defined _controller, I do not want to use _form.
I want to display on the form e.g. only timezone field, but not the rest. And I'm not able to achieve it. I can render this field, other fields like form_build_id, form_id, form_token
But form html tag is not rendered at all.
It works only if I display the whole form with {{ form.form }}
.
This is the content of the files I am using.
my_module.info.yml
name: 'My module'
type: module
description: 'my module'
core_version_requirement: ^8.8 || ^9
my_module.routing.yml
my_module.mymodule_controller_view::
path: '/my-module'
defaults:
_controller: '\Drupal\my_module\Controller\MymoduleController::view'
_title: 'My module'
requirements:
_permission: 'access content'
my_module.module
function my_module_theme($existing, $type, $theme, $path)
{
$templates = array(
'my_module_form' => [
'render element' => 'form',
],
);
return $templates;
}
MymoduleController.php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\user\Entity\User;
class MymoduleController extends ControllerBase
{
public function view()
{
$data['header'] = [
'#type' => 'markup',
'#markup' => '<h1>HEADER</h1>',
];
$user = User::load(\Drupal::currentUser()->id());
$formObject = \Drupal::entityTypeManager()
->getFormObject('user', 'default')
->setEntity($user);
$form = \Drupal::formBuilder()->getForm($formObject);
$data['form'] = [
'#theme' => 'my_module_form',
'form' => $form,
];
$data['footer'] = [
'#type' => 'markup',
'#markup' => '<h3>footer</h3>',
];
return $data;
}
}
my-module-form.html.twig
<div>TWIG TEMPLATE</div>
{{ form.form.timezone }}
{{ form.form.form_build_id }}
{{ form.form.form_token }}
{{ form.form.form_id }}
{{ form.form.actions }}