Drupal 8 Custom Module

By | January 12th 2019 11:25:11 AM | viewed 115 times

Create a folder brandinfo8 in the location:projectname/modules/

Create a file brandinfo8.info.yml in the location:projectname/modules/brandinfo8/ and add tho following code

name: Crud for Brand
description: Field API to add fields to entities like nodes and users.
type: module
package: 'Custom Module'
core: '8.x'
version: "8.12"
project: "drupal"
datestamp: "1328134560"

libraries:
  global_brand_style_script
 

Note:After colon must use one space(like name:space Crud for Brand),any para after colon must start after two space(like after libraries colon new para start with space space - space'global_brand_style_script'). it is important for every .yml file

Create a file brandinfo8.libraries.yml in the location:projectname/modules/brandinfo8/ and add tho following code

global_brand_style_script:
  css:
    theme:
      css/demos.css:{}  
  js:
    js/jquery-1.7.2.js:{}
 

Create a file brandinfo8.routing.yml in the location:projectname/modules/brandinfo8/ and add tho following code

brandinfo8.display_brand:
  path: '/admin/brand/index'
  defaults:
    _controller: '\Drupal\brandinfo8\Form\BrandFormController::index'
    _title: 'All Brand'
  requirements:
    _permission: 'access content'	
brandinfo8.new_brand:
  path: '/admin/brand/new'
  defaults:
    _form: '\Drupal\brandinfo8\Form\BrandForm'
    _title: 'New Brand'
  requirements:
    _access: 'true'	
brandinfo8.edit_brand:
  path: '/admin/brand/edit/{id}'
  defaults:
    _form: '\Drupal\brandinfo8\Form\BrandForm'
    _title: 'Update Brand'
  requirements:
    _access: 'true'	
brandinfo8.delete_brand:
  path: '/admin/brand/delete/{id}'
  defaults:
    _controller: '\Drupal\brandinfo8\Form\BrandFormController::delete'
    _title: 'Delete Brand'
  requirements:
    _permission: 'access content'
 

Create a file brandinfo8.install in the location:projectname/modules/brandinfo8/ and add the following code

 <?php
function brandinfo_install() {
}
function brandinfo_uninstall() {
}

function brandinfo_schema() {
    $schema['brand'] = array(
        'description' => 'Brand Category Table',
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'length'=>10,
                'unsigned' => true,
                'not null' => true),
			'btype'=> array(
	            'type'=>'text',
	            'not null'=> true),
            'name' => array(
                'type' => 'text',
                'not null' => true),
			'picture'=> array(
	            'type'=>'text',
	            'not null'=> false),	
        ),
        'primary key' => array('id'),
    );
	
    return $schema;
}

?>
 
 

Create a file brandinfo8.links.menu.yml in the location:projectname/modules/brandinfo8/ and add the following code for creation a administration menu under configuration->development section

brandinfo8.display_brand:
  title: 'Crud Brand List'
  description: 'Crud Brand'
  parent: system.admin_config_development
  route_name: 'brandinfo8.display_brand'

Create a file BrandForm.php in the location:projectname/modules/brandinfo8/src/Form/

 <?php
/**
 * @file
 * Contains \Drupal\brandinfo8\Form\BrandForm.
 */
namespace Drupal\brandinfo8\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Drupal\Core\Url;
use Drupal\Core\Database\Database;
use Symfony\Component\HttpFoundation\RedirectResponse;
class BrandForm extends FormBase {

  
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
  
