ExampleCustomInput.php in Extra Field 8.2
File
modules/extra_field_example/src/Plugin/ExtraField/Form/ExampleCustomInput.php
View source
<?php
namespace Drupal\extra_field_example\Plugin\ExtraField\Form;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\extra_field\Plugin\ExtraFieldFormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ExampleCustomInput extends ExtraFieldFormBase implements ContainerFactoryPluginInterface {
use StringTranslationTrait;
const VOUCHER_CODE_FIELD = 'voucher_code';
const VOUCHER_REFERENCE_FIELD = 'field_voucher';
protected $entityTypeManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entityTypeManager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entityTypeManager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'));
}
public function formElement(array &$form, FormStateInterface $form_state) {
$form[self::VOUCHER_CODE_FIELD] = [
'#type' => 'textfield',
'#title' => $this
->t('Voucher code'),
'#required' => TRUE,
'#size' => 30,
];
$form['#validate'][] = [
$this,
'validateVoucherCode',
];
}
public function validateVoucherCode(array $form, FormStateInterface $form_state) {
$voucherCode = $this
->lookupVoucherCodeEntity($form_state
->getValue('voucher_code_text'));
if (empty($voucherCode)) {
$form_state
->setErrorByName(self::VOUCHER_CODE_FIELD, $this
->t('Invalid voucher code'));
return;
}
if ($voucherCode
->isExpired()) {
$form_state
->setErrorByName(self::VOUCHER_CODE_FIELD, $this
->t('This voucher code is no longer valid'));
return;
}
$form_state
->setValue(self::VOUCHER_REFERENCE_FIELD, [
[
'target_id' => $voucherCode
->id(),
],
]);
}
private function lookupVoucherCodeEntity($code) {
if (empty($code)) {
return NULL;
}
$vouchers = $this->entityTypeManager
->getStorage('voucher')
->loadByProperties([
'code' => trim($code),
]);
return empty($vouchers) ? NULL : reset($vouchers);
}
}