Saturday, October 26, 2019

custom module CRUD operations in drupal 8


mydata.info.yml

name: mydata
type: module
description: This dispaly information what you enter your application.
core: 8.x
package: Custom

mydata.routing.yml

# 1.hello word display machin name is lakhan u have to given any name

lakhan.content:
  path: '/hello'
  defaults:
    _controller: '\Drupal\mydata\Controller\MyDataHelloController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

# 2.how to make simple form add two number manchin name is drupal_simple_form must 
# be use underscore(_) of big name

drupal_simple_form.simple_form:
  path: '/simple-form'
  defaults:
    _form: '\Drupal\mydata\Form\SimpleForm'
    _title: 'My cool form calculator'
  requirements:
    _permission: 'access content'

# 3. how to make ajex 

drupal_simple_form.simple_ajax_form:
  path: '/simple-ajax-form'
  defaults:
    _form: '\Drupal\mydata\Form\SimpleAjaxForm'
    _title: 'Our cool ajax form calculator'
  requirements:
    _permission: 'access content'

# 4.curd opretion in drupal 8

mydata.mydata_controller_display:
  path: '/mydata'
  defaults:
    _controller: '\Drupal\mydata\Controller\MydataController::lakhan'
    _title: 'This is for test'
  requirements:
    _permission: 'access content'

mydata.mydata_form:
  path: '/mydata/form/mydata'
  defaults:
    _form: '\Drupal\mydata\Form\MydataForm'
    _title: 'My cool MydataForm'
  requirements:
    _access: 'TRUE'
  

mydata.display_table_controller_display:
  path: '/mydata/hello/table'
  defaults:
    _controller: '\Drupal\mydata\Controller\DisplayTableController::display'
    _title: 'display mydata table'
  requirements:
    _permission: 'access content'

mydata.delete_form:
  path: '/mydata/form/delete/{cid}'
  defaults:
    _form: '\Drupal\mydata\Form\DeleteForm'
    _title: 'DeleteForm'
  requirements:
    _access: 'TRUE'

mydata.display_texonomy:
  path: '/texonomy'
  defaults:
    _controller: '\Drupal\mydata\Controller\MyTexonomyController::display'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

mydata.display_texonomy_term:
  path: '/texonomy/term'
  defaults:
    _entity: '\Drupal\mydata\Entity\MyTexonomyEntity::lakhan'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

mydata.install


<?php

function mydata_schema() {
    $schema['mydata'] = array(
'fields' => array(
'id'=>array(
'type'=>'serial',
'not null' => TRUE,
    ),
'name'=>array(
'type' => 'varchar',
'length' => 40,
'not null' => TRUE,
),
'mobilenumber'=>array(
'type' => 'varchar',
'length' => 40,
'not null' => TRUE,
),
'email'=>array(
'type' => 'varchar',
'length' => 40,
'not null' => TRUE,
),
'age'=>array(
'type' => 'varchar',
'length' => 25,
'not null' => TRUE,
),
'gender'=>array(
'type' => 'varchar',
'length' => 40,
'not null' => TRUE,
),
'address'=>array(
'type' => 'varchar',
'length' => 25,
'not null' => TRUE,
),
),
'primary key' => array('id'),
);
return $schema;
}

step 2: we are going to under Controller Folder 
src/controller/DisplayTableController.php
<?php

namespace Drupal\mydata\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Database;
use Drupal\Core\Url;

/**
 * Class DisplayTableController.
 *
 * @package Drupal\mydata\Controller
 */
class DisplayTableController extends ControllerBase {
  public function display() {
    /**return [
      '#type' => 'markup',
      '#markup' => $this->t('Implement method: display with parameter(s): $name'),
    ];*/

    //create table header
    
    $header_table = array(
      'id'=>    t('SrNo'),
      'name' => t('Name'),
      'mobilenumber' => t('MobileNumber'),
      //'email'=>t('Email'),
      'age' => t('Age'),
      'gender' => t('Gender'),
      //'address' => t('Web site'),
      'opt' => t('operations'),
      'opt1' => t('operations'),
    );

    //select records from table
    $query = \Drupal::database()->select('mydata', 'm');
    $query->fields('m', ['id','name','mobilenumber','email','age','gender','address']);
    $results = $query->execute()->fetchAll();
    $rows=array();
    foreach($results as $data){
      $delete = Url::fromUserInput('/mydata/form/delete/'.$data->id);
      $edit   = Url::fromUserInput('/mydata/form/mydata?num='.$data->id);

      //print the data from table
            
      $rows[] = array(
        'id' =>$data->id,
        'name' => $data->name,
        'mobilenumber' => $data->mobilenumber,
        //'email' => $data->email,
        'age' => $data->age,
        'gender' => $data->gender,
        //'address' => $data->address,
         \Drupal::l('Delete', $delete),
         \Drupal::l('Edit', $edit),
      );
    }
    
    //display data in site
    
    $form['table'] = [
        '#type' => 'table',
        '#header' => $header_table,
        '#rows' => $rows,
        '#empty' => t('No users found'),
    ];
    //echo '<pre>';print_r($form['table']);exit;
    return $form;
  }
}

src/controller/MydataController.php
<?php
namespace Drupal\mydata\Controller;
use Drupal\Core\Controller\ControllerBase;
class MydataController extends ControllerBase {
  public function lakhan() {
    return [
      '#type' => 'markup',
      '#markup' => $this->t('This page contain all inforamtion about my data '),
    ];
  }
}

src/controller/MyDataHelloController.php

<?php

namespace Drupal\mydata\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
 * Defines HelloController class.
 */
class MyDataHelloController extends ControllerBase {
  /**
   * Display the markup.
   *
   * @return array
   *   Return markup array.
   */
  public function content() {
    return [
      '#type' => 'markup',
      '#markup' => $this->t('Hello, Lakhan!'),
    ];
  }
}
src/controller/MyTexonomyController.php
<?php
namespace Drupal\mydata\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Database;
use Drupal\Core\Url;
/**
 * Class DisplayTableController.
 *
 * @package Drupal\mydata\Controller
 */
class MyTexonomyController extends ControllerBase {
  public function display() {
    
    $header_table = array(
      'id'=>    t('SrNo'),
      'name' => t('Name'),
      'depth' => t('Depth'),  
    );
    $vid = 'Tags';
  $terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
  // echo "<pre>";
  //  print_r($terms);
  //   die();
  foreach ($terms as $term) {

    if($term->depth == 1){
   $term_data[] = array(
    "id" => $term->tid,
    "name" => $term->name,
    "depth" => $term->depth,
   );
 }
 }
  //display data in site
    
    $form['table'] = [
        '#type' => 'table',
        '#header' => $header_table,
        '#rows' => $term_data,
        '#empty' => t('No users found'),
    ];
    //echo '<pre>';print_r($form['table']);exit;
    return $form;
  }
}
step 3: we are going to under form Folder

src/Form/DeleteForm.php

<?php
namespace Drupal\mydata\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Url;
use Drupal\Core\Render\Element;
/**
 * Class DeleteForm.
 *
 * @package Drupal\mydata\Form
 */
class DeleteForm extends ConfirmFormBase {


  /**
   * {@inheritdoc}
   */

  /**
   * all are predifine function in use Drupal\Core\Form\FormBase;
     1. getFormId();
     2. getModuleName();
     3. getQuestion();
     4. getCancelUrl();
     5. getDescription();
     6. getConfirmText();
     7. function getCancelText();

   */



  public function getFormId() {
    return 'delete_form';
  }
  public $cid;

  public function getQuestion() { 
    return t('Do you want to delete %cid?', array('%cid' => $this->cid));
  }

  public function getCancelUrl() {
    return new Url('mydata.display_table_controller_display');
  }
  
  public function getDescription() {
    return t('Only do this if you are sure!');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return t('Delete it!');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelText() {
    return t('Cancel');
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $cid = NULL){ 
     $this->id = $cid;
    return parent::buildForm($form, $form_state);
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // $num=$form_state->getValues('id');
    // echo "$num";
    // $name=$field['id'];
    // echo "$name";
    // die;

    //print_r($form_state);die;
    $query = \Drupal::database();
    //echo $this->id; die;
    $query->delete('mydata')
        //->fields($field)
        ->condition('id',$this->id)
        ->execute();
        //if($query == TRUE){
             drupal_set_message("succesfully deleted");
        //    }
        // else{

        //   drupal_set_message(" not succesfully deleted");

        // }
    $form_state->setRedirect('mydata.display_table_controller_display');
  }


  //   $num_deleted = db_delete('mydata')
  // ->condition('id', 1)
  // ->execute();

  //     if($num_deleted == TRUE){
  //        drupal_set_message("deleted suceesfully");
  //      }
  //    else
  //     {

  //       drupal_set_message(" unsucessfully");
  //      }
  
  // }
}

src/Form/MydataForm.php
<?php

namespace Drupal\mydata\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;
use Symfony\Component\HttpFoundation\RedirectResponse;

use Drupal\Core\Url;
class MydataForm extends FormBase {

