How to call Custom Module in Drupal - php

I am new to Drupal, I have made a custom module using PHP, which shows List of Student's with Information, and want to call it, on click of Submenu item, named, student Info. Please guide me by step wise step procedure.

The starting place to look for generating a "page callback" (essentially making a url active in drupal) would be hook_menu. As suggested take a look at the documentation but a starting point to actually make your callback work would be this in a my_module.module file:
/**
* Implements hook_menu().
*/
function my_module__menu() {
$items = array();
$items['student-info'] = array(
'title' => 'Student Info', // This becomes the page title
'description' => 'Information about students.', // this is the link description
'page callback' => 'function_name_that_outputs_content', // this is the page callback function that will fire
'type' => MENU_CALLBACK, // this is the type of menu callback, there are several that you can use depending on what your needs are.
);
return $items; // make sure you actually return the items.
}
/**
* Output the page contents when someone visits http://example.com/student-info.
*/
function function_name_that_outputs_content() {
$output = 'My page content'
return $output;
}

Related

Drupal 8 - Adding/Creating Menu Item with HTML in it

I'm creating a website using Drupal 8. I want to create a menu item link that I could add HTML/Javascript code in it (I'm trying to display a widget that expands on click in the menu rather than displaying it in its own block next to the menu). The only way I could see to add a menu item is to link to a page.
You could work with a derivative. This lets you customize pretty much everything about it and control what is to be made. An example below:
Note: I am assuming you have a general knowledge of custom modules. If not follow this link
Create the following file in your custom module:
# my_module.links.menu.yml
my_module.custom_links:
deriver: \Drupal\my_module\Plugin\Derivative\CustomLinkDerivative
And now for the derivative class (Located under my_module/src/Plugin/Derivative)
<?php
namespace Drupal\my_module\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CustomLinkDerivative extends DeriverBase implements ContainerDeriverInterface {
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static();
}
/**
* {#inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
$links['custom_menulink'] = [
'title' => t('Custom menulink'),
'menu_name' => 'main',
'route_name' => 'entity.node.canonical',
'parent' => footer,
'route_parameters' => [
'node' => 1,
]
] + $base_plugin_definition;
return $links;
}
}
Note: Derivatives get triggered during rebuild of cache!
This just creates a link in the footer that directs to node 1. You can add all sort of stuff and logic to your liking. Hope this helps you :)

Override callback function in Drupal7

I am using blog module. I can access it using this URL: http://localhost/drupal/blog. I have put some posts.
In the blog content type, I have added a field such as posted date. When I open the same URL http://localhost/drupal/blog, blog posts are coming using ordering on submitted date.
Now I want that posts should be list out using order by newly added field "posted_date". I don't want to change default functionality defined in the blog.pages.inc page.
please suggest!
Create this function in module_name.module file in the custom module.
Ex: sites/all/modules/custom/module_name/moduleName.module
/**
* Implements hook_menu().
*/
function moduleName_menu() {
$items['blog'] = array(
'title' => 'Blogs',
'page callback' => 'blog_list',
'access callback' => TRUE,
'file' => 'page_name.inc',
'type' => MENU_CALLBACK
);
}
Create a file moduleName.pages.inc and define callback function.
Exm: sites/all/modules/custom/moduleName/moduleName.pages.inc
function blog_list() {
return t('welcome blog');
}
I hope it will work for you cheers!

Drupal 6: Make a menu_hook() return a specific view

I created a hook in order to add an item to the administrator's menu. When the user clicks on the item, I want to return the content of a specific view I created. How should I return the view?
My current code looks like:
function my_view_menu(){
$items['view'] = array(
'title' => 'Report',
'page callback' => 'return_my_view',
'access arguments' => array('access content'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function return_my_view(){
return t("Hello!");
}
EDIT:
As suggested by Berdir, this the correct way to call a view:
function return_my_view(){
$viewName = 'my_report'; // use the machine readable name of the view
return views_embed_view($viewName);
}
You could just add a menu item in the view itself...and restrict access (to the view) to the admin role of choice :)
In your view choose "page" and click
on the "Add Display" button (if there isn't already a page display).
Under
"Page Settings" add a Path and a
Normal Menu-Entry in the Navigation
Menu
Next Under Basic Settings
change the access to Role based and
choose the role(s) that should have
access
Finally go to the
navigation menu settings and drag
the new menu item to the desired
place in the Administer menu
You want views_embed_view(), see http://web.archive.org/web/20110213234806/http://thedrupalblog.com/embedding-view-drupal-6-using-views-embed-view
views_embed_view() is the correct call. If you are getting a blank page, try checking your apache error log to see if there are any php errors. I also notice that in your revised example you used $viewName = "my-report", but views_embed_view() expects the machine readable name of the view, which only allows for alphanumeric and underscore characters. Perhaps you are using the incorrect name?
Third technique: Once you have created a Page Display for a View, Views will provision that page with a menu entry. Once that exists, it is possible to duplicate that menu entry for your own purposes.
Create a module with a weight of at least 11 (higher weight than Views)
Implement hook_menu_alter() and duplicate the View entry.
function example_menu_alter(&$items) {
$items['admin/new/path'] = $items['original/view/path'];
}
This approach is somewhat convoluted, but is sometimes a useful alternative for Views or other "page" content you want to clone.
In addition to berdir's comment, you can also skip the intermediate callback function and just call views_embed_view directly from your menu router:
function hook_menu(){
$items['path/to/my/view'] = array(
'title' => 'Report',
'page callback' => 'views_embed_view',
'page arguments' => array('my-view-name'),
'access arguments' => array('access content'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}

How to pass jquery variable to drupal (ajax)

I want to pass
var x = 10; to drupal/php variable $x without page refresh.
Can anyone suggest?
Thank you so much for reply.
Actually I am developing custom module for E commerce site(Drupal 6).
On product page, I have 4 attributes as text field (Width inch, width foot, height inch, height foot) By doing some calculation I got new price for that product. I did that calculation in j query.
Now I alter "uc_add_to_cart_form" and add 1 hidden field and get jquery new price into that hidden field using $_SESSION. Upto this point everything is working fine.
I want to save this new price to product node. I am not able set this new price to $node->price.
I am using uc_ajax_cart for "Add to cart" button.
Can anyone please suggest me how can I proceed?
Passing the variable data from JavaScript to Drupal/PHP is one thing. Passing the information from Drupal/PHP to JavaScript is another separate thing. I think that you meant the first one in your question. So I'll go ahead and answer that.
Passing variables from JavaScript to Drupal/PHP
1) Implement a menu hook. You can do that on an existing contributed or new custom module, it depends what you are doing. It's pretty easy and straight forward, it is also well documented on the Drupal site.
$items = array();
$items['my_custom_callback/%'] = array(
'title' => 'My Custom Callback',
'description' => 'Listing of blogs.',
'page callback' => 'my_custom_php_function',
'page arguments' => array(1),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
Let's break down the example above.
$items['my_custom_callback/%']
$items is just an array, and it can be named anything you like. If the URL of my website is www.alexanderallen.name, then http://www.alexanderallen.name/my_custom_callback would be the resource that I would call from my JavaScript application.
In the array's key, the percentage symbol after the word my_custom_callback is a placeholder. This is where you will pass your data from JS to PHP. So if the value of variable x is 10, the call from your JQuery will look like this:
http://www.alexanderallen.name/my_custom_callback/10
When you load that URL, Drupal will find your menu hook, and it will call the function you defined in the 'page callback' array key. In this case that would be:
<?php
/**
* Function that gets called from JQuery asynchronously.
*/
function my_custom_php_function($argument) {
// Do something with $argument...
echo $argument;
}
?>
There you can do anything you want with the value of variable x, like storing it in the database.
If you were to put the menu hook on a custom module, and the name of your module were example_module, the menu hook and custom PHP callback would look like this:
<?php
/**
* #file example_module.module Handles fancy AJAX functionality.
*
*/
/**
* Implementation of hook_menu
*
* #see http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_menu/6
*/
function example_module_menu() {
$items = array();
$items['my_custom_callback/%'] = array(
'title' => 'My Custom Callback',
'description' => 'Listing of blogs.',
'page callback' => 'my_custom_php_function',
'page arguments' => array(1),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Function that gets called from JQuery asynchronously.
*/
function my_custom_php_function($argument) {
// Do something with $argument...
echo $argument;
}
?>
If you wanted to pass multiple variables from JQuery to Drupal/PHP, you could consider JSONifying them in JavaScript, before passing it to PHP. Remember that if the payload is very large you should consider JQuery .post() instead of .get(). The PHP functions for decoding JSON are here on php.net.
Don't forget to return $items at the end of the example_module_menu() function. If you wanted to pass two or more arguments from JavaScript to PHP then the menu item would look similar to this:
function example_module_menu() {
$items = array();
$items['my_custom_callback/%/%/%'] = array(
'title' => 'My Custom Callback',
'description' => 'Listing of blogs.',
'page callback' => 'my_custom_php_function',
'page arguments' => array(1, 2, 3),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function my_custom_php_function($arg1, $arg2, $arg3) {
// Do something ...
$sum = $arg2 + $arg3;
echo "Hi". $arg1 .", X + Z = ". $sum;
}
?>
In this case I am passing three arguments to PHP. 'page arguments' specifies the part of the URL that you want to pass to PHP. If you were to write 'page arguments' => array(0),, then the argument to your PHP function would be the string my_custom_callback.
2) Call the menu hook from your JS code using JQuery. JQuery provides various AJAX methods. Which one you use will depend on the format of the data your dealing with and it's size, amongst other things.
Most likely you will use one of two JQuery methods. .post() or .get(), bearing in mind that that post requests will allow for a bigger data payload than get requests. So if the size of variable x = 10, you might want to stick with .get(). Both .post() and .get() methods are an extension of, or rely on the .ajax() method. The .ajax() method is more flexible because it provides you with more options, like the ability to specify the format of the data (JSON or plain-text), send a username/password along with your request, choose between synchronous or asynchronous requests, and whether the browser should cache or not the request.
This is the method signature for the JQuery .get() method:
jQuery.get( url, [ data ], [ callback(data, textStatus, XMLHttpRequest) ], [ dataType ] )
If you were going to send your data using GET to Drupal/PHP, using the example above you could do something like this:
<script type='text/javascript'>
var name = 'alexander';
var x = 10;
var z = 20;
$.get(
// Callback URL.
"http://www.alexanderallen.name/my_custom_callback/"+ name +"/"+ x +"/"+ z
);
</script>
Note that the usage of the data argument on the .get() method is optional, and in my example I omitted it, but achieved the same effect by concatenating the data to pass to Drupal/PHP with the rest of the URL.
If I were to run that, the HTTP GET request would look like:
http://www.alexanderallen.name/my_custom_callback/alexander/10/20
and the response would look like:
Hi Alexander, X + Z = 30
Passing data from Drupal to JavaScript
For that then you would use Behaviors, I am not entering into details since I think that wasn't your question, but you can go to the official documentation for Drupal 6 behaviors here.
You need to know:
The menu API:
http://api.drupal.org/api/drupal/includes--menu.inc/group/menu/7
Some Drupal JSON functions (maybe)
http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_json_encode/7
variable_set()
http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/variable_set/7
And jQuery ajax API:
http://api.jquery.com/category/ajax/
Essentially, you need to create a menu item that delegates to a callback (be careful with your permissions) and then call it with $.ajax(). If you need to do something with the response, see the json_encode functionality.
You might want to take a look here for some menu examples:
http://drupal.org/project/examples
I think there is a Drupal interface to the jQuery ajax API. Perhaps someone can comment if they know a better way.

Difference in rendering when visiting node/1 and programmatically loading it

A node loads a profile of a user (external database + views). All of this works when I visit: node/123/profile/id/3. Now I have implemented hook_menu() in order to load any profile page and have nicer URLs.
When I load it myself for some reason $left in page.tpl.php is suddenly empty and many more variables seem not to be loading. I have tried many different functions to render and create the correct $output but realized that node_show() seems to be the function of choice.
Testing has shown now that for some reason hook_nodeapi() calls are ignored.
My code:
/**
* Implementation of hook_menu
*/
function modulename_menu() {
$items = array();
$items['my/nice/url/profile'] = array(
'description' => 'This page holds a view that shows profiles based on the %',
'page callback' => 'website_profile_load',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Menu path wildcard callback
*/
function website_profile_load() {
$output = node_show(node_load(1221), false, true);
return $output;
}
So what is the correct way to do this and get Panels (see comment below) to load correctly?
UPDATE:
I am using table wizard and Views 2 to connect to another database with information about people that aren't users of the system. This is an alumni page, the page is administered externally and showed internally (nothing I can do about, have to make this work :)
Just discovered that Panels aren't loaded at all. So even if the node I am trying to load is uses panels for some reason none of that is loaded.
/**
* Menu path wildcard callback
*/
function website_profile_load($uid = null) {
if (!$uid) {
global $user; // if no user passed in argument, show current user profile
$uid = $user->uid;
}
$output = drupal_render(content_profile_show_profiles($uid));
}
There are many reasons why rendering the result of a node_load is different from going to the stock Drupal path /node. It is way too much to go over here honestly but the short answer is that you have to define a template/theme and blocks etc for each page you create. Just because you make a new path and do a node_load in the callback for that path doesn't mean Drupal can automagically know how you want to display that content. It simply loads data from the node and it is available to do whatever you please with it after that. This is why you get a blankish looking page instead of what you'd expect from going through /node.
However I will offer this simple solution since it sounds like you want the exact same page you'd get when you go to 'node/123/profile/id/3' but accessible through a link you define yourself. You just need to setup a redirect in your hook_menu like so:
$items['my/nice/url/profile'] = array(
'description' => 'This page holds a view that shows profiles based on the %',
'page callback' => 'drupal_goto',
'page arguments' => 'node/123/profile/id/3',
'access callback' => TRUE,
'type' => MENU_CALLBACK);
This is essentially saying that when you navigate to 'my/nicer/url/profile' it runs: drupal_goto('node/123/profile/id/3');
I found the answer to be that apparently somewhere in the pipeline of creating a node Drupal uses $path (that is originally set by $_GET['q']) and sometimes also $_GET['q'] to determine how to render the page. NOTE that I am using Panels and Ctools Page Manager modules in order to get my things working correctly.
It turns out Panels, if you search the code, looks at $_GET['q'] for quite an amount of things.
Here is what I ended up with:
/**
* Implementation of hook_menu
*/
function modulename_menu() {
$items = array();
// For department and having nice URL's for their profile pages.
$items['my/nice/url/profile/%'] = array(
'description' => 'This page holds a view that shows profiles based on the %',
'page callback' => 'website_profile_load',
'page arguments' => arg(4),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Menu path callback
*/
function website_profile_load($id = NULL) {
// Rename the query internally since other functions base the design
// on the way the query is structured and not simply by the node which
// is currently loading.
if(!empty($id)) {
$path = $_GET['q'] = 'node/1221/profile/id/' . $id;
}
// Use ctools function to correctly display node view since
// this site heavily uses ctools rendering for panels and
// web parts / web pages.
drupal_load('module', 'page_manager');
ctools_include('node_view', 'page_manager', 'plugins/tasks');
if(function_exists('page_manager_node_view')) {
$output = page_manager_node_view(node_load(1221));
} else {
// Will display incorrectly but still load the UI
$output = node_page_view(node_load(1221));
}
return $output;
}
And it works :)

Categories