graph_element-1.0.4/src/Plugin/Field/FieldWidget/GraphElementWidget.php
src/Plugin/Field/FieldWidget/GraphElementWidget.php
<?php
namespace Drupal\graph_element\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\graph_element\Utility;
/**
* Plugin implementation of the 'graph_element_widget' widget.
*
* @FieldWidget(
* id = "graph_element_widget",
* module = "graph_element",
* label = @Translation("Chart Widget"),
* field_types = {
* "graph_element_item"
* }
* )
*/
class GraphElementWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$utility = new Utility();
$graphResourceOptions = $utility->getGraphResources(TRUE);
$graphTypesOptions = $utility->getGraphTypes();
$element += [
'#type' => 'fieldset',
'#attributes' => [
'class' => ['row'],
],
'graph_title' => [
'#type' => 'textfield',
'#title' => $this->t('Chart Title'),
'#default_value' => $items[$delta]->graph_title ?? NULL,
'#size' => 60,
'#maxlength' => 128,
'#required' => FALSE,
],
'graph_source' => [
'#type' => 'select',
'#title' => $this->t('Chart Source'),
'#options' => $graphResourceOptions,
'#default_value' => $items[$delta]->graph_source ?? NULL,
'#required' => TRUE,
],
'graph_type' => [
'#type' => 'select',
'#title' => $this->t('Chart Type'),
'#options' => $graphTypesOptions,
'#default_value' => $items[$delta]->graph_type ?? NULL,
'#required' => TRUE,
],
'graph_description' => [
'#type' => 'textfield',
'#title' => $this->t('Chart Description'),
'#default_value' => $items[$delta]->graph_description ?? NULL,
'#size' => 60,
'#maxlength' => 128,
'#required' => FALSE,
],
];
return $element;
}
/**
* Validate the video script field.
*/
public function validate($element, FormStateInterface $form_state) {
$graph_type = $element['#graph_type'];
$graph_type = trim($graph_type);
if (empty($graph_type)) {
$form_state->setError($element, $this->t('Please select a Chart type.'));
return;
}
$graph_source = $element['#graph_source'];
$graph_source = trim($graph_source);
if (empty($graph_source)) {
$form_state->setError($element, $this->t('Please select a Chart source.'));
return;
}
$graph_title = $element['#graph_title'];
$graph_description = $element['#graph_description'];
$form_state->setValueForElement($element, $graph_type);
$form_state->setValueForElement($element, $graph_source);
$form_state->setValueForElement($element, $graph_title);
$form_state->setValueForElement($element, $graph_description);
}
}
