Showing posts with label custom module. Show all posts
Showing posts with label custom module. Show all posts

Tuesday 11 February 2020

How to create tabs by custom module in drupal 8?

Today we will discuss about, how to create new tab in custom module and set the linking. So before start, we will clear some points for custom module.
1. "module_name.links.task.yml" and "module_name.routing.yml" is important file, if we are going to create tabs.
2. Now Please follow the syntax, we will explain here for all parameters and syntax for tabs.
Example Syntax:   Here 'account_login' is example of my module name..

account_login.tab_1:                                   // This is the Tab Routers
  route_name : account_login.content         // This is route name and we will use this in routing.yml  file when we create routers and path
  title: account login                                   // This is Title of Tabs.
  base_route: account_login.content          // This is for set default open Tab
  weight: 10                                                // This is for tab weight or for order of Tab

account_login.tab_2:                                   // This is for second Tab Router
  route_name: account_login_otp.content   // This is route name and we will use this in routing.yml file when we create routers and path
  title: Work                                                 // This is Title of Tabs.
  base_route: account_login.content           // This is for set default open Tab
  weight: 20                                                 // This is for tab weight or for order of Tab

 
 
Now we will create "routing.yml" file.
Example Syntax:   Here 'account_login' is example of my module name..

account_login.content:        // so we will use same route name for first tab which we use in 'links.task.yml' file
   path: '/account/login'
   defaults:
   # Calls the list controller, defined in the annotation of the product entity.      
    _form: '\Drupal\account_login\Plugin\Form\userloginForm'
    -title: 'Two Way Authentication Login'
   requirements:
    _permission: 'access content'
    _user_is_logged_in: 'FALSE'
   
account_login_otp.content:                             // We will use same route name for second tab which we use in 'links.task.yml' file
   path: '/account/login/authenticate'
   defaults:
   # Calls the list controller, defined in the annotation of the product entity.      
    _form: '\Drupal\account_login\Plugin\Form\userloginotpForm'
    -title: 'Login Form Authenticate'
   requirements:
    _permission: 'access content'   
    _user_is_logged_in: 'FALSE'
   

   
Now just we have to install custom module and and clear the cache then put the first URL on brower (Ex: /account/login) and its will show our Tabs. So simple way to easily create custom tabs.


Note: What is Namespace and Use keyword in drupal 8 module?

Tuesday 7 January 2020

What is Namespace and Use keyword in drupal 8 module?

Namespace: Namespace is a way of Organizing your classes into folder and ensure that your class does not conflict with another class with the same name because the class can be same but namespace will be unique.

Use Keyword: use keyword allows you to use classes from another namespaces when you need them.

Drupal 8 generally use PHP classes instead of functions. Two classes can have same name in different namespace. Namespace is way of organize the classes into folders and subfolders and the namespace as the path of the file.

If you will try the same name file with the same name in same folder, you will get the fetal error. but if you want to create the same name file then you have to create subfolder and put there.

Get the example of namespaces with create module.

1. Start the custom module with create directory name like 'testing'.
2. Now create 'info.yml' file. That file tells Drupal that your module exist and have some content/information.

The filename should be the machine name of your module with .info.yml extension, like testing is our module name so here name will be 'testing.info.yml'.
File content:
    name: Testing
    description: A custom module to build our Drupal 8 module
    package: Custom
    type: module
    version: 1.0
    core: 8.x

   
3. Some modules have controllers, plugins, forms, templates, test all are in src folder. So now we will create the src required folder.
4. Now we need a page controller for show the content output with these simple steps:
  a. Create src folder.
  b. now create Controller folder under the src folder.
  c. within the Controller folder , create file with name of 'TestingController.php'.
In the 'TestingController.php' file we will print our short message for testing.

    /**
     * @file
     * Contains \Drupal\testing\Controller\TestingController.
     */
    namespace Drupal\testing\Controller;
    
    use Drupal\Core\Controller\ControllerBase;
    
    class TestingController extends ControllerBase {
      public function content() {
        return array(
          '#type' => 'markup',
          '#markup' => t('Hello, we are here for testing.'),
        );
      }
    } 
 

Here the namespace has been defined as Drupal\testing\Controller. We will not here use full folder structure like ->  Drupal\modules\testing\src\Controller

here modules\src is silent from namespace and Drupal automatically mapped with namespace src folder, so that we have to follow standard folder structure of modules.

If we have to use TestingController class in different namespace then we have to include with 'use keyword' as its namespace -> use Drupal\testing\Controller\TestingController;

TestingController is extending another class called ControllerBase. So for get the classes, include ControllerBase with use statement -> use Drupal\Core\Controller\ControllerBase;

If use statement are not included then PHP will looking for ControllerBase and gives error.
"So use statement allows you to use classes from another namespace."

5. Now we have to create important file with name of 'routing.yml'. here the name will be 'testing.routing.yml' that will create in custom module root.

    testing.content:
      path: '/testing'
      defaults:
        _controller: 'Drupal\testing\Controller\TestingController::content'
        _title: 'Hello Tester'
      requirements:
        _permission: 'access content'

       
so now enable the module and clear the cache then go with the path '/testing' and get the output form controller.
       

Note: What is Namespace and Use keyword in drupal 8 module?

Thursday 24 January 2019

How to render template for custom module in drupal 8?

It is easy way to render/call template(.html.twig) file for custom module in drupal 8, But here concept is slightly different from drupal 7.
First we will go to the Controller file:
Like our controller name is ContactController.php so we will write there code like.
//Go to the ContactController.php file..
/**
 * @file
 * Contains \Drupal\contact\Controller\ContactController.
 */

