GetCoding
  • Home
  • Courses
  • Contact
Category:

Programming

DrupalLearningPHPProgrammingTutorial

Drupal 9 – Custom module development – Simple Module

by Matt Heff 1 year ago
written by Matt Heff

After working with drupal for years I am amazed by the number of custom modules out there and what they have unleased for business’s that have used them and continue to innovate more. The ones I refer to here are the publicly accessable ones, I believe there are just as many which are private and are highly specialised to the business that have them developed. This is the use case I am wanting to target here. These Custom Modules are ones you can create for a clients specific needs.

In Drupal 9 custom modules off there flexibility to create entirely new features and/or adjust existing ones to enhance a business’s growth or open up new lines of what they offer. It allows virtually unlimited creativity and possibility for owner of a Drupal system. For Developers if offers then a way to provide highly novel solutions for those busssiness.

The aim of this article is to help you build your first basic custom module in Drupal 9. Note these will also work for Drupal 8 ( D8 is end of life and migration plans ideally would be underway, if not, reach out to me and we may be able to work together on it)

Drupal 9 Module development

Lets getCoding! and create this module in just a few phases.

Phase 1: The Name

A great place to start is to decide on the name of your module and then we can create it under the folder path “/modules/custom”. The one ill choose for this article is “simple_module“. You will notice my root folder is called drupal_tutorals yours may be configured as web, root or something else

Rules for naming:

  • start it with lower case letters, (simple_module, not, Simple_Module)
  • no spaces in the name. ( simple_module, not, simple module)

done!, lets get onto the next phase

Phase 2: Create info.yml file ( for Drupal to recognise it)

Next we need to create a .yml file. If you are unfamiliar with what a .yml ( or .yaml) file is it is a format that is great for storing configuration it is a superset of JSON and not a markup language, if you want to learn more about JSON read this article.

So in short the .yml is a configuration file for our module which allows drupal to know about it. We create a file in our new folder (simple_module) and call it simple_module.info.yml, put the following code into it

name: Simple Module
type: module
description: 'Demo a creating a simple Drupal 9 Module.'
package: Custom
version: 0.5
core_version_requirement: ^8 || ^9

Lets look at what each of these config items is

name: This is the name that will get displayed in the modules list in our Drupal admin section

type: this will be either module or theme, in our case module

description: a longer description of the module that will appear in the Drupal admin section under the name

package: specify this as being custom module

version: this is our module version, I have put 0.5 as it is in dev, for a full ready release it should go out as 1.0 )

core_version_requirement: let it know which versions of Drupal this will work with ( 8/9)

That is our config done! Nice we are almost there now we just need to add our Router file and our controller!

Phase 3: Create Module Routing, routing.yml

I really like the routing system in Drupal 8/9, it replaces the routing parts of the hooks_menu() that was in Drupal 7. The routing system is mostly based on Symfony’s, so where I say mostly it can do everything that Symfony’s can and more, both Drupal 8/9 and Symfony use the same syntax to define routes.

In short: Routing is where our pages will be accessed via URL’s

Create a file simple_module.routing.yml in our simple_module folder and add the following

simple_module.demopage:
  path: '/simple/demopage'
  defaults:
    _controller: '\Drupal\simple_module\Controller
\SimpleController::demopage'
    _title: 'Simple Demo page for Drupal 9'
  requirements: 
    _permission: 'access content'

So lets unpack what we have here in the simple_module.routing.yml file

Line #1: is the route name

Line #2: The URL page this route will be regestered to eg https://demo.com/simple/demopage

Line #4: Is a reference to the _controller and a demopage class() that is within this controller ( we will be making this file next)

Line #5: The _title ( default title ) of the page for the controller we specify in Line #4

Line #7: List of _permission that are needed to access the module, here we just want a public page so access content is the only one needed, if we were creating an admin page or something within a user profile then we would add some more restrictive permissions

So far we have now got the shell of our module ( phase 1 & 2 ) the routing information of where to access the page we are making ( phasev3) . Now for our final phase.

As mentioned on Line #4: The controller is what we need next so that we can build out the meat of our custom module and put in the actual behavours of what will be on the page this is what our controller will do

Phase 4: Create a Controller

In the folder we created in step 1 (/modules/custom/simple_module) we need to create some additional folders

(/modules/custom/simple_module/src/Controller) and also a file “SimpleController.php” and in it put the following

<?php
namespace Drupal\simple_module\Controller;
class SimpleController {
  public function demopage() {
    return array(
      '#markup' =----> 'Congratulations, you have made your a Custom Module in Drupal 9!</br>Time to Celebrate!</br>Don't forget to reward yourself!'
    );
  }
}

From here we are done with the code!

Your files should look something like this

Log into your Drupal installation and enable the simple module we just created. As always we need to check that what we have done works so navigate to /simple/demopage , you may need to clear the cache if it does not work.

admin / configuration / performance and then clear cache on that page.

Try the location /simple/demopage again.

Thats the end. Whilst the module itself does not do anything you now are able to create a custom module and then implement what it is your client or company needs.

You can access the code for this module at this GitHub repo

1 year ago 0 comment
TwitterLinkedin
BlogFeaturedJavaScriptNodeJSProgrammingTutorial

Create a RESTful API in NodeJS

by Matt Heff 1 year ago
written by Matt Heff

Ever wanted to create your very own API or do you just need some syntax for something that you are currently working on? Well we have you covered!

Tools you will need

  • Visual Code
  • Command line
  • Node / npm installed
  • Postman ( or some way to interact with the API)

Navigate to the directory you want to set up this project in

cd /home/heff/Code/NodeJS/ApiTutorial-Simple
npm init
npm install express cors
code .

Create Products.JSON

Create a file name products.json in the root directory and put the following JSON into it, this is a simple product database that we will read/update/create/delete ( get, put, post, delete ).

I have no intention of permanently altering this data, we will load it into the memory of the service and then modify it but after the service is terminated nothing will be retains. This is especially helpful once we start deleting.

[
  {
    "id": "Prod1",
    "name": "Online Product #1",
    "type": "online",
    "qty": null,
    "price": 10.5
  },
  {
    "id": "Prod2",
    "name": "Shipping Product #2",
    "type": "physical",
    "qty": 55,
    "price": 17.5,
    "shipping_price": 10
  },
  {
    "id": "Prod3",
    "name": "Online Course Product #3",
    "type": "physical",
    "qty": 55,
    "price": 17.5,
    "shipping_price": 10
  }
]

Create a Server.js file

Create a server.js file and this is the one we will be having node execute for us we will put together in sections and test along the way the sequence will be

  • Load the Products Data
  • Initialise the API Service
  • Create GET
    • Get All
    • Get by ID
  • PUT
  • POST
  • DELETE

ok now we are ready to GetCoding!

Load the Products Data

Run: node server.js

let products = require("./products.json");

console.log(products)

use the command node sever.jsAfter that you should see the products JSON object written to the console like in the image below

Great! Now lets make a service that will listen to us

Initialise the API Service

Add the following code to your server.js file what we are doing here is getting our service setup and configured so it will sit and listen for instruction i have included some CORS handling incase anyone tries to do test this via their browser console instead of postman

const express = require("express");
const cors = require("cors");
const app = express();

var corsOptions = {
  origin: "http://localhost:9999",
};

app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));


////////////////////////////////////////
//Insert GET/PUT/POST/DELETE functions in this section

//Get functions
app.get("/product", function (req, res) {
  res.json(products);
});

app.get("/product/:id", function (req, res) {
  let item = products.find((product) => product.id === req.params.id);
  res.json(item);
});

//put functions

// post functions

// delete functions

////////////////////////////////////////


var server = app.listen(9999, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log(`Simple API listening on host: ${host} with port: ${port} `);
});

if you run this now you will have a service start up and sit there listening on port 9999, how cool is that!

You can use postman now to perform a get on

  • http://localhost:9999/product
  • http://localhost:9999/product/Prod1

Postman gives the following results,

At this stage you now have a very basic API! If this is your first time congratulations! I hope you remember me!

Try out looking for Prod2 & Prod3 even a Prod4 that does not exist to see what happens.

PUT

Add the following code under the comment //PUT functions

Here we need to make sure the data send to us is not empty, from there we look for where our item is in the product list and once we find it ( assuming we do ) we will update it with the JSON sent, the whole record must be sent, sending only partial data will result in data missing.

app.put("/product/:id", function (req, res) {
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!",
    });
  }
  console.log(req.body);
  //find the product by id and update it 
  let index = products.findIndex((x) => x.id == req.params.id);
  products[index] = req.body;

  console.log(products);
  res.json(products);
});

POST

Add the following code under the comment //POST functions

Here we need to make sure the data send to us is not empty, from there we look for where our item is in the product list and if we don’t find it we create a new one otherwise let them know one already exists.

app.post("/product", function (req, res) {
  if (!req.body) {
    res.status(400).send({
      message: "Content can not be empty!",
    });
  }
  // check to see if there is a product that exists with that id
  let index = products.findIndex((x) => x.id == req.body.id);
  if (index !== -1) {
    res.status(400).send({
      message: `Item already exists wth the ID: ${req.body.id}`,
    });
  }
  //add new product to the list 
  products.push(req.body);
  res.json(products);
});

DELETE

Add the following code under the comment //DELETE functions

The code below looks for a matching product with the value that was passed to it and if it finds one it will remove it from the product list.

app.delete("/product/:id", function (req, res) {
  //here we remove the product from our list if it is found
  let tmp = products.filter((item) => item.id !== req.params.id);
  products = tmp;
  console.log(products);
  res.send(products);
});

GITHUB

You can find the code for this in github as well as a collection from postman so you can test out the API

GitHub Repo

NodeJS.postman_collectionDownload
1 year ago 0 comment
TwitterLinkedin
BlogJavaScriptProgramming

How to Add Hours to a Date Object in JavaScript

by Matt Heff 1 year ago
written by Matt Heff 5 read

As if programming and dealing with dates did not have enough headaches that come from timezones, daylight savings, leap years the JavaScript Date API does not offer us a way to add hours to Date objects.

Fortunately with this tutorial we are going to do this ourselves and do it a couple of ways.

Method 1: Create a function ( use Date.setHours() )

function addHours(dateObj, hours){
   //We create a new Date Object so that we dont alter the one passed into the function (this is a pure function )
   const dateUpdated = new Date(dateObj.getTime());
   dateUpdated.setHours( dateUpdated.getHours() + hours);
   return dateUpdated;
}


const dateDemo = new Date('2022-06-22T12:00:00.000Z'); 
console.log(dateDemo); //2022-06-22T12:00:00.000Z

let dateModified = addHours(dateDemo,1)
console.log(dateModified); //2022-06-22T13:00:00.000Z

dateModified = addHours(dateDemo,3); //Original Date is not modified
console.log(dateModified); //2022-06-22T15:00:00.000Z

dateModified = addHours(dateModified,3)
console.log(dateModified); //2022-06-22T18:00:00.000Z


In the above function we create the variable dateUpdated and create a new Date Object so that the dateObj that is passed does not get modified. The Date.setHours() function updates the object, the above implementation is a pure state function, this will help prevent unexpected behaviours.

Method 2: Use NPM Package date-fns

If you are inclined to use NPM packages then this is a great one to make dates a little nicer in JavaScript or NodeJS

So this assumes you have NodeJS installed or an IDE where you can install NPM packages, you can install the package via the command below. We are only going to focus on demonstrating the addHours functionality.

npm install date-fns

import { addHours } from 'date-fns';

const date = new Date('2022-06-22T12:00:00.000Z');

//Add 1 hour to the existing date
let newDate = addHours(date, 1);
console.log(newDate); // 2022-06-22T13:00:00.000Z

//Add 2 hour to the already updated date
newDate = addHours(newDate, 2);
console.log(newDate); // 2022-06-22T15:00:00.000Z

//Original Date Object has not been modified
console.log(date); // 2022-05-15T12:00:00.000Z

The NPM package offers loads of date functions if you are in a situation to use this i would recommend it, anything that makes our lives easier with dates is worthwhile!

A few examples of date-fns functions

addDays, addHours, subHours, addMinutes, subMinutes, addSeconds, subSeconds, subDays, addWeeks, subWeeks, addYears, subYears,

Code Repo

Github: Example 1

Github: Example 2

1 year ago 0 comment
TwitterLinkedin
BlogJavaScriptProgrammingTutorial

Create your own JSON.stringify() function

by Matt Heff 1 year ago
written by Matt Heff

If you have been around the traps the JavaScript for a while you will know JSON.stringify(), you may have have even used it to compare objects, make clones of objects and arrays or even work with RESTful API’s. Using it is not enough of people like you and me, we must pull it apart, look under the hood and then make our own version of it.

This is a two way operation JSON.stringify() will turn objects into strings the inverse of that is JSON.parse() which will objectify strings. This is a good type of objectification.

Example of JSON.stringify() and JSON.parse()

const demoJsonObj = {
  mission: "CreateJsonStringify",
  timeToComplete: 10,
  useExistingFunction: false,
  reasons: ['Inquisitive','Masochist','Bragging Rights'],
  toolsAllowed:{
    language: "JavaScript",
    enhancer: "Coffee",
    motivation: "Binaural Beats",
    alternativeMethod: "Youtube - Check out my video tutorial"
  }
};

console.log(JSON.stringify(demoJsonObj));
// Output
//{"mission":"CreateJsonStringify","timeToComplete":10,"useExistingFunction":false,"reasons":["Inquisitive","Masochist","Bragging Rights"],"toolsAllowed":{"language":"JavaScript","enhancer":"Coffee","motivation":"Binaural Beats","alternativeMethod":"Youtube - Check out my video tutorial"}}


//Test the string is valid by parsing it back
console.log(JSON.parse(JSON.stringify(demoJsonObj)));

Ok that was nice and easy, we can pass the JavaScript Object and get a JSON String. Job done for 99% of folks out there. Not for us! Roll up your sleeves as we are only just about to GetCoding!

Where to begin?

Shall we jump in and start bashing out some code to start with? Or shall we have a think about what we are going to be doing here?

I’d start bashing on the keyboard, only to get 5 mins and and be like hmmmm. So here I am faced with the question how to we take a JSON Object and convert it into a JSON String?

What is a JSON Object? What can be in it? Do we need to cover all cases? Are there any weird things that could happen?

How do I go through each object item? What if it is an array of items? What if there is a object in the object? What if there is a array in the object or in the objects object array . . . . .does that even make sense?

Hmmm thats a lot of questions, Lets start with what is a JSON Object W3schools and MDN — I found the W3Schools page better it gave me a nice convenient list of what are valid JSON types

  • string
  • number
  • object
  • array
  • boolean
  • null

It also gave an example on how to loop through a JSON object. We are definitely going to need this!

//looping through the JSON Object using the object above
//variable is -- demoJsonObj -- just to remind you

for (const item in demoJsonObj) {
  console.log(item);
}

//This is handy, we can loop through the object and output each item. 

//Can you think how else we can use it?

This is excellent at least we have a starting point now, we know a bit about JSON and we definitely know that we need to handle these types. At some point we are going to need to check if the data we are looking at so lets make that code now.

Here your style preference can change how you write this, you could use if statements, switch or functions for each data type and return true/false.

function isStr(val){
    return typeof val === 'string';
}

function isNum(val){
 return typeof val === 'number';
}

// when checking a object we must ensure it is not null and not an array. Both null & Array has typeof object in JS
function isObj(val){
    return typeof val === 'object' && !Array.isArray(val) && val !== null;
};

// We need to check that it is an Array and also of type object

function isArray(val){
    return Array.isArray(val) && typeof val === 'object';
};

function isBool(val){
  return typeof val === 'boolean';
}

function isNull(val){
    return typeof val === 'string';
}

So that handles our Data types listed by W3Schools, there was a bit of knowledge I did have about type of for null and arrays returning as objects. If you didn’t have that you may get some weird results.

So now lets build out some code that will get a JSON Object and then loop through each item and check its type.

function CustomJsonStringify(obj){

 //check if it is string
  if(isStr(obj) ===true){
    return `"${obj}"`
  }
  if( isNum(obj) || isBool(obj)){
    return `${obj}`;
  }

  if(isArray(obj)){
    let arrayString = "";
    obj.forEach((val) => {
      arrayString += CustomJsonStringify;
      arrayString +=','
     });

    return `[${arrayString.replace(/,*$/, '')}]`;
  }




  // loop through each item in the object and handle it
  if(isObj(obj)){

        let objectString = ""; 
        let keys = Object.keys(obj);

    keys.forEach((key) => {
      let val = obj[key];
      objectString += `"${key}":${CustomJsonStringify(val)},`;

     });
     return `{${objectString.replace(/,*$/, '')}}`;

    }
  }


console.log(CustomJsonStringify(demoJsonObj));

//Pass string into JSON.parse() to check it is valid
console.log(JSON.parse(CustomJsonStringify(demoJsonObj)));

Conclusion

Here we have a basic stringify function , there are fringe cases which are not handled. and to make it more robust and a 1:1 equivalent we would need to add handling for

  • functions, undefined and Symbol values
  • Dates
  • NaN, Null and Infinity
  • Undefined

Hope this has been helpful to you, Ill have a youtube video going through this in the near future!

Code on GitHub

1 year ago 0 comment
TwitterLinkedin
BlogProgrammingTutorial

Introduction to JSON with Examples

by Matt Heff 2 years ago
written by Matt Heff

Over the last couple of years I have been marvelling that the pervasiveness and elegance of JSON, if you are working with data, API’s, server requests or database migrations then there is a good chance that you are going to come across a payload that contains this format. If you are lucky it will be this format!

What is JSON?

It stands for JavaScript Object Notation ( JSON ), It was derived from JavaScript (JS) as the name suggests and is a subset of JavaScript, it came about after object literals and array literals were added to the language. One of its great strengths is that it works across all programming languages. Because of this it is arguable the most populate way to store and transfer data across systems, API requests and migrating database data are two really populate uses.

When giving someone JSON data it should be in a FILE_NAME.json format, it generally is not a issue if it is a FILE_NAME.txt or other because it is plain text inside.

Syntax and Data Types

JSON data is stored as key/value pairs which is the same as Javascript Object properties, each item is separated by a comma, the object is sourraounded by {} curly brackets and arrays are sourrounded by [] the square brackets. The data itself has a Key/Name component which is sourrounded by “” double quotes followed by : (colon) and then the value (types are string ,number, null, boolean, array, object )

JSON Strings

Strings in JSON are contained by double quotes

{
    "firstName": "Matt",
    "lastName": "Heff"
}

JSON Null

Null values are empty values

{
    "dob": null
}

JSON Boolean

Boolean values are true or false in JSON

{
    "education" : false
}

JSON Numbers

A number must either be an integer ( eg 10 ) or a floating-point ( eg 10.1 )

{
    "age" : 15
}

JSON Object

JSON Objects elements which are wrapped in curly brackets, inside a object we can have any number of key/value pairs, each is separated by a comma.

{
    "firstName": "Matt",
    "lastName": "Heff",
    "dob": null,
    "education" : false
}

JSON Arrays – Multiple Records

JSON arrays are wrapped with the square brackets. Inside an array we can have as many objects as we like, each needs to be separated by a comma.

[
  {
    "firstName": "Matt",
    "lastName": "Heff",
    "dob": null,
    "education": false,
    "age": 15

  },{
    "firstName": "John",
    "lastName": "Smith",
    "dob": "12/12/2000",
    "education": true,
    "age": 21
  }
]

Multiple Records in an Array with Nested Array

[
  {
    "firstName": "Matt",
    "lastName": "Heff",
    "dob": null,
    "education": false,
    "languages": ["JSON","Solidity","JavaScript","Node.js"],
    "age": 15
  },
  {
    "firstName": "John",
    "lastName": "Smith",
    "dob": "12/12/2000",
    "education": true,
    "languages": null,
    "age": 21,
    "educationItems": 
         [
           {"schoolLevel":"High School","yearGraduated":2020},
           {"schoolLevel":"University","yearGraduated":null},
        ]
  }    
]

Wrangling JSON Data in JavaScript

JSON is based on a subset of the JavaScript language, so it works really nicely with JS. We are able to convert JSON data into JavaScript objects pretty simply and with tools built in.

There is a JSON object in JavaScript that offers us two methods where we can encode/decode JSON data. parse() and stringify()

When we recieve a JSON data payload from a server/api request it is not going to be a Javascript Object by default, it is going to be a string so we will need to convert it into a JavaScript Object like below:

// from our JSON example above we make a sample string
const jsonDataExampleString = `{    "firstName": "Matt",    "lastName": "Heff",    "dob": null,    "education": false,    "age": 15 }`;

// lets convert it into a JavaScript Object!
const record = JSON.parse(jsonDataExampleString);

console.log(record.firstName); Matt
console.log(record.lastName); // Heff
console.log(record.dob); //null
console.log(record.education); //false
console.log(record.age); // 15

When we need to send some JSON over a request or two write it into a file we need to convert it to a string, JSON.stringify() does this for us:

// Make a JavaScript Object that is correct JSON
const record = { 
    "firstName" : "Matt",
    "lastName" : "Heff",
    "dob" : null,
    "education": false,
    "age": 15
}

// convert the object into a string
const jsonDataExampleString  = JSON.stringify(record );


console.log(jsonDataExampleString);

//{    "firstName": "Matt",    "lastName": "Heff",    "dob": null,    "education": false,    "age": 15 }

JSON Resources

  • Introducing JSON — Learn about JSON language supported features.
  • JSONLint — A JSON validator to verify if the JSON string is valid.
  • JSON.dev — A little tool for viewing, parsing, validating, minifying, and formatting JSON.
  • JSON Schema — Annotate and validate JSON documents according to your own specific format.
2 years ago 0 comment
TwitterLinkedin

Recent Posts

  • How to read environment variables with Node.js
  • AI – What is Natural Language Processing (NLP)
  • Web3 RPC Nodes
  • Drupal 9 – Custom module development – Simple Module
  • Create a RESTful API in NodeJS

About

About

GetCoding is a blog and tech educational resource specialized in programming, Web3, blockchain and everything in between. Follow us to help you understand and GetCoding!

Stay Connect

Twitter Linkedin Youtube Email

Popular Posts

  • 1

    Writing your first Ethereum Smart Contract

    1 year ago
  • 2

    Create your own JSON.stringify() function

    1 year ago
  • 3

    Install Metamask and get Testnet Tokens

    1 year ago
  • 4

    Introduction to JSON with Examples

    2 years ago
  • 5

    What is an AMM ( Automated Market Maker)

    1 year ago

Categories

  • Blockchain (4)
  • Blog (7)
  • Featured (3)
  • Learning (1)
  • Programming (5)
    • JavaScript (3)
    • NodeJS (1)
    • PHP (1)
  • Technologies (2)
    • Drupal (1)
  • Thought Provoking (1)
  • Tutorial (6)
  • Uncategorized (3)

Recent Posts

  • How to read environment variables with Node.js

    8 months ago
  • AI – What is Natural Language Processing (NLP)

    12 months ago
  • Web3 RPC Nodes

    1 year ago

Featured Posts

  • How to read environment variables with Node.js

    8 months ago
  • AI – What is Natural Language Processing (NLP)

    12 months ago
  • Web3 RPC Nodes

    1 year ago

Subscribe Newsletter

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

  • Twitter
  • Linkedin
  • Youtube
  • Email
GetCoding
  • Home
  • Courses
  • Contact