    return 'brand_form';
  }
  
   /**
       * {@inheritdoc}
     */
  public function buildForm(array $form, FormStateInterface $form_state) {

    //print_r(arg(3));die;
    //$id= $_GET['id'];
	$pathinfo = \Drupal::request()->getpathInfo();
	//$pathinfo = \Drupal::service('path.current')->getPath();
	$path_args = explode('/', $pathinfo);
	
	$conn = Database::getConnection();
    $record = array();
    if (isset($path_args[4])) {
        $query = $conn->select('brand', 'b')
            ->condition('id', $path_args[4])
            ->fields('b');
        $record = $query->execute()->fetchAssoc();
    }
	
	$form['#method'] = 'post';
    $form['#attrubutes'] = array(
        'enctype' => 'multipart/form-data',
        'target' => 'name_of_the_form'
    ); 
	
   $result =array();
   $result['trade']='trade';
   $result['therapic']='therapic';
   $result['generic']='generic';
   $tradeOption = array();

    $form['id'] = array(
        '#type' => 'hidden',
		'#default_value' => (isset($record['id']) && $path_args[4]) ? $record['id']:'',
    );
	
	$form['btype'] = array(
        '#title' => t("Type"),
        '#type' => 'select',
        '#options' => $result,
		'#default_value' => (isset($record['name']) && $path_args[4]) ? $record['btype']:'',
        '#required' => true
    );
	
    $form['name'] = array(
        '#title'=>t('Trade Name:'),
        '#type' => 'textfield',
        '#title' => 'Product Name',
        '#size' => 30,
		'#default_value' => (isset($record['name']) && $path_args[4]) ? $record['name']:'',
        '#required' => true
    );
	
	$form['picture_show'] = array(
        '#prefix' => '<div id="show_pic_div">',
        '#suffix' => </div>'
    );
	$form['pre_picture'] = array(
        '#type' => 'hidden',
		'#default_value' => (isset($record['picture']) && $path_args[4]) ? $record['picture']:'',
    );

    $form['picture'] = array(
        '#title' => t('Image'),
        '#type' => 'managed_file',
        '#description' => t('Only allowed jpg,png,gif and file dimension 500X300px and size'),
        '#upload_location' => 'public://upload/',
        '#required' => false
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'submit'
    );
	
    return $form;
  }
  
   /**
   * {@inheritdoc}
   */
   public function validateForm(array &$form, FormStateInterface $form_state) {
		      /*if (strlen($form_state->getValue('candidate_number')) < 10) {
		                $form_state->setErrorByName('candidate_number', $this->t('Mobile number is too short.'));
		     }*/
	 
    }
	
/**
   * {@inheritdoc}
   */
 public function submitForm(array &$form, FormStateInterface $form_state) {

		        /*foreach ($form_state->getValues() as $key => $value) {
		              drupal_set_message($key . ': ' . $value);
		        }*/
	$err = null;
	$filename = null;
	$file_type = null;
	$file_size = null;
	$file = null;
    $image = $form_state->getValue('picture');	
	$file = (! empty($image))? \Drupal\file\Entity\File::load($image[0]):null;
	$type = $form_state->getValue('btype');
	$name = $form_state->getValue('name');
	//print_r($file->getSize());die;	
	if($file && $file->getFilename()){
	    $filename = $file->getFilename();
	    $file_type = $file->getMimeType();
	    $file_size = $file->getSize();
		
	}else{
	  $pre_picture = $form_state->getValue('pre_picture');
	}

		if (!preg_match("/^[A-Za-z]+([A-Za-z0-9\s])*$/", $name)) {
	        $err = drupal_set_message(t('%productname is invalid', array('%name' => $name)), 'error');
			return false;
	      }

	    if ($filename) {
	        if ($file_type && ($file_type == "image/png") or ($file_type == "image/jpeg") or ($file_type == "image/jpg") or ($file_type == "image/gif")) {            //byte = 50KB
	        } else {
	            $err = drupal_set_message(t('Please enter valid file type'), 'error');
				return false;
	        }


	        if ($file_size && $file_size >1048576) {          // 1*1024*1024 = 1MB
	            $err = drupal_set_message(t('Please enter valid file size'), 'error');
				return false;
	        }
	    } 

		if($form_state->getValue('id')){
		
		  $query = \Drupal::database();
          $query->update('brand')
              ->fields(array(
						'btype' => $type,  
						'name' => $name,
						'picture' => ($filename)? $filename : $pre_picture							
					))
              ->condition('id', $form_state->getValue('id'))
              ->execute();
          drupal_set_message("succesfully updated");
          $form_state->setRedirect('brandinfo8.display_brand');
		
		}else{
		
		   $query = \Drupal::database();
           $query ->insert('brand')
               ->fields(array(
			             'id'=>0,
						'btype' => $type,  
						'name' => $name,
						'picture' => ($filename)? $filename : $pre_picture							
					))
               ->execute();
           drupal_set_message("succesfully saved");
		   $form_state->setRedirect('brandinfo8.display_brand');
           //$response = new RedirectResponse("/admin/brand/index");
           $response->send();
		
		}
	      
   }
   
 }

