Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Custom module to Insert, Update and Delete and also Sorting with pagination

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 701
    Comment on it

    Hello Drupal 8 guys,

    I am sharing a custom module which function is to collect a developer data and show list of that data with header sorting and pagination and also used form validation. If Anybody wants to use this module just download the ZIP and put it in custom module folder of drupal 8 and then enable it. it starts working. I am sharing code only of controller class rest user can create or download zip.

    Below is the explanation for better understanding:

    Create a folder name bd_contact in custom module folder of your drupal project and then create src/Controller.after that create a PHP file name AddForm.php and write the code.

    <?php
    /**
     * @file
     * Contains \Drupal\bd_contact\AddForm.
     */
    
    namespace Drupal\bd_contact;
    
    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Component\Utility\SafeMarkup;
    
    class AddForm extends FormBase {
      protected $id;
    
      function getFormId() {
        return 'bd_contact_add';
      }
    
      function buildForm(array $form, FormStateInterface $form_state) {
        $this->id = \Drupal::request()->get('id');
        $bd_contact = BdContactStorage::get($this->id);
    
        $form['name'] = array(
          '#type' => 'textfield',
          '#title' => t('Name'),
          '#required' => TRUE,
          '#default_value' => ($bd_contact) ? $bd_contact->name : '',
        );
        $form['message'] = array(
          '#type' => 'textarea',
          '#title' => t('Address'),
          '#required' => TRUE,
          '#default_value' => ($bd_contact) ? $bd_contact->message : '',
        );
        $form['country'] = array(
                '#type' => 'select',
                '#required' => TRUE,
                '#title' => ('Country'),
                '#options' => array(
                    'india' => t('India'),
                    'usa' => t('USA'),
                ),
          '#default_value' => ($bd_contact) ? $bd_contact->country : '',
            );
        $form['gender'] = array(
                '#type' => 'radios',
                '#title' => ('Gender'),
                '#required' => TRUE,
                '#options' => array(
                    'male' => t('Male'),
                    'female' => t('Female')
                ),
          '#default_value' => ($bd_contact) ? $bd_contact->gender : '',      
            );
        $form['foreigner'] = array(
                '#type' => 'checkbox',
                '#title' => t(' Are You Foreigner.'),
          '#default_value' => ($bd_contact) ? $bd_contact->foreigner : '',
            );
        $form['actions'] = array('#type' => 'actions');
        $form['actions']['submit'] = array(
          '#type' => 'submit',
          '#value' => ($bd_contact) ? t('Edit') : t('Add'),
        );
        return $form;
      }
    
      /**
       * {@inheritdoc}
       */
      public function validateForm(array &$form, FormStateInterface $form_state) {
    
        if (strlen($form_state->getValue('name')) < 3) {
        $form_state->setErrorByName('name', $this->t('The name is too short. Please enter a full name.'));
      }
    
        if ($form_state->hasValue('name'))
      {
         $name = $form_state->getValue('name');
    
         //var_dump($name);die;
    
          if (strlen(trim($name)) > 0 && !preg_match('/^[a-z A-Z\'\-]+$/', $name)) {
           // form_set_error('submitted][name', t('Your name contains invalid characters. Only letters are allowed!'));
            $form_state->setErrorByName('name', $this->t('Your name contains invalid characters. Only letters are allowed!'));
          }
       }
    
      }
    
    
      function submitForm(array &$form, FormStateInterface $form_state) {
        $name = $form_state->getValue('name');
        $message = $form_state->getValue('message');
        $country = $form_state->getValue('country');
        $gender = $form_state->getValue('gender');
        $foreigner = $form_state->getValue('foreigner');
        if (!empty($this->id)) {
          BdContactStorage::edit($this->id, SafeMarkup::checkPlain($name), SafeMarkup::checkPlain($message), SafeMarkup::checkPlain($country), SafeMarkup::checkPlain($gender), SafeMarkup::checkPlain($foreigner));
          \Drupal::logger('bd_contact')->notice('@type: deleted %title.',
              array(
                  '@type' => $this->id,
                  '%title' => $this->id,
              ));
    
          drupal_set_message(t('Your message has been edited'));
        }
        else {
          BdContactStorage::add(SafeMarkup::checkPlain($name), SafeMarkup::checkPlain($message), SafeMarkup::checkPlain($country), SafeMarkup::checkPlain($gender), SafeMarkup::checkPlain($foreigner));
          \Drupal::logger('bd_contact')->notice('@type: deleted %title.',
              array(
                  '@type' => $this->id,
                  '%title' => $this->id,
              ));
    
          drupal_set_message(t('Your message has been submitted'));
        }
        $form_state->setRedirect('bd_contact_list');
        return;
      }
    }
    

     

    Step 2. Create a new file name BdContactStorage.php for function.

    <?php
    
    namespace Drupal\bd_contact;
    
    class BdContactStorage {
    
      static function getAll() {
        $result = db_query('SELECT * FROM {bd_contact}')->fetchAllAssoc('id');
        return $result;
      }
    
      static function exists($id) {
        return (bool) $this->get($id);
      }
    
      static function get($id) {
        $result = db_query('SELECT * FROM {bd_contact} WHERE id = :id', array(':id' => $id))->fetchAllAssoc('id');
        if ($result) {
          return $result[$id];
        }
        else {
          return FALSE;
        }
      }
    
      static function add($name, $message, $country, $gender, $foreigner) {
        db_insert('bd_contact')->fields(array(
          'name' => $name,
          'message' => $message,
          'country' => $country,
          'gender' => $gender,
          'foreigner' => $foreigner,
        ))->execute();
      }
    
      static function edit($id, $name, $message, $country, $gender, $foreigner) {
        db_update('bd_contact')->fields(array(
          'name' => $name,
          'message' => $message,
          'country' => $country,
          'gender' => $gender,
          'foreigner' => $foreigner,
        ))
        ->condition('id', $id)
        ->execute();
      }
      
      static function delete($id) {
        db_delete('bd_contact')->condition('id', $id)->execute();
      }
    }
    

     

    step 3: Create a file DeleteForm.php for deleting the data with id.

    <?php
    
    namespace Drupal\bd_contact;
    
    use Drupal\Core\Form\ConfirmFormBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Core\Url;
    
    class DeleteForm extends ConfirmFormBase {
      protected $id;
    
      function getFormId() {
        return 'bd_contact_delete';
      }
    
      function getQuestion() {
        return t('Are you sure you want to delete submission %id?', array('%id' => $this->id));
      }
    
      function getConfirmText() {
        return t('Delete');
      }
    
      function getCancelUrl() {
        return new Url('bd_contact_list');
      }
    
      function buildForm(array $form, FormStateInterface $form_state) {
        $this->id = \Drupal::request()->get('id');
        return parent::buildForm($form, $form_state);
      }
    
      function submitForm(array &$form, FormStateInterface $form_state) {
        BdContactStorage::delete($this->id);
        //watchdog('bd_contact', 'Deleted BD Contact Submission with id %id.', array('%id' => $this->id));
        \Drupal::logger('bd_contact')->notice('@type: deleted %title.',
            array(
                '@type' => $this->id,
                '%title' => $this->id,
            ));
        drupal_set_message(t('Developer whose evon id is %id now no longer employee of evon.', array('%id' => $this->id)));
        $form_state->setRedirect('bd_contact_list');
      }
    }
    

     

    step 4: Now you have to create an admin page for listing and for that you need to create AdminController.php in Controller directory.

    <?php
    
    namespace Drupal\bd_contact;
    
    use Drupal\Core\Form\ConfirmFormBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Core\Url;
    
    class DeleteForm extends ConfirmFormBase {
      protected $id;
    
      function getFormId() {
        return 'bd_contact_delete';
      }
    
      function getQuestion() {
        return t('Are you sure you want to delete submission %id?', array('%id' => $this->id));
      }
    
      function getConfirmText() {
        return t('Delete');
      }
    
      function getCancelUrl() {
        return new Url('bd_contact_list');
      }
    
      function buildForm(array $form, FormStateInterface $form_state) {
        $this->id = \Drupal::request()->get('id');
        return parent::buildForm($form, $form_state);
      }
    
      function submitForm(array &$form, FormStateInterface $form_state) {
        BdContactStorage::delete($this->id);
        //watchdog('bd_contact', 'Deleted BD Contact Submission with id %id.', array('%id' => $this->id));
        \Drupal::logger('bd_contact')->notice('@type: deleted %title.',
            array(
                '@type' => $this->id,
                '%title' => $this->id,
            ));
        drupal_set_message(t('Developer whose evon id is %id now no longer employee of evon.', array('%id' => $this->id)));
        $form_state->setRedirect('bd_contact_list');
      }
    }
    

    If you get any issue or query regarding this feel free to ask in comment section of the blog.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: