How to validate all elements in Custom Widget

by Jitha M Saroj   Last Updated November 13, 2017 20:07 PM

I can validate a single textfield usig the fllowing code.

/**
 * @file
 * Contains \Drupal\field_example\Plugin\Field\FieldWidget\TextWidget.
 */

namespace Drupal\field_example\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'field_example_text' widget.
 *
 * @FieldWidget(
 *   id = "field_example_text",
 *   module = "field_example",
 *   label = @Translation("RGB value as #ffffff"),
 *   field_types = {
 *     "field_example_rgb"
 *   }
 * )
 */
class TextWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';
    $element += array(
      '#type' => 'textfield',
      '#default_value' => $value,
      '#size' => 7,
      '#maxlength' => 7,
      '#element_validate' => array(
        array($this, 'validate'),
      ),
    );
    return array('value' => $element);
  }

  /**
   * Validate the color text field.
   */
  public function validate($element, FormStateInterface $form_state) {
    $value = $element['#value'];
    if (strlen($value) == 0) {
      $form_state->setValueForElement($element, '');
      return;
    }
    if (!preg_match('/^#([a-f0-9]{6})$/iD', strtolower($value))) {
      $form_state->setError($element, t("Color must be a 6-digit hexadecimal value, suitable for CSS."));
    }
  }

}

But I have more elements in the widgets as follows

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {


     $element['cert_fqdn'] = [
      '#type' => 'textfield',
      '#title' => t('Fully qualified Domain Name'),
      '#value' => $items[$delta]->value ?: NULL,
      '#empty_value' => '',
      '#placeholder' => t('Fully qualified Domain Name'),

    ];
    $element['privatekey'] = [
      '#type' => 'textfield',
      '#title' => t('Private Key'),
      '#default_value' => isset($items[$delta]->cert_key) ? 
          $items[$delta]->cert_key : null,
      '#empty_value' => '',
      '#placeholder' => t('PrivateKey'),
    ];

    // City

    $element['csr'] = [
      '#type' => 'textfield',
      '#title' => t('Certificate Signing Request'),
      '#default_value' => isset($items[$delta]->cert_csr) ? 
          $items[$delta]->cert_csr : null,
      '#empty_value' => '',
      '#placeholder' => t('Certificate Signing Request'),
    ];
    $element['cert_crt'] = [
      '#type' => 'textfield',
      '#title' => t('Server Certificate'),
      '#placeholder' => t('Server Certificate'),
    ];


$element['create_cert_btn'] = array(
    //'#name' => implode('_', $element['#parents']) .'_create_cert_btn',
    '#type' => 'submit',
    '#value' => t('Create/Renew Cert'),
        '#element_validate' => array(
        array($this, 'validate'),
            ),

    );

    return $element;


  } 

I need to get the values of all the elements in validate function. How can I change the code to meet this . Please help.

Tags : 8


Answers 1


A GOOD example of this approach is Field_example module from Example module for developers.(link here https://www.drupal.org/project/examples/releases/8.x-1.x-dev).

The widget with the "field_example_3text" id has also 3 elements: "r", "g, "b", and the values are accessed in validation function:

  foreach (['r', 'g', 'b'] as $colorfield) {

      $values[$colorfield] = $element[$colorfield]['#value'];
  }

So create an array containing your keys elements and loop into it, accessing the values by writing $element['your key']['#value'];

Have a look at this module. The dpm of the $element variable looks like this: enter image description here

OPTASY
OPTASY
November 13, 2017 19:48 PM

Related Questions