  public function getFormId() {
    return 'mydata_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $conn = Database::getConnection();
    $record = array();
    if (isset($_GET['num'])) {
      $query = $conn->select('mydata', 'm')
          ->condition('id', $_GET['num'])
          ->fields('m');
      $record = $query->execute()->fetchAssoc();
    }
    // print "<pre>";
    // print_r($record);
    // die();

    $form['candidate_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Full Name:'),
      '#required' => TRUE,
       //'#default_values' => array(array('id')),
      '#default_value' => (isset($record['name']) && $_GET['num']) ? $record['name']:'',
    );
    // print"<pre>";
    // print_r($form);die();

    $form['mobile_number'] = array(
      '#type' => 'textfield',
      '#title' => t('Mobile Number:'),
      '#default_value' => (isset($record['mobilenumber']) && $_GET['num']) ? $record['mobilenumber']:'',
    );

    $form['candidate_mail'] = array(
      '#type' => 'email',
      '#title' => t('Email ID:'),
      '#required' => TRUE,
      '#default_value' => (isset($record['email']) && $_GET['num']) ? $record['email']:'',
    );

    $form['candidate_age'] = array (
      '#type' => 'textfield',
      '#title' => t('AGE'),
      '#required' => TRUE,
      '#default_value' => (isset($record['age']) && $_GET['num']) ? $record['age']:'',
    );

    $form['candidate_gender'] = array (
      '#type' => 'select',
      '#title' => ('Gender'),
      '#options' => array(   
        'Female' => t('Female'),
        'male' => t('Male'),
        '#default_value' => (isset($record['gender']) && $_GET['num']) ? $record['gender']:'',
     
      ),
    );

    $form['address'] = array (
      '#type' => 'textfield',
      '#title' => t('address'),
      '#default_value' => (isset($record['address']) && $_GET['num']) ? $record['address']:'',
    );

  //   $form['link'] = array(
  //   '#type' => 'url',
  //   '#title' => $this->t('Link title'),
  //   '#options' => ['external' => TRUE],
  // );

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'save',
      //'#value' => t('Submit'),
    ];
    return $form;
  }
  
  public function validateForm(array &$form, FormStateInterface $form_state) {

   $name = $form_state->getValue('candidate_name');
    if(preg_match('/[^A-Za-z]/', $name)) {
      $form_state->setErrorByName('candidate_name', $this->t('your name must in characters without space'));
    }

    //Confirm that age is numeric.
    if (!intval($form_state->getValue('candidate_age'))) {
      $form_state->setErrorByName('candidate_age', $this->t('Age needs to be a number'));
    }

    // $number = $form_state->getValue('candidate_age');
    // if(!preg_match('/[^A-Za-z]/', $number)) {
    //    $form_state->setErrorByName('candidate_age', $this->t('your age must in numbers'));
    // }

    if (strlen($form_state->getValue('mobile_number')) < 10 ) {
      $form_state->setErrorByName('mobile_number', $this->t('your mobile number must in 10 digits'));
    }
    parent::validateForm($form, $form_state);
  }

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

    // print "<pre>";
    // print_r($form_state);
    // die();   
    $field=$form_state->getValues();
    
    // $lakhan = $form_state->getValue('candidate_name');
    // echo "$lakhan";
    // die();
    $name=$field['candidate_name'];
    //echo "$name";
    $number=$field['mobile_number'];
    $email=$field['candidate_mail'];
    $age=$field['candidate_age'];
    $gender=$field['candidate_gender'];
    $Address=$field['address'];

  
   //method 1 insert data in data base ame is d7

    // $insert = array('name' => $name, 'mobilenumber' => $number, 'email' => $email, 'age' => $age, 'gender' => $gender, 'address' => $address);
    // db_insert('mydata')
    // ->fields($insert)
    // ->execute();

    // if($insert == TRUE)
    // {
    //   drupal_set_message("your application subimitted successfully");
    // }
    // else
    // {
    //   drupal_set_message("your application not subimitted ");
    // }

    if (isset($_GET['num'])) {
        $field  = array(
            'name'   => $name,
            'mobilenumber' =>  $number,
            'email' =>  $email,
            'age' => $age,
            'gender' => $gender,
            'address' => $Address,
        );
        $query = \Drupal::database();
        $query->update('mydata')
            ->fields($field)
            ->condition('id', $_GET['num'])
            ->execute();
        drupal_set_message("succesfully updated");
        $form_state->setRedirect('mydata.display_table_controller_display');
      }
    else
       {
        //show all data 
        
        // foreach ($form_state->getValues() as $key => $value) {
        //   drupal_set_message($key . ': ' . $value);
        // }
         
         //method 2 like ci mvc insert data in data base

          $field  = array(
            'name'   =>  $name,
            'mobilenumber' =>  $number,
            'email' =>  $email,
            'age' => $age,
            'gender' => $gender,
            'address' => $Address,
          );
          $query = \Drupal::database();
          $query ->insert('mydata')
             ->fields($field)
             ->execute();
          drupal_set_message("succesfully saved");

           //work direct path
          // $response = new RedirectResponse("/mydata/hello/table");
         
          $response = new RedirectResponse(Url::fromUserInput('/mydata/hello/table')->toString());
          $response->send();
        }
  }
}
src/Form/SimpleAjaxForm.php
<?php

namespace Drupal\mydata\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

/**
 * Our simple form class.
 */
class SimpleAjaxForm extends FormBase {

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

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

    $form['massage'] = [
      '#type' => 'markup',
      '#markup' => '<div class="result_message"></div>',
    ];

    $form['number_1'] = [
      '#type' => 'textfield',
      '#title' => $this->t('First number'),
    ];

    $form['number_2'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Second number'),
    ];

    $form['actions'] = [
      '#type' => 'button',
      '#value' => $this->t('Calculate'),
      '#ajax' => [
        'callback' => '::setMessage',
      ]
    ];

    return $form;
  }

  public function setMessage(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    $response->addCommand(
      new HtmlCommand(
        '.result_message',
        '<div class="my_top_message">' . $this->t('The result is @result', ['@result' => ($form_state->getValue('number_1') + $form_state->getValue('number_2'))])
        )
    );

    return $response;
  }
// Class Drupal\mydata\Form\SimpleAjaxForm 
// contains abstract method and must therefore be declared abstract or implement the
// remaining methods 
// (Drupal\Core\Form\FormInterface::submitForm) 
// in /var/www/html/drupal-test/modules/mydata/src/Form/SimpleAjaxForm.php on line 69
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
  }

}

src/Form/SimpleForm.php
<?php

namespace Drupal\mydata\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
 * Our simple form class.
 */
class SimpleForm extends FormBase {

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

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

    $form['number_1'] = [
      '#type' => 'textfield',
      '#title' => $this->t('First number'),
    ];

    $form['number_2'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Second number'),
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Calculate'),
    ];

 return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // drupal_set_message($form_state->getValue('number_1') + $form_state->getValue('number_2'));
    $data = $form_state->getValue('number_1');
    $data2 = $form_state->getValue('number_2');
    $result = $data + $data2;
     // print $result;
     // die();
  }

}
src/Plugin/Block/HelloBlock.php
<?php
/**
 * @file
 * Contains \Drupal\module_name\Plugin\Block\HelloBlock.
 */
namespace Drupal\mydata\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 * Provides a 'Hello' Block
 *
 * @Block(
 *   id = "hello_block",
 *   admin_label = @Translation("Hello block"),
 * )
 */
class HelloBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}
src/Plugin/Block/MydataBlock.php
<?php

namespace Drupal\mydata\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 * Provides a 'MydataBlock' block.
 *
 * @Block(
 *  id = "mydata_block",
 *  admin_label = @Translation("Mydata block"),
 * )
 */
class MydataBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    ////$build = [];
    //$build['mydata_block']['#markup'] = 'Implement MydataBlock.';

     $form = \Drupal::formBuilder()->getForm('Drupal\mydata\Form\MydataForm');
    //dsm($form);
    return $form;
  }

}
src/Entity/MyTaxonomyEntity.php

<?php


namespace Drupal\mydata\Entity;
  use Drupal\taxonomy\Entity\Term;      
  use Drupal\Core\Link;
  use Drupal\Core\Url;


class MyTaxonomyEntity extends Term {
   /**
   * {@inheritdoc}
   */
public function lakhan() {
    $query = new entityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'taxonomy_vocabulary')
  ->propertyCondition('machine_name', 'Tags')
  ->execute();

if (empty($result['taxonomy_vocabulary'])) {
  return;
}

$vocabularies = taxonomy_vocabulary_load_multiple(array_keys($result['taxonomy_vocabulary']));
dpm($vocabularies);
  }
}

No comments:

Post a Comment

If you have any problem please let me know.