TransWikia.com

Why is my code called again written on build form?

Drupal Answers Asked by namit garg on January 29, 2021

I have a form and i call an API tahta brings huge data on build form.
But when i call Ajax on other form elements , the whole code for form(buildForm, constructor ) is called again and again. There is a way to check triggering element but the code is called twice again once due to ajax Callback and once due to validateForm. I want a solution so that the Api are only called once, what solution i can use for this

<?php

namespace Drupalfapi_exampleForm;

use DrupalCoreFormFormStateInterface;

/**
 * Implements the ajax demo form controller.
 *
 * This example demonstrates using ajax callbacks to populate the options of a
 * color select element dynamically based on the value selected in another
 * select element in the form.
 *
 * @see DrupalCoreFormFormBase
 * @see DrupalCoreFormConfigFormBase
 */
class AjaxDemo extends DemoBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'fapi_example_ajax_demo';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['temperature'] = [
      '#title' => $this->t('Temperature'),
      '#type' => 'select',
      '#options' => $this->getColorTemperatures(),
      '#empty_option' => $this->t('- Select a color temperature -'),
      '#ajax' => [
        // Could also use [get_class($this), 'updateColor'].
        'callback' => '::updateColor',
        'wrapper' => 'color-wrapper',
      ],
    ];
    print("API call");
    $form['color_wrapper'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'color-wrapper'],
    ];

    $temperature = $form_state->getValue('temperature');
    if (!empty($temperature)) {
      $form['color_wrapper']['color'] = [
        '#type' => 'select',
        '#title' => $this->t('Color'),
        '#options' => $this->getColorsByTemperature($temperature),
      ];
    }

    // Add a submit button that handles the submission of the form.
    $form['actions'] = [
      '#type' => 'actions',
      'submit' => [
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
      ],
    ];

    return $form;
  }

  /**
   * Ajax callback for the color dropdown.
   */
  public function updateColor(array $form, FormStateInterface $form_state) {
    return $form['color_wrapper'];
  }

  /**
   * Returns colors that correspond with the given temperature.
   *
   * @param string $temperature
   *   The color temperature for which to return a list of colors. Can be either
   *   'warm' or 'cool'.
   *
   * @return array
   *   An associative array of colors that correspond to the given color
   *   temperature, suitable to use as form options.
   */
  protected function getColorsByTemperature($temperature) {
    return $this->getColors()[$temperature]['colors'];
  }

  /**
   * Returns a list of color temperatures.
   *
   * @return array
   *   An associative array of color temperatures, suitable to use as form
   *   options.
   */
  protected function getColorTemperatures() {
    return array_map(function ($color_data) {
      return $color_data['name'];
    }, $this->getColors());
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    print("Sssaaa");
  }

  /**
   * Returns an array of colors grouped by color temperature.
   *
   * @return array
   *   An associative array of color data, keyed by color temperature.
   */
  protected function getColors() {
    return [
      'warm' => [
        'name' => $this->t('Warm'),
        'colors' => [
          'red' => $this->t('Red'),
          'orange' => $this->t('Orange'),
          'yellow' => $this->t('Yellow'),
        ],
      ],
      'cool' => [
        'name' => $this->t('Cool'),
        'colors' => [
          'blue' => $this->t('Blue'),
          'purple' => $this->t('Purple'),
          'green' => $this->t('Green'),
        ],
      ],
    ];
  }

}

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP