Skip to content

Instantly share code, notes, and snippets.

@gambry
Created December 6, 2017 13:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gambry/87fc6b4be05713addc4694de407bc1a6 to your computer and use it in GitHub Desktop.
Save gambry/87fc6b4be05713addc4694de407bc1a6 to your computer and use it in GitHub Desktop.
Drupal text field widget to set custom maxlength
<?php
namespace Drupal\mymodule\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextfieldWidget;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'textfield_with_maxlength' widget.
*
* @FieldWidget(
* id = "textfield_with_maxlength",
* label = @Translation("Textfield with maxlength"),
* field_types = {
* "text",
* "string"
* }
* )
*/
class TextfieldWithMaxlengthWidget extends StringTextfieldWidget {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'custom_maxlength' => NULL,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['custom_maxlength'] = [
'#type' => 'number',
'#title' => t('Maxlength of textfield'),
'#default_value' => $this->getCustomMaxLength(),
'#description' => t('Set a custom maxlength. Leave it empty to use field default value (@size).', ['@size' => $this->getFieldSetting('max_length')]),
'#min' => 1,
'#max' => $this->getFieldSetting('max_length'),
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
$summary[] = t('Maxlength: @size', ['@size' => $this->getCustomMaxLength()]);
return $summary;
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$main_widget = parent::formElement($items, $delta, $element, $form, $form_state);
$element = $main_widget['value'];
$element['#maxlength'] = $this->getCustomMaxLength();
return $element;
}
/**
* Return custom maxlength.
*
* This method returns the custom maxlength if is set, otherwise defaults to
* the field max_length setting.
*
* @return int
* The maxlength size.
*/
protected function getCustomMaxLength() {
return $this->getSetting('custom_maxlength') ?: $this->getFieldSetting('max_length');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment