Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.