• Awning Works 1
  • Socaz 2
  • Socaz 1
  • Randy Montana 3
  • Randy Montana 2
  • Randy Montana 1
  • Rodgers & Hammerstein 3
  • Rodgers & Hammerstein 2
  • Rodgers and Hammerstein 1
  • Love Fine Art
  • Feb
  • 16
  • 2012

Drupal 7: How To Create a Views View from Within a Module (default view)

The whole idea in making a module is to make it, well ‘modular’, right? The person who is going to install the module should not have to create and configure a view. Chances are they would not get it just right anyway (you know, with all the exact settings the module depends upon). This is because the Views UI is so versatile that no two people are likely to set it up the exact same way. In many cases, if a module depends on data from a view, all the Views setting need to be just so in order for the module to work its magic.

Although this is very doable, I found it very difficult to locate documentation spelling out just how to do it. I’m not sure if it was not documented in a way that was easy to find or if it was the fact that I had a 3-day headache pounding away. Either way, I did finally come across a few links.

techcommons.stanford.edu

Drupal API

To give myself and others one more place to stumble upon what to do I have documented how to create a Views default view from within a module below. A default Views view is a view that weather enabled or not shows up on the /admin/structure/views page once a module is installed and enabled.

For the purpose of these notes we will call our module, ‘mymodule’. Everywhere you see ‘mymodule’ you need to replace with the name of your actual module name. This article assumes that you are familiar with module development basics and that you have already created your basic module files ( mymodule/mymodule.module, mymodule/mymodule.install & mymodule/mymodule.info ).

OK, let’s create a default view in a module!

Create a new file named mymodule.views_default.inc and save it into a directory named mymodule/includes/.

Inside the file you just created, paste the following function…

23
24
25
26
27
28
29
30
31
32
/**
 * Implementation of hook_views_default_views().
 */
function mymodule_views_default_views() {
 
  //PASTE EXPORTED VIEW CODE HERE
 
  $views[$view->name] = $view;
  return $views;
}

You can now create a View in the Views UI as you normally would.
Then export the view. Select the entire export text as presented in the textarea of the export result and past it in place of where you see “PASTE EXPORTED VIEW CODE HERE” inside the function you just made and save the file.

OK, next, inside the file your mymodule.module file, paste the following function (remember that everywhere you see ‘mymodule’ you need to replace with the name of your actual module name.).

47
48
49
50
51
52
53
54
55
/**
* Implementation of hook_views_api().
*/
function mymodule_views_api() {
  return array(
    'api' => 3.0,
    'path' => drupal_get_path('module', 'mymodule') .'/includes'
  );
}

Now you can clear your cache and see the default View you just created in the list of default views at ‘admin/structure/views’

Please feel free to register and comment.

  • Feb
  • 15
  • 2012

Drupal 7: How to Make a Drupal Theme Function in a Module

This is intended as a simple reminder for all of those out there who find making a drupal theme a bit confusing at times.
There are three main steps that all work together.

1) hook_theme which adds an array of callbacks and their arguments to the theme registry. You need to put this in your sites/all/modules/mymodule/mymodule.module file to rebuild the theme registry before it would be added.

23
24
25
26
27
28
29
30
31
32
33
function mymodule_theme($existing, $type, $theme, $path) {
  $theme = array(
    // This is in the mymodule.module file.
    // example theme template register
    // for sites/all/modules/mymodule/templates/mymodule_theme_name.tpl.php
    'mymodule_theme_function_name' => array(
        'variables' => array('node' => NULL, $param2 =>NULL),
        'type' => 'module',
       ),  
  return $theme;
}// function

2) The themable function itself which starts with theme_ followed by the function name that was added to the registry with hook_theme

45
46
47
48
49
50
51
52
// The $vars paramiter is an array of passed 
// variables corresponding to the 'variables' 
// key in the the above hook_theme() function.
function theme_mymodule_theme_function_name( $vars ){
... code here ...
// Return a string that contains the rendered representation of the data.
 return $output; 
}//function

3) Then call the function,

52
 theme('mymodule_theme_function_name', $whatever_argument );

which actually calls the function.

It is important to remember all three of these or the theme will not work.

  • Jan
  • 30
  • 2012

DRUPAL 7: How to Expose a Field in Views

DRUPAL 7: How to Expose a Field in Views

The other day when trying to expose a Filter criteria in a view of the Views module 7.x-3.1, I was frustrated by the fact that it would not function despite my best efforts. After triple checking my set up and reading a lot of documentation, there was no fix. Finally, after digging deep into some threads by a person having the same frustration with Views in Drupal 7 and exposed filters, I found the simple, although illusive, solution.

In the VIEWS UI, open the “ADVANCED” section and look under the “OTHER” subsection. Find the item “Use AJAX” and set the value to yes. I know, I know, (pause, make face) – right? Well, the guy on the thread that helped me complained enough about it so I’ll just keep my mouth shut.

I hope that if you were having this problem you found my post faster than I found that thread. : )

As, always, feel free to comment and make suggestions.

select yes for use ajax

  • Jan
  • 24
  • 2012

Drupal 7 Calendar New Interface Set Up (in Views)

I found this very helpful video by Arlin Sandbulte on the
Drupal Calendar version 7.3 configuration (Calendar 7.x-3.x-dev).

The interface on this Calendar is quite different than what is shown in other slightly older videos.

The new video for Drupal 7 Calendar New Interface Set Up.

  • Jan
  • 03
  • 2012

Secure URL Handling with Drupal

In most cases dynamic data in forms is handled by the forms API which does a pretty good job of keeping it clean. Since the variables in hook_menu() for example are picked up as a % sign and then translated into a callback array, they are “cleansed” as they are passed through the Drupal Core code.

