Shuaib
Shuaib

Reputation: 3

Drupal 8 Render User Profile Form in custom module

I'm pretty new to Drupal 8 and I wanted to render the user profile (user/[user_id]/edit) from in a certain page which will be created through a custom module. I wanted to this because I want the users to edit their profile without going to the user/[user_id]/edit page.

here's what I have done so far in my controller:

namespace Drupal\my_account\Controller
use Drupal\user\ProfileForm

class MyAccountController{
  public function content(){
   $entity = \Drupal::entityManager()
  ->getStorage('user')
  ->create(array());

  $formObject = \Drupal::entityManager()
  ->getFormObject('user', 'default')
  ->setEntity($entity);

$form = \Drupal::formBuilder()->getForm($formObject);

    return ['form'=>$form];
  }
}

It manages to display the form but no user contents.

Upvotes: 0

Views: 2523

Answers (2)

Nayan Arora
Nayan Arora

Reputation: 1

You need to use load function instead of create and it will load user profile form with loaded user.

$user_id = \Drupal::currentUser()->id();
$user_entity = \Drupal::entityTypeManager()->getStorage('user')->load($user_id);
$formObject = \Drupal::entityTypeManager()->getFormObject('user', 'default')->setEntity($user_entity);
$form = \Drupal::formBuilder()->getForm($formObject);

Upvotes: 0

Gorav Singal
Gorav Singal

Reputation: 538

  1. Get your user object ready with which you want to load data.
  2. Drupal::formBuilder()->getForm(Drupal\user\ProfileForm::class, $user_obj)

Upvotes: 0

Related Questions