public function WidgetForm::buildForm in Search API Sorts Widget 1.x
Form constructor.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Return value
array The form structure.
Overrides FormInterface::buildForm
File
- src/
Form/ WidgetForm.php, line 62
Class
- WidgetForm
- Provides a Search API Sorts Widget form.
Namespace
Drupal\search_api_sorts_widget\FormCode
public function buildForm(array $form, FormStateInterface $form_state, $content = NULL, $derivative_plugin_id = NULL) {
if (!$content || !$derivative_plugin_id) {
return $content;
}
$config_id = $this
->getEscapedConfigId($derivative_plugin_id);
$settings = $this->searchApiSortsWidgetStorage
->load($config_id);
if (empty($settings) || !$settings
->get('status')) {
return $content;
}
$links = $content['links'];
$new_items = [];
$default = '';
$sort_fields = array_column($links['#items'], '#sort_field');
foreach ($settings
->get('sorts') as $name => $setting) {
$key = array_search($name, $sort_fields);
if (!empty($links['#items'][$key])) {
$link = $links['#items'][$key];
if (!empty($setting['label_asc'])) {
$new_items[$name . '|asc'] = $setting['label_asc'];
}
if (!empty($setting['label_desc'])) {
$new_items[$name . '|desc'] = $setting['label_desc'];
}
if ($link['#active']) {
$default = $name . '|' . ($link['#order'] == 'asc' ? 'desc' : 'asc');
}
}
}
$form_state
->set('links', $links);
$form['sort_by'] = array(
'#type' => 'select',
'#options' => $new_items,
'#default_value' => $default,
);
if ($settings
->get('autosubmit')) {
$form['sort_by']['#attributes']['onChange'] = 'this.form.submit();';
}
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Sort'),
];
if ($settings
->get('autosubmit_hide')) {
$form['actions']['submit']['#attributes']['style'] = [
'display: none;',
];
}
return $form;
}