Skip to content

Instantly share code, notes, and snippets.

@aklump
Created March 29, 2024 14:42
Show Gist options
  • Save aklump/7830e7930bf37fa6b4e758f022f6d93b to your computer and use it in GitHub Desktop.
Save aklump/7830e7930bf37fa6b4e758f022f6d93b to your computer and use it in GitHub Desktop.
Drupal form widget to preload with current user's IP.
<?php
namespace Drupal\se_core\Plugin\Field\FieldWidget;
use Drupal;
use Drupal\Component\Utility\Color;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\se_core\Seao;
/**
* Plugin implementation of the 'current_user_ip' widget.
*
* @FieldWidget(
* id = "current_user_ip",
* module = "se_core",
* label = @Translation("Current User IP"),
* field_types = {
* "string"
* }
* )
*/
class CurrentUserIpWidget extends WidgetBase {
const IP_REGEX = '(\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}';
/**
* {@inheritdoc}
*/
public function formElement(
FieldItemListInterface $items,
$delta,
array $element,
array &$form,
FormStateInterface $form_state
) {
$default_value = Seao::surveyResponses()->getDefaultIP();
$value = $items[$delta]->value ?? $default_value;
$element += [
'#type' => 'textfield',
'#placeholder' => $default_value,
'#default_value' => $value,
'#element_validate' => [[$this, 'validate']],
];
$readonly = $this->getSetting('readonly');
if ($readonly) {
$element['#attributes']['readonly'] = TRUE;
}
return ['value' => $element];
}
/**
* Validate the color text field.
*/
public static function validate($element, FormStateInterface $form_state) {
$value = NestedArray::getValue($form_state->getValues(), $element['#parents']);
if (strlen($value) === 0) {
$form_state->setValueForElement($element, '');
return;
}
if (!preg_match('#' . self::IP_REGEX . '#', $value)) {
$form_state->setError($element, t('@value does not appear to be a valid IP.',
['@value' => $value]));
}
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'readonly' => FALSE,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['readonly'] = array(
'#type' => 'radios',
'#title' => t('Read only'),
'#options' => [0 => t('False'), 1 => $this->t('True')],
'#default_value' => (int) $this->getSetting('readonly'),
);
return $element;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$bool_value = $this->getSetting('readonly') ? $this->t('TRUE') : $this->t('FALSE');
$summary[] = t('Readonly: @value', ['@value' => $bool_value]);
return $summary;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment