DemoWidgetFormsController.php in Geolocation Field 8
File
modules/geolocation_demo/src/Controller/DemoWidgetFormsController.php
View source
<?php
namespace Drupal\geolocation_demo\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Field\WidgetPluginManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
class DemoWidgetFormsController extends ControllerBase {
protected $pluginManagerFieldWidget;
protected $entityTypeManager;
public function __construct(WidgetPluginManager $plugin_manager_field_widget, EntityTypeManager $entity_type_manager) {
$this->pluginManagerFieldWidget = $plugin_manager_field_widget;
$this->entityTypeManager = $entity_type_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.manager.field.widget'), $container
->get('entity_type.manager'));
}
public function widgets(Request $request, RouteMatchInterface $route_match) {
$node = $this->entityTypeManager
->getStorage('node')
->create([
'type' => 'geolocation_default_article',
]);
$items = $node
->get('field_geolocation_demo_single');
$field_definition = $node
->getFieldDefinition('field_geolocation_demo_single');
$widget_settings = [
'field_definition' => $field_definition,
'form_mode' => 'default',
'prepare' => TRUE,
'configuration' => [
'settings' => [],
'third_party_settings' => [],
],
];
$form_state = new FormState();
$form = [];
foreach ([
'geolocation_googlegeocoder',
'geolocation_latlng',
'geolocation_html5',
] as $widget_id) {
$widget = $this->pluginManagerFieldWidget
->getInstance(array_merge_recursive($widget_settings, [
'configuration' => [
'type' => $widget_id,
],
]));
$form[$widget_id] = $widget
->formElement($items, 0, [
'#title' => $widget
->getPluginDefinition()['label'],
], $form, $form_state);
}
return $form;
}
}