tckk_field-1.0.x-dev/src/Plugin/Field/FieldWidget/TCKimlikNoWidget.php
src/Plugin/Field/FieldWidget/TCKimlikNoWidget.php
<?php
namespace Drupal\tckk_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;
/**
* Defines the 'tckk_field' field widget.
*
* @FieldWidget(
* id = "tckk_field",
* label = @Translation("T.C. Kimlik No"),
* field_types = {"tckk_field"},
* )
*/
class TCKimlikNoWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['tckk_field'] = [
'#type' => 'textfield',
'#default_value' => isset($items[$delta]->tckk_field) ? $items[$delta]->tckk_field : NULL,
'#element_validate' => [[$this, 'validateElement']],
];
$element['#theme_wrappers'] = ['container', 'form_element'];
$element['#attributes']['class'][] = 'container-inline';
$element['#attributes']['class'][] = 'tckk-field-elements';
$element['#attached']['library'][] = 'tckk_field/tckk_field';
return $element;
}
/**
* {@inheritdoc}
*/
public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
return isset($violation->arrayPropertyPath[0]) ? $element[$violation->arrayPropertyPath[0]] : $element;
}
/**
* {@inheritDoc}
*/
public function validateElement(array $element, FormStateInterface $form_state) {
/** @var \Drupal\tckk_field\TckkValidator */
$validator = \Drupal::service('tckk_field.validator');
$value = $element['#value'];
if ($value !== '' && $validator->validate($value) === FALSE) {
$form_state->setError($element, $this->t('T.C. Kimlik No is not valid'));
}
}
/**
* {@inheritdoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as $delta => $value) {
if ($value['tckk_field'] === '') {
$values[$delta]['tckk_field'] = NULL;
}
}
return $values;
}
}
