Warning message

Newsletter category Drupal Developer newsletter format has not been set to HTML. There will be no statistics recorded for this newsletter.

Drupal7: JSON, hook_form_alter & hook_menu

This CodeLet demonstrates the use of hook_form_alter & hook_menu.
Using hook_form_alter, a text field is added to site information page. Once a API key is saved, the button has value 'Update configuration'
Using JSON menu, one can pull a node of type page, as JSON string.

Module Info

name = Site infomation Tweaks
description = This module tweaks the Site infomration page. Provides a field for API key & make it available using JSON.
core = 7.x

CodeLet: 

<?php

/**
* @file
*
* @author DrupalD
*/

/**
* Implementation of hook_menu
*
* @author DrupalD
*/
function siteinfo_tweaks_menu() {
$item = array();
$item['JSON/%/%node'] = array(
'type' => MENU_CALLBACK,
'page callback' => 'siteinfo_api_data',
'page arguments' => array(1, 2),
'access callback' => TRUE,
);

return $item;
}

/**
* Impementation of hook_form_alter
* @param Array $form
* @param Array $form_state
* @param String $form_id
* @author DrupalD
*/
function siteinfo_tweaks_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'system_site_information_settings':

$siteAPI_key = variable_get('siteapikey', '');
//If site API key is set, change the value of the submit button
if ($siteAPI_key != '' ) {
$form['actions']['submit'][''] = t('Update configuration');
}

//Add site API field
$form['siteinfo_api'] = array(
'' => 'fieldset',
'' => t('API'),
);

$form['siteinfo_api']['siteapikey'] = array(
'' => 'textfield',
'' => t('Site API Key'),
'' => t('Provide the API key'),
'' => array('placeholder' => t('No API Key saved yet')),
'' => variable_get('siteapikey', ''),
);

//Add a submit routine to display custom message
$form[''][1] = 'siteinfo_tweaks_submit';
break;
}
}

/**
* siteinfo_tweaks_submit
*
* Custom submit routine
*
* @param unknown $form
* @param unknown $form_values
* @author DrupalD
*/
function siteinfo_tweaks_submit($form, $form_values) {
$siteAPI_key = $form_values['values'] ['siteapikey'];
drupal_set_message(t('Site API Key has been saved: @api', array('@api' => $siteAPI_key)));
}

/**
* siteinfo_api_data
*
* Return API key in JSON format
*
* @param unknown $siteAPI_key
* @param unknown $nid
* @author DrupalD
*/
function siteinfo_api_data($siteAPI_key, $node) {
//Make sure the API key is present & its the one which has been saved previously
if (variable_get('siteapikey') != '' && variable_get('siteapikey') == $siteAPI_key && $node->type == 'page') {
return drupal_json_output(array('node' => $node));
}
else {
drupal_access_denied();
}
}

Dependency

Hook_form_alter | Drupal Developer

By DrupalD on Wed, 08/06/2016 - 6:24pm

Add comment

Log in or register to post comments
QR code for this page URL This page URL
Feedback