Note:The annotation @file in the above code is important

Create a file BrandFormController.php in the location:projectname/modules/brandinfo8/src/Form/

 <?php
 /**
 * @file
 * Contains \Drupal\brandinfo8\Form\BrandFormController.
 */
namespace Drupal\brandinfo8\Form;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Database;
use Drupal\Core\Url;
use Drupal\image\Entity\ImageStyle;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\brandinfo8\Form\BrandForm;



class BrandFormController extends ControllerBase {

   public function index(){
     /*return array(
	   '#title'=>'Hi Module'
	   );*/
	   
	  // make table header
	$header_table = array(
     'sl'=>    t('SrNo'),
     'btype' => t('Type'),
     'name' => t('Name'),
     'picture' => t('Picture'),
     'operation' => t('New'),t('Edit'),t('Delete')
    );
	
	  //select records from table
    $query = \Drupal::database()->select('brand', 'b');
    $query->fields('b', ['id','btype','name','picture']);
      $results = $query->execute()->fetchAll();
      $rows = array();
    foreach($results as $data){
	    $new   = Url::fromUserInput('/admin/brand/new');
		$edit   = Url::fromUserInput('/admin/brand/edit/'.$data->id);
        $delete = Url::fromUserInput('/admin/brand/delete/'.$data->id);
		$img = "<img style='width:70px' src='".file_create_url('public://upload/'.$data->picture)."'>";
		
		//$path = 'public://upload//'.$data->picture;
        //$img = ImageStyle::load('style_name')->buildUrl($path);
		
       
         //print the data from table
             $rows[] = array(
                'id' => $data->id,
				'btype' => $data->btype,
                'name' => $data->name,
                'picture' => t($img),
				'operation' =>\Drupal::l('New', $new ),\Drupal::l('Edit', $edit),\Drupal::l('Delete', $delete)
            );
    }
	
	 //display data in site
     $form['table'] = [
            '#type' => 'table',
            '#header' => $header_table,
            '#rows' => $rows,
            '#empty' => t('No users found'),
        ];
        return $form;
	
	
	  //$form = \Drupal::formBuilder()->getForm('Drupal\brandinfo8\Form\BrandForm');
      //return $form;
   }
   
   
   
    public function delete($id = null){
		if($id){
		    $query = \Drupal::database();
	        $query->delete('brand')
	                   ->condition('id',$id)
	                  ->execute();
	        drupal_set_message("succesfully deleted");
			return $this->redirect('brandinfo8.display_brand');
			
		}else{
		    drupal_set_message("deletion fail");
	        return $this->redirect('brandinfo8.display_brand');
		}
		
	}
  
 }

Create a file FormBlock.php in the location:projectname/modules/brandinfo8/src/Plugin/Block for creation a block

<?php
/**
 * @file
 * Contains  Drupal\brandinfo8\Plugin\Block\FormBlock.
 */
namespace Drupal\brandinfo8\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormInterface;
use Drupal\brandinfo8\Form\BrandForm;

/**
 * Provides a 'Form Block' block.
 *
 * @Block(
 *   id = "form_block",
 *   admin_label = @Translation("Form block"),
 *   category = @Translation("Custom form block example")
 * )
 */
 
class FormBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\brandinfo8\Form\BrandForm');
    return $form;
   }
}

Add necesary css, js,image files in the location:projectname/modules/brandinfo8/css/,projectname/modules/brandinfo8/js/,projectname/modules/brandinfo8/images/

Login the as administrator and go to extention-> module-> install them to go configuration->development -> Crud Brand List and click to view list

bONEandALL