Tasks Completed
Create a site localhost site with Drupal 8 with given tasks
http://localhost/drupal8/
userid/password : admin/admin@123
Task 1
created a custom module called custom.
* Implemented hook_form_FORM-ID_alter, This function will Add a New field in Site information page
* Site Api key value stores in /custom/custom/config/install/custom.settings.yml file
for demo, check below URL
http://localhost/drupal8/admin/config/system/site-information
Task 2
created a new menu as /nodecheck/{key}/{nid} to return json object
* created a controller to match siteapikey and nodeid ,
* if Key doesn't match it will respond access denaid
* if key matches but node id is wrong, it will respond as 'not a node'
* if key and node both matches, it will respond json object
for url demo, check below URL
http://localhost/drupal8/nodecheck/testkey/1
Conclusion
- Refered drupal.org and stackoverflow.com
- Spended 3.5 hours to complete these tasks
Background Information
When logged in as the administrator, the "Site Information" form can be found at the path /admin/config/system/site-information.
Requirements
This module needs to alter the existing Drupal "Site Information" form. Specifics:
- A new form text field named "Site API Key" needs to be added to the
"Site Information" form with the default value of “No API Key yet”.
- When this form is submitted, the value that the user entered for
this field should be saved as the system variable named "siteapikey".
- A Drupal message should inform the user that the Site API Key has been saved with that value.
- When this form is visited after the "Site API Key" is saved, the field should be populated with the correct value.
- The text of the "Save configuration" button should change to "Update Configuration".
- This module also provides a URL that responds with a JSON
representation of a given node with the content type "page" only if the
previously submitted API Key and a node id (nid) of an appropriate node
are present, otherwise it will respond with "access denied".
So let's get started create a custom drupal 8 module for extend functionality and/or modify Drupal 8 core configuration section:
Under the folder modules, I have created a custom folder
First I have created under custom/config/install folder
siteapikey:
description: custom module for Drupal 8 |
-
serialization
path: '/nodecheck/{key}/{nid}' |
_controller: '\Drupal\custom\Controller\CustomNodeCheck::nodecheck' |
_permission: 'access content'
<?php
/**
* @file
* Contains \Drupal\custom\Controller\CustomNodeCheck
* custom menu to check siteapikey and node id (/nodecheck/{key}/{nid})
*/
namespace Drupal\custom\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\HeaderBag;
/**
* Provides route responses for the Example module.
*/
class CustomNodeCheck extends ControllerBase {
public function nodecheck($key,$nid) {
$output = array(
'status' => false,
'data' => '',
);
$path = \Drupal::request()->getpathInfo();
$arg = explode('/',$path);
$key = '';
if( false == empty( $arg[2] ) ) {
$key = $arg[2];
$siteapikey = \Drupal::config('custom.settings')->get('siteapikey');
if ( $key != $siteapikey ) {
//access denied
$output['data'] = 'Access Denied';
return new JsonResponse($output);
}
}
$nid = $arg[3];
$node = \Drupal\node\Entity\Node::load($nid);
if( true == empty( $node ) ) {
//not a node
$output['data'] = 'not a node';
$output['status'] = false;
} else {
$serializer = \Drupal::service('serializer');
//$node = Node::load(2);
$data = $serializer->serialize($node, 'json', ['plugin_id' => 'entity']);
$output['data'] = $data;
$output['status'] = true;
}
return new JsonResponse($output);
}
}
<!-- you can add custom twig html here -->
<?php
/**
* @file
* Contains custom.module.
*/
/**
* HB.
*/
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_help().
*/
function custom_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
// Main module help for the custom module.
case 'help.page.custom':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('custom module for axelerant tasks') . '</p>';
return $output;
default:
}
}
/**
* Implements hook_theme().
*/
function custom_theme() {
return [
'custom' => [
'render element' => 'children',
],
];
}
/*
*
* Implements hook_form_FORM-ID_alter
* This is to Add New field in Site information page
* By default, custom.settings siteapikey will be empty.
*/
function custom_form_system_site_information_settings_alter(&$form, FormStateInterface $form_state) {
$siteapikey = '';
$siteapikey = \Drupal::config('custom.settings')->get('siteapikey');
$form['site_information']['siteapikey'] = array(
'#type' => 'textfield',
'#title' => t('Site API Key'),
'#default_value' => $siteapikey,
'#placeholder' => t('No API Key yet'),
);
$form['actions']['submit']['#value'] = t('Update Configuration');
//Submit handler to store siteapikey value into custom.setting
$form['#submit'][] = 'custom_siteinformation_submit_handler';
}
//Submit handler to store siteapikey value into custom.setting
function custom_siteinformation_submit_handler(&$form, FormStateInterface $formState) {
if( false == empty( $form['site_information']['siteapikey']['#value'] ) && $form['site_information']['siteapikey']['#value'] != \Drupal::config('custom.settings')->get('siteapikey') ) {
\Drupal::configFactory()->getEditable('custom.settings')
->set('siteapikey', $form['site_information']['siteapikey']['#value'])
->save();
drupal_set_message($form['site_information']['siteapikey']['#value'].' - Site API Key updated.');
}
}
<?php
namespace Drupal\Tests\custom\Functional;
use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
/**
* Simple test to ensure that main page loads with module enabled.
*
* @group custom
*/
class LoadTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['custom'];
/**
* A user with permission to administer site configuration.
*
* @var \Drupal\user\UserInterface
*/
protected $user;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->user = $this->drupalCreateUser(['administer site configuration']);
$this->drupalLogin($this->user);
}
Below is the screen shots of Task 1 and task for of Drupal 8 Custom module
Comments
Post a Comment