1

I'm trying to add the user edit form in a block. I created a custom module

use Drupal\Core\Block\BlockBase;
use Drupal\user\ProfileForm;


class EditUserBlock extends BlockBase{

  /**
   * {@inheritdoc}
   */
  public function build() {

    $form = \Drupal::formBuilder()->getForm(ProfileForm::class, \Drupal::currentUser());

    return $form;
  }
}

but it doesn't render the form.

Sorry but I'm pretty new to D8.

1

This is an entity form and you need EntityFormBuilder::getForm() to build this form. After you have injected the entity form builder and the necessary user storage and current user services in the block plugin:

<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a Profile Block.
 *
 * @Block(
 *  id = "profile_block",
 *  admin_label = @Translation("Profile Block"),
 * )
 */
class ProfileBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * @var \Drupal\Core\Entity\EntityFormBuilderInterface
   */
  protected $entityFormBuilder;

  /**
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $userStorage;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityFormBuilderInterface $entity_form_builder, AccountInterface $current_user, EntityStorageInterface $user_storage) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityFormBuilder = $entity_form_builder;
    $this->currentUser = $current_user;
    $this->userStorage = $user_storage;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity.form_builder'),
      $container->get('current_user'),
      $container->get('entity_type.manager')->getStorage('user')
    );
  }

you can build the profile form for the current user with two lines of code:

  public function build() {
    $user = $this->userStorage->load($this->currentUser->id());
    return $this->entityFormBuilder->getForm($user);
  }

}
  • This is very helpful, thanks! This might be a little off-topic, but do you know how I would do this for the user specified in the route rather than for the current user? – Anne Bonham Jan 3 '18 at 20:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.