dependent_country_state-1.0.6/src/Form/AddCtForm.php
src/Form/AddCtForm.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 AddCtForm 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_id";
}
/**
* {@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) {
$cityData = $this->getData->getAllCity($this->id);
}
$countryList = $this->getData->getAllCountry();
$stateList = $this->getData->getAllStateByCountryId(103);
$options = ['' => 'Select Country'];
foreach ($countryList as $value) {
$options[$value->id] = $value->country_name;
}
$form['country'] = [
'#type' => 'select',
'#title' => $this->t('Country'),
'#options' => $options,
'#validated' => TRUE,
'#default_value' => $cityData[0]->countryId ?? $this->getRequest->getCurrentRequest()->query->get('country'),
'#ajax' => [
'callback' => '::statesList',
'effect' => 'fade',
'event' => 'change',
'wrapper' => 'state_list',
'progress' => [
'type' => 'throbber',
'message' => 'Loading States...',
],
],
];
if ($this->id > 0) {
$stateList = $this->getData->getAllStateByCountryId($cityData[0]->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' => $cityData[0]->stateId ?? $this->getRequest->getCurrentRequest()->query->get('state'),
'#empty_option' => $this->t('- Select State -'),
'#prefix' => '<div id="state_list">',
'#suffix' => '</div>',
];
$form['city'] = [
'#type' => 'textfield',
'#size' => '50',
'#title' => $this->t('City Name'),
'#placeholder' => 'New Delhi',
'#default_value' => $cityData[0]->city_name ?? $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 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) {
$countryId = $form_state->getValue('country');
$stateList = $this->getData->getAllStateByCountryId($countryId);
$optionState = ['' => 'Select State'];
foreach ($stateList as $value) {
$optionState[$value->id] = $value->state_name;
}
$form['state'] = [
'#type' => 'select',
'#name' => 'state',
'#prefix' => '<div id="state_list">',
'#suffix' => '</div>',
'#validated' => TRUE,
'#title' => $this->t('State'),
'#options' => $optionState,
];
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');
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'));
}
}
/**
* 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) {
$state = $form_state->getValue('state');
$country = $form_state->getValue('country');
$city_name = $form_state->getValue('city');
$query = $this->dbConnection;
if (isset($this->id) && $this->id > 0) {
$query = $query->update('dependent_city')
->fields(
[
'countryId' => $country,
'stateId' => $state,
'city_name' => $city_name,
]);
$query->condition('id', $this->id, '=');
$success = $query->execute();
if ($success) {
$this->messenger()->addMessage($this->t('City Updated Successfully'), 'status', TRUE);
}
else {
$this->messenger()->addError($this->t('City not updated, please try again.'), 'status', TRUE);
}
$url = Url::fromRoute('country_state.city');
$form_state->setRedirectUrl($url);
}
else {
$query = $query->insert('dependent_city')
->fields(['countryId', 'stateId', 'city_name', 'created']);
$record = [$country, $state, $city_name, time()];
$query->values($record);
$success = $query->execute();
if ($success) {
$this->messenger()->addMessage($this->t('City Successfully Added'), 'status', TRUE);
}
else {
$this->messenger()->addError($this->t('City not added, please try again.'), 'status', TRUE);
}
}
}
}