345
346
347
348
349
350
351
352
353
354
355
356
357
358
<?php
function hook_menu(){
... some code
 
  $items['my-module/%/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );
 
more code ...
 
return $items;
}
?>

On the other hand, there may be times when you you really need to pass dynamic data as a $_GET variable that is tacked onto an URL. In this case you need to pass the code through the urlencode() function.

When you are passing a user submitted URL in a hyperlink, rather than using check_plain(), the Drupal documentation says to use urlencode() instead.

  • Jan
  • 03
  • 2012

How to Access the Database from hook_form_submit() Function

  • Jan
  • 03
  • 2012

Get The Calling Function

Knowing which PHP function call the code we are working on can give us the clues we need for de-bugging a script.
Getting the calling function is easy in PHP, thanks to the debug_backtrace() function.

Just put the following code wherever in your script you need to know what function is calling the part you are working on.

45
46
47
48
49
50
<?php>
 
$backtrace = debug_backtrace();
print "The function that just called this code is <strong>" .$backtrace[1]['function'] . "<strong>.";
 
</php>

This will output something like this:

The function that just called this code is DrawWidget.

Where DrawWidget is the name of the function.

I hope this comes in handy for someone. Thanks for visiting!

  • Jan
  • 02
  • 2012

Drupal Security Best Practices When Outputting Text Into HTML

When creating a module in Drupal it is very important to be aware of some security best practices when outputting text into HTML. This helps prevent XSS (Cross Site Scripting) exploits and keeps your code in general good health as it prevents problems with user input like angle brackets or ampersands.

Be sure to read the documentation for db_query() on how to use the database API securely.

When passing plain-text from the user to HTML markup, you need to pass it through the check_plain() function first. Drupal’s check_plain() converts quotes, ampersands and angle brackets into entities. This causes the string to be shown in a literal way on the browser screen.

There are a few themeable functions that automatically sanitize text by first passing it through check_plain(). They are: t() , menu items and breadcrumbs, Block descriptions (‘but not titles’), theme(‘ plain-text placeholder’), theme_username() and Drupal Form API #default_value element and #options element when the type is a select box.

Examples:

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php>
        $form['safe_way'] = array(
          '#type' => 'textfield',
          '#default_value' => $user_supplied,
        );
 
        $form['not_safe_way'] = array(
          '#type' => 'select',
          '#default_value' => 0, //FORM API will pass this through 
                                 //check_plain(),
          '#options' => node_get_types('names'),  // DANGER: FORM 
                                 // API will NOT sanitize the  
                                 // '#options' attribute with 
                                 // check_plain().
        );
?>

As a Drupal module developer, it is important to commit to memory some common places where sanitizing plain text is important.

Setting the page title:
Examples:

23
24
25
26
27
28
29
30
<?php>
 
        drupal_set_title($node->title);//BAD, XSS vulnerability
        drupal_set_title(check_plain($node->title));// Correct way
        //NOTE: The same applies to block titles that are 
        //      passed through hook_block().
 
?>

Form elements #description and #title
Examples:

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php>
 
        $form['wrong_way'] = array(
        '#type' => 'textfield',
        '#default_value' => check_plain($user_supplied),  //←-escaped twice
        '#description' => t("Old data: !data", array('!data' => $user_supplied)), // XSS
        );
 
        $form['right_way'] = array(
        '#type' => 'textfield',
        '#default_value' => $user_supplied,
        '#description' => t("Old data: @data", array('@data' => $user_supplied)),
        );
 
?>

Form elements – #options when #type = checkboxes or #type = radios
Examples:

23
24
25
26
27
28
29
30
31
32
33
34
35
<?php>
 
        $form['wrong_way'] = array(
          '#type' => 'checkboxes',
          '#options' => array($user_supplied0, $u_supplied1),
        );
 
        $form['right_way'] = array(
          '#type' => 'checkboxes',
          '#options' => array(check_plain($user_supplied0), check_plain($user_supplied1)),
        );
 
?>

Form elements – #value of #type markup and item need to be safe.
Note that the default form element #type is markup!
Examples:

23
24
25
26
27
28
29
30
<?php>
 
        $form['wrong_way'] = array('#value' => $user->name); //XSS
        $form['right_way'] = array('#value' => check_plain($user->name));
         //       - or -
        $form['right_way'] = array('#value' => theme('username', $user));
 
?>

This information was gleaned from the Drupal documentation at “Handle text in a secure fashion”, which covers this topic more extensively than this post.

  • Sep
  • 21
  • 2011

Build Drupal Form Elements BEFOR the AJAX Callback is Called

I just lost two days of productive development time trying to figure out why AJAX was breaking in one of the steps of a form I am building in Drupal. As it turns out, a very important, and not at all obvious, thing to remember when developing a Drupal form is that the Drupal Forms API needs to define the form fields BEFORE the AJAX callback is fired.

The form I was working on was up until now, being built in such a way that this was not a problem. However, when I started working on a select element that uses AJAX to call an undetermined number of subsequent select elements, I decided to put that logic inside of the callback function. That was a “bad move”. The callback function needs to call upon a $form array that has already been built. Logically, I figured that I could just add to the existing $form array before returning it via the AJAX callback function. After all since I ad not yet returned it, why not? Well the reason why not is buried somewhere in the Drupal Forms API I suppose.

So, be sure to build the form elements into the $forms array prior to the AJAX callback function getting called.

  • Sep
  • 16
  • 2011

How to Get the Path ID (pid) for a Node’s Path Alias in Drupal 7

Posted by admin In Drupal 6 & Drupal 7, How To, PHP | No Comments »

After searching the internet I found nothing satisfactory for simply finding the Path ID for a node’s alias.

I need this this so that I could programmatic update a node alias in a way that keeps the Drupal site installation updated system wide without conflicts. So, anyway here is a simple function to find the alias path id for a given node.

By the way, if you got to   Home » Administration » Configuration » Search and metadata  and then hover over the edit link on the row of the alias in question, you will see the path is in the url.

<?php

/**
*
* Returns the path alias id for a given alias.
*
* $nid
* int    The node id
*
*/
function pathdata_get_pid( $nid ) {
if ( isset($nid)  && is_numeric($nid) ) {

    $source  = ‘node/’. $nid ;
$query = db_select(‘url_alias’, ‘ua’);
$result = $query->fields(‘ua’ )
->condition( ‘source’, $source , ‘=’)
->execute();
$data = $result->fetchAssoc();
return $data['pid'];
}
else {
return 0;
}
}

?>

 

 

Flickr Stream