namespace Drupal\contact\Controller;
use Drupal\node\Entity\Node;
use Drupal\Core\Controller\ControllerBase;


class Contactv4Controller extends ControllerBase {  
    public function indexv2() {
     
      $data = "<div>Testing</div>";
     
      return [
       '#theme'  => 'specific_contact',
       '#contact'   => $data,
    ];
  }
}

// Then go to the contact.module file.
/**
* Implements hook_theme() to add the template definition..
**/
function contact_theme($existing, $type, $theme, $path) {
  return array(
       'specific_contact' => [
        'variables' => [
            'contact' => NULL,
       ]
    ]
  );
}
 
// Now in the create template folder and the file with name of 'specific_contact.html.twig'.
And render the variable there like: <p> {{ contact }} </p>
And clear the cache after this.
Now Front end result will be 'Testing' on new template page.


Note: If have any suggestions or issue regarding 'How to render template for custom module in drupal 8?' then you can ask by comments.   

Thursday 20 December 2018

How to add custom js file in custom module in drupal 8 ?

It is very simple way to add custom JQuery file in custom module, but we have few methods for this.

Method 1: Our custom libraries(js/css) will be apply on all pages of project.
If we want to add custom js file in whole pages of project then we have to use this method.

1. First we have to create js file like 'gallery.js' file in js folder in our custom module.
2. Then we have to create a 'hook.libraries.yml' file means there hook will be module name.
     
Example: Suppose our Module name will be 'gallery' So we will create file with name of     'gallery.libraries.yml' in custom module folder means this file should be placed with '.routing.yml' file.
3. The code for '.libraries.yml' file is..

image_gallery:
  version: 8.4.5
  js:
    js/gallery.js: {}   
  dependencies:
    - core/jquery
  css:
    theme:
      css/gallery.css: {}


Note: There is a library called image_gallery that when included in a page will deliver the 'js/gallery.js' and 'css/gallery.css' file.

4. Then we have to create '.module' file.

Example: Suppose our Module name is gallery so file name will be 'gallery.module'. There our code for attachment of this library to our module is..

<?php
function gallery_page_attachments(array &$attachments) {
   $attachments['#attached']['library'][] = 'gallery/image_gallery';
}
?>

5. Here 'gallery/image_gallery' means 'module name/libraries name' and in the time of controller function return of page will be written like..
return array('#markup' => t($html)); // here $html is return the result for page.   

Method 2: Our custom libraries(js/css) will be apply only on custom module pages of project.  
1. Whole process and file creation will be same but we will not use attachments code in '.module' file.
2. In this case we just have to create '.libraries.yml' file and apply code..

image_gallery:
  version: 8.4.5
  js:
    js/gallery.js: {}   
  dependencies:
    - core/jquery
  css:
    theme:
      css/gallery.css: {}

     
3. Then in the time of controller function return of page will be written like..
   
return [
    '#markup' => t($html),
    '#attached' => array(
        'library' => array(
            'gallery/image_gallery',
        ),
    ),
];       


here 'gallery/image_gallery' means 'module name/libraries name' and '$html' is the written result for page.

Note: If have any suggestions or issue regarding 'How to add custom js file in custom module in drupal 8 ?' then you can ask by comments.   

Monday 17 September 2018

How to create Schema in custom module drupal 8?

When we need to create our custom module table, So we have to create schema file in custom module root like if our module name is `crudform`, so in the folder of module we will create file which name is `crudform.install`. here our file extension will be `.install` for schema.
In the file we will create function `hook_schema()` with name of `crudform_schema()` and there we will define create structure of table with table name, we have an example for this, Please have a look..

Schema database

function crudform_schema() {
  $schema['crudform'] = array(
    'fields' => array(
          'id'=>array(
            'type'=>'serial',
            'not null' => TRUE,
          ),
          'name'=>array(
            'type' => 'varchar',
            'length' => 40,
            'not null' => TRUE,
          ),
           'email'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
            'city'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
            'country'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
          'message'=>array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
          ),
    ),
    'primary key' => array('id'),
  );
  return $schema;
}

In that function crudform_schema(), our database table name will be `crudform`. here we will define table fields and structure and then return the schema. When we will install our custom module then this table with schema will automatically create in database and with the help of this we can store data in our custom table.


If we want to store default data on table then we have to use `hook_install` function In case of installation of module that data will store automatically. We have an example for this, please have a look..

function crudform_install() {
  $database = \Drupal::database();
  // Add default entry in table.
  $fields = array(
    'name' => 'Sahil',
    'email' => 'sahil@gmail.com',
    'city' => 'Delhi',
    'country' => 'India',
    'message' => 'Hello text',
  );
  $database->insert('crudform')
    ->fields($fields)
    ->execute();
  
  // Add one another entry on this table.
  $fields = array(
    'name' => 'Abhi',
    'email' => 'abhi@gmail.com',
    'city' => 'Delhi',
    'country' => 'India',
    'message' => 'Hello text world',
  );
  $database->insert('crudform')
    ->fields($fields)
    ->execute();
}

There we are creating a $fields array with few data and then store by insert query.
So that's a simple process of 'create schema in drupal 8 custom module'.


Note: If have any suggestions or issue regarding 'How to create Schema in custom module drupal 8?' then you can ask by comments.   

How to resolve max execution time error in drupal ?

When you found error regarding 'max_execution_time' exceed, then you can follow steps for resolve this error: Steps:   You can put t...