toolshed-8.x-1.x-dev/src/Element/HtmlButton.php
src/Element/HtmlButton.php
<?php
namespace Drupal\toolshed\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\Button;
/**
* Create a button element that is a HTML button element.
*
* @FormElement("html_button")
*/
class HtmlButton extends Button {
/**
* {@inheritdoc}
*/
public function getInfo(): array {
$info = [
'#theme_wrappers' => ['html_button'],
'#executes_submit_callback' => TRUE,
] + parent::getInfo();
return $info;
}
/**
* {@inheritdoc}
*/
public static function processButton(&$element, FormStateInterface $form_state, &$complete_form): array {
$element = parent::processButton($element, $form_state, $complete_form);
// Pose as a button in order to get normal AJAX and other behaviors.
$element['#type'] = 'button';
return $element;
}
/**
* Prepares a #type 'button' render element for input.html.twig.
*
* @param mixed $element
* An associative array containing the properties of the element.
* Properties used: #attributes, #button_type, #name, #value. The
* #button_type property accepts any value, though core themes have CSS that
* styles the following button_types appropriately: 'primary', 'danger'.
*
* @return array
* The $element with prepared variables ready for input.html.twig.
*/
public static function preRenderButton($element): array {
Element::setAttributes($element, ['id']);
// If there was no value involved, skip adding the name and value.
if (!empty($element['#value'])) {
$element['#attributes']['name'] = $element['#name'];
$element['#attributes']['value'] = $element['#value'];
}
if ($element['#executes_submit_callback']) {
$element['#attributes']['class'][] = 'js-form-submit';
$element['#attributes']['class'][] = 'form-submit';
}
if (!empty($element['#attributes']['disabled'])) {
$element['#attributes']['class'][] = 'is-disabled';
}
return $element;
}
}
