The code in MymoduleBlock::build()
is correct, and it is what Drupal core does in UserLoginBlock::build()
.
$form = \Drupal::formBuilder()->getForm('Drupal\user\Form\UserLoginForm');
unset($form['name']['#attributes']['autofocus']);
// When unsetting field descriptions, also unset aria-describedby attributes
// to avoid introducing an accessibility bug.
// @todo Do this automatically in https://www.drupal.org/node/2547063.
unset($form['name']['#description']);
unset($form['name']['#attributes']['aria-describedby']);
unset($form['pass']['#description']);
unset($form['pass']['#attributes']['aria-describedby']);
$form['name']['#size'] = 15;
$form['pass']['#size'] = 15;
What the block definition is missing is the annotation (the comment before the class) which allows Drupal to identify that class as plugin. See what Block API says. (Emphasis is mine.)
Blocks are a combination of a configuration entity and a plugin. The configuration entity stores placement information (theme, region, weight) and any other configuration that is specific to the block. The block plugin does the work of rendering the block's content for display.
Block plugins use the annotations defined by \Drupal\Core\Block\Annotation\Block
. See the Annotations topic for more information about annotations.
In the block class I used as example, the annotation is the following one.
/*
* @Block(
* id = "user_login_block",
* admin_label = @Translation("User login"),
* category = @Translation("Forms")
* )
*/
Also, the machine name of module should not contain hyphens, which aren't allowed in PHP functions. That creates problems when you implement hooks, since the hook name is derived from the machine name of the module. For example, the implementation of hook_page_attachments()
for your module would be my-module_page_attachments()
, which is not an acceptable PHP function name.
If you think your module is not going to implement hooks, keep in mind that the majority of modules implements at least hook_update_N(), for which is also preferable not using capital letters in the module machine name.