View source
<?php
namespace Drupal\cpf\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\FormElement;
class Cpf extends FormElement {
const CANONICAL_MASK = '000.000.000-00';
const DIGITS_MASK = '00000000000';
const MAX_LENGTH_CANONICAL_MASK = 14;
const MAX_LENGTH_DIGITS_MASK = 9;
public function getInfo() {
$class = get_class($this);
return [
'#input' => TRUE,
'#size' => 60,
'#maxlength' => self::MAX_LENGTH_CANONICAL_MASK,
'#autocomplete_route_name' => FALSE,
'#description' => '',
'#mask' => TRUE,
'#process' => [
[
$class,
'processAutocomplete',
],
[
$class,
'processAjaxForm',
],
[
$class,
'processPattern',
],
],
'#element_validate' => [
[
$class,
'validateCpf',
],
],
'#pre_render' => [
[
$class,
'preRenderCpf',
],
],
'#theme' => 'input__cpf',
'#theme_wrappers' => [
'form_element',
],
];
}
public static function validateCpf(&$element, FormStateInterface $form_state, &$complete_form) {
$value = trim($element['#value']);
$form_state
->setValueForElement($element, $value);
if ($value !== '' && !\Drupal::service('cpf')
->isValid($value)) {
$form_state
->setError($element, t('The CPF number %cpf is not valid.', [
'%cpf' => $value,
]));
}
}
public static function preRenderCpf(array $element) {
$element['#attributes']['type'] = 'cpf';
$element['#maxlength'] = $element['#mask'] ? self::MAX_LENGTH_CANONICAL_MASK : self::MAX_LENGTH_DIGITS_MASK;
$data['cpf']['mask_plugin']['elements'][$element['#id']] = [
'id' => $element['#id'],
'mask' => $element['#mask'] ? self::CANONICAL_MASK : self::DIGITS_MASK,
];
$element['#attached'] = [
'library' => [
'cpf/cpf',
],
'drupalSettings' => $data,
];
$attributes = [
'id',
'name',
'value',
'size',
'maxlength',
'placeholder',
];
Element::setAttributes($element, $attributes);
static::setAttributes($element, [
'form-cpf',
]);
return $element;
}
}