View source
<?php
namespace Drupal\prepopulate;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Render\Element;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Component\Utility\Html;
class Populate implements PopulateInterface {
protected $request;
protected $entityTypeManager;
protected $moduleHandler;
protected $whitelistedTypes = [
'container',
'date',
'datelist',
'datetime',
'entity_autocomplete',
'email',
'fieldset',
'inline_entity_form',
'language_select',
'machine_name',
'number',
'path',
'select',
'tel',
'textarea',
'text_format',
'textfield',
'url',
];
public function __construct(RequestStack $request, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler) {
$this->request = $request;
$this->entityTypeManager = $entity_type_manager;
$this->moduleHandler = $module_handler;
$this->moduleHandler
->alter('prepopulate_whitelist', $this->whitelistedTypes);
}
public function populateForm(array &$form, $request_slice = NULL) {
if (is_null($request_slice)) {
$request_slice = $this->request
->getCurrentRequest()->query
->get('edit');
}
if (is_array($request_slice)) {
foreach (array_keys($request_slice) as $request_variable) {
if (isset($form[$request_variable])) {
$element =& $form[$request_variable];
if (isset($element['widget'][0]['value']['#type'])) {
$type = $element['widget'][0]['value']['#type'];
}
elseif (isset($element['widget'][0]['target_id']['#type'])) {
$type = $element['widget'][0]['target_id']['#type'];
}
elseif (isset($element['widget']['#type'])) {
$type = $element['widget']['#type'];
}
elseif (isset($element['#type'])) {
$type = $element['#type'];
}
if (Element::child($request_variable) && !empty($element) && (empty($type) || in_array($type, $this->whitelistedTypes))) {
$this
->populateForm($element, $request_slice[$request_variable]);
}
}
}
}
else {
if (empty($form['#type'])) {
return;
}
if (!empty($form['#value']) && is_scalar($form['#value'])) {
return;
}
if (isset($form['#access']) && $form['#access'] === FALSE) {
return;
}
$value = Html::escape($request_slice);
switch ($form['#type']) {
case 'entity_autocomplete':
$form['#value'] = $this
->formatEntityAutocomplete($value, $form);
break;
case 'checkbox':
$form['#checked'] = $value === 'true';
default:
$form['#value'] = $value;
break;
}
}
}
protected function formatEntityAutocomplete($value, array &$element) {
$entity = $this->entityTypeManager
->getStorage($element['#target_type'])
->load($value);
if ($entity && $entity
->access('view label')) {
return "{$entity->label()} ({$value})";
}
return $value;
}
}