dependent_country_state-1.0.6/src/Form/AddPincodeForm.php

src/Form/AddPincodeForm.php
<?php

namespace Drupal\dependent_country_state\Form;

use Drupal\Core\Url;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\dependent_country_state\services\GetData;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Database\Connection;

/**
 * This is simple contact Form.
 */
class AddPincodeForm extends FormBase {

  /**
   * Dbconnectin variable for storing database instance.
   *
   * @var dbConnection
   */
  protected $dbConnection;

  /**
   * Store state id from the URL incase of edit functinality.
   *
   * @var id
   */
  protected $id = 0;

  /**
   * Store state object of specific id which is given in URL.
   *
   * @var getData
   */

  protected $getData;

  /**
   * Constructor to assign object on getData variable.
   *
   * @var \Drupal\timezone\services\GetData $getData
   */

  /**
   * This variable store instace of reqequest stack to get value from url.
   *
   * @var getRequest
   */
  protected $getRequest;

  /**
   * Construction to inilized the database object.
   *
   * @param Drupal\dependent_country_state\services\GetData $getData
   *   The getData will fetch data from data.
   * @param Symfony\Component\HttpFoundation\RequestStack $getRequest
   *   The request param from url to be used.
   * @param Drupal\Core\Database\Connection $getConnection
   *   The database connection to be used.
   */
  public function __construct(GetData $getData, RequestStack $getRequest, Connection $getConnection) {
    $this->getData = $getData;
    $this->getRequest = $getRequest;
    $this->dbConnection = $getConnection;
  }

  /**
   * Define here unique form ID.
   */
  public function getFormId() {
    return "dependent_country_state_city_form";
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {

    // Instantiates GetData class.
    return new static(
      $container->get(GetData::class),
      $container->get('request_stack'),
      $container->get('database'),
    );

  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $this->id = !empty($this->getRequest->getCurrentRequest()->query->get('id')) ? $this->getRequest->getCurrentRequest()->query->get('id') : 0;

    if (isset($this->id) && $this->id > 0) {
      $pincodeData = $this->getData->getPincodeById($this->id);
    }

    $countryList = $this->getData->getAllCountry();

    $stateList = $this->getData->getAllStateByCountryId(103);

    $options = [];

    foreach ($countryList as $value) {
      $options[$value->id] = $value->country_name;
    }

    $form['country'] = [
      '#type' => 'select',
      '#title' => $this->t('Country'),
      '#options' => $options,
      '#default_value' => $pincodeData->countryId ?? $this->getRequest->getCurrentRequest()->query->get('country'),
      '#empty_option' => $this->t('- Select Country -'),
      '#ajax' => [
        'callback' => '::statesList',
        'effect' => 'fade',
        'event' => 'change',
        'wrapper' => 'state_list',
        'progress' => [
          'type' => 'throbber',
          'message' => 'Loading States...',
        ],
      ],

    ];

    if ($form_state->getTriggeringElement()) {

      $countryId = $form_state->getValue('country');

      $stateList = $this->getData->getAllStateByCountryId($countryId);

      $optionState = [];

      foreach ($stateList as $value) {
        $optionState[$value->id] = $value->state_name;
      }

      $form['state'] = [
        '#type' => 'select',
        '#title' => $this->t('State'),
        '#validated' => TRUE,
        '#prefix' => '<div id="state_list">',
        '#suffix' => '</div>',
        '#options' => $optionState,
        '#empty_option' => $this->t('- Select State -'),
        '#ajax' => [
          'callback' => '::cityList',
          'effect' => 'fade',
          'event' => 'change',
          'wrapper' => 'city_list',
          'progress' => [
            'type' => 'throbber',
            'message' => 'Loading City...',
          ],
        ],
      ];
    }
    else {

      if ($this->id > 0) {
        $stateList = $this->getData->getAllStateByCountryId($pincodeData->countryId);
        $optionState = [];
        foreach ($stateList as $value) {
          $optionState[$value->id] = $value->state_name;
        }
      }
      else {
        $optionState = [];
      }

      $form['state'] = [
        '#type' => 'select',
        '#title' => $this->t('State'),
        '#validated' => TRUE,
        '#options' => $optionState,
        '#default_value' => $pincodeData->stateId ?? $this->getRequest->getCurrentRequest()->query->get('state'),
        '#prefix' => '<div id="state_list">',
        '#suffix' => '</div>',
        '#empty_option' => $this->t('- Select State -'),
      ];

    }

    if ($this->id > 0) {
      $cityList = $this->getData->getAllCityByStateId($pincodeData->stateId);
      $optionCity = ['' => 'Select City'];
      foreach ($cityList as $value) {
        $optionCity[$value->id] = $value->city_name;
      }
    }
    else {
      $optionCity = [];
    }

    $form['city'] = [
      '#type' => 'select',
      '#title' => $this->t('City'),
      '#empty_option' => $this->t('- Select City -'),
      '#validated' => TRUE,
      '#options' => $optionCity,
      '#default_value' => $pincodeData->cityId ?? $this->getRequest->getCurrentRequest()->query->get('city'),
      '#prefix' => '<div id="city_list">',
      '#suffix' => '</div>',
    ];

    $form['area'] = [
      '#type' => 'textfield',
      '#size' => '30',
      '#title' => $this->t('Area Name'),
      '#placeholder' => 'Mayur Vihar',
      '#default_value' => $pincodeData->area_name ?? $this->getRequest->getCurrentRequest()->query->get('state'),
    ];

    $form['pincode'] = [
      '#type' => 'textfield',
      '#size' => '30',
      '#title' => $this->t('Pincode'),
      '#placeholder' => '110091',
      '#default_value' => $pincodeData->pincode ?? $this->getRequest->getCurrentRequest()->query->get('state'),
    ];

    $form['action'] = ['#type' => 'actions'];

    $form['state_search']['submit'] = [
      '#type' => 'submit',
      '#value' => (isset($this->id) && $this->id > 0) ? $this->t('Update') : $this->t('Submit'),
    ];

    return $form;
  }

  /**
   * Ajax call back method for City list.
   *
   * @param array $form
   *   The render array of the currently built form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Object describing the current state of the form.
   */
  public function cityList(array $form, FormStateInterface $form_state) {

    $stateId = $form_state->getValue('state');

    $cityList = $this->getData->getAllCityByStateId($stateId);

    $optionCity = ['' => 'Select City'];

    foreach ($cityList as $value) {
      $optionCity[$value->id] = $value->city_name;
    }

    $form['city'] = [
      '#type' => 'select',
      '#name' => 'city',
      '#prefix' => '<div id="city_list">',
      '#suffix' => '</div>',
      '#validated' => TRUE,
      '#title' => $this->t('City'),
      '#options' => $optionCity,
    ];

    return $form['city'];

  }

  /**
   * Ajax call back method for state list.
   *
   * @param array $form
   *   The render array of the currently built form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Object describing the current state of the form.
   */
  public function statesList(array $form, FormStateInterface $form_state) {
    return $form['state'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    $state = $form_state->getValue('state');
    $country = $form_state->getValue('country');
    $city = $form_state->getValue('city');
    $pincode = $form_state->getValue('pincode');

    if (empty($state)) {
      $form_state->setErrorByName('state', $this->t('State cannot be blank'));
    }
    elseif (!is_numeric($state)) {
      $form_state->setErrorByName('state', $this->t('Invalid State is selected.'));
    }

    if (empty($country)) {
      $form_state->setErrorByName('country', $this->t('Country cannot be blank'));
    }
    elseif (!is_numeric($country)) {
      $form_state->setErrorByName('country', $this->t('Invalid Country is selected.'));
    }

    if (empty($city)) {
      $form_state->setErrorByName('city', $this->t('City cannot be blank'));
    }
    elseif (!is_numeric($city)) {
      $form_state->setErrorByName('country', $this->t('Invalid City is selected.'));
    }
    if (empty($pincode)) {
      $form_state->setErrorByName('pincode', $this->t('Pincode cannot be blank'));
    }

  }

  /**
   * Implements a form submit handler.
   *
   * @param array $form
   *   The render array of the currently built form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Object describing the current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    $country = $form_state->getValue('country');
    $state = $form_state->getValue('state');
    $city_name = $form_state->getValue('city');
    $area_name = $form_state->getValue('area');
    $pincode = $form_state->getValue('pincode');

    $query = $this->dbConnection;

    if (isset($this->id) && $this->id > 0) {

      $query = $query->update('dependent_pincode')
        ->fields([
          'countryId' => $country,
          'stateId' => $state,
          'cityId' => $city_name,
          'area_name' => $area_name,
          'pincode' => $pincode,
        ]);
      $query->condition('id', $this->id, '=');
      $success = $query->execute();

      if ($success) {
        $this->messenger()->addMessage($this->t('Record Updated Successfully'), 'status', TRUE);
      }
      else {
        $this->messenger()->addError($this->t('Record not updated, please try again.'), 'status', TRUE);
      }

      $url = Url::fromRoute('country_state.pincode');
      $form_state->setRedirectUrl($url);

    }
    else {

      $query = $query->insert('dependent_pincode')
        ->fields(['countryId', 'stateId', 'cityId',
          'area_name', 'pincode', 'created',
        ]);
      $record = [$country, $state, $city_name, $area_name, $pincode, time()];
      $query->values($record);
      $success = $query->execute();

      if ($success) {
        $this->messenger()->addMessage($this->t('Record Successfully Added'), 'status', TRUE);
      }
      else {
        $this->messenger()->addError($this->t('Record not added, please try again.'), 'status', TRUE);
      }
    }

  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc