Skip to content

Instantly share code, notes, and snippets.

@LittleCoding
Forked from aklump/node_edit_form_d8.php
Last active October 4, 2016 15:24
Show Gist options
  • Save LittleCoding/f534968af9417fd675a890d730e3f4ed to your computer and use it in GitHub Desktop.
Save LittleCoding/f534968af9417fd675a890d730e3f4ed to your computer and use it in GitHub Desktop.
Programmatically embed an entity edit form in Drupal 8
<?php
// Without the use of D.I.
$form = \Drupal::service('entity.manager')
->getFormObject('{ENTITY_TYPE}', 'default')
->setEntity($entity);
$build[] = \Drupal::formBuilder()->getForm($form);
// Within a class using D.I.
class someClass {
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Constructs a someClasssForm object.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
*/
public function __construct(EntityManagerInterface $entityManager) {
$this->entityManager = $entityManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.manager')
);
}
public function someFunction() {
$build = array();
$form = $this->entityManager
->getFormObject('{ENTITY_TYPE}', 'default')
->setEntity($entity);
$build[] = \Drupal::formBuilder()->getForm($form);
return $build;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment