I'm trying to integrate Selectize plugin within Drupal 8 Form API. The important thing that I want to create 'optgroup' options.
I've used Selectize module and created a custom FieldWidget
Field plugin.
Almost everything works, but I got some troubles with validation of my element.
Every time my form element submitted I receive an validation error:
"An illegal choice has been detected. Please contact the site administrator."
I've found the function, which sends me that error - performRequiredValidation().
I've found lines, so I can hack the core and add a case for my widget. But it's not a case for me.
if ($elements['#type'] == 'select') {
$options = OptGroup::flattenOptions($elements['#options']);
}
else {
$options = $elements['#options'];
}
So the only way I see - I have to avoid this validation somehow.
Plase help. Any suggestions would be appreciated.
Here is a simplified code of my widget:
namespace Drupal\my_fields\Plugin\Field\FieldWidget;
use Drupal;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsSelectWidget;
/**
* Plugin implementation of the 'my_selectize_widget' widget.
*
* @FieldWidget(
* id = "my_selectize_widget",
* label = @Translation("My Selectize Widget"),
* module = "my_fields",
* field_types = {
* "entity_reference"
* },
* multiple_values = TRUE
* )
*/
class MySelectizeWidget extends OptionsSelectWidget {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
// Get our types.
$grouped_types = _getTypesGrouped();
// Override select form element.
$element['#settings'] = [
'plugins' => ['optgroup_columns'],
];
$element['#type'] = 'selectize';
$element['#options'] = $grouped_types;
return $element;
}
/**
* Get types grouped (options).
*/
protected function _getTypesGrouped() {
/**
* // For example:
* return [
* '1' => $this->t('One'),
* '2' => [
* '2.1' => $this->t('Two point one'),
* '2.2' => $this->t('Two point two'),
* ],
* '3' => $this->t('Three'),
* ];
*/
}
}