Skip to main content

The Cheeky Monkey Media Blog

A few words from the apes, monkeys, and various primates that make up the Cheeky Monkey Super Squad.

"Building a Custom Module - Part 3 by Yan Yong, Monkey Wrencher at Cheeky Monkey Media

Building a Custom Module - Part 3

This is part 3, of a 3 part tutorial for creating a custom module for drupal 7. If you haven't already done so, you may wish to look at part 1 and part 2 first. Anyway, here is the source code of this tutorial.

First of all, though, I have to apologize that I did not do a good job of keeping track of all of the changes made so far. I code everything before I start writing, so hopefully it is not too confusing.

There are few things I would like update this time so here is a list of the things that I want to cover in this tutorial:

  • Update the module menu, so each recipe operation has their unique path.
  • Implement helper functions to handle add/edit/update operations
  • Implement functions to handle recipe status changes via ajax call.
  • Implement functions to handle delete recipes.

 

Update the module menu, so each recipe operation has their unique path.

Time to update the hook_menu to clear up the mess that I left from my last tutorial. Let's use a constant for the recipe path, so it’s easier to update it. Add the following line to the top of the simple_recipe.module

  1. define ('SIMPLE_RECIPE_BASE_PATH', ‘simple_recipe');

Then let's make a menu item to list all recipes, so the end user could actually use this thing. Let’s add the following menu items to the hook_menu array.

  1. $items['user/%user/' . SIMPLE_RECIPE_BASE_PATH . '/list'] = array(
  2. 'title' => 'Listing all Recipes',
  3. 'type' => MENU_DEFAULT_LOCAL_TASK,
  4. 'weight' => 0,
  5. );

You might wonder why there is no callback for this path. If we declare menu item type to be MENU_DEFAULT_LOCAL_TASK we have to put the actual callback in other items, strange isn’t it? Anyways, let’s declare another menu item. Please add the following code to your hook_menu:

  1. $items['user/%user/' . SIMPLE_RECIPE_BASE_PATH] = array(
  2. 'title' => 'Simple Recipe',
  3. 'description' => 'List recipes',
  4. 'page callback' => '_simple_recipe_list_recipes',
  5. 'page arguments' => array(1),
  6. 'access callback' => '_simple_recipe_access_check',
  7. 'access arguments' => array(1),
  8. 'type' => MENU_LOCAL_TASK,
  9. );

This MENU_LOCAL_TASK has to do all the hard work.

Then, we need to update the path for add and edit operation.

  1. $items['user/%user/' . SIMPLE_RECIPE_BASE_PATH . '/add'] = array(
  2. 'title' => 'Add a Simple Recipe',
  3. 'description' => 'Add recipe',
  4. 'page callback' => 'drupal_get_form',
  5. 'page arguments' => array('simple_recipe_form'),
  6. 'access callback' => '_simple_recipe_access_check',
  7. 'access arguments' => array(1),
  8. 'type' => MENU_CALLBACK,
  9. );
  10. $items['user/%user/' . SIMPLE_RECIPE_BASE_PATH . '/edit/%'] = array(
  11. 'title' => 'Edit Simple Recipe',
  12. 'description' => 'Edit recipe',
  13. 'page callback' => 'drupal_get_form',
  14. 'page arguments' => array('simple_recipe_form'),
  15. 'access callback' => '_simple_recipe_access_check',
  16. 'access arguments' => array(1),
  17. 'type' => MENU_CALLBACK,
  18. );

As you can see, both operations use the same simple_recipe_form form. I need to make some changes to make it work. Basically add a hidden field to store recipe id to distinguish the insert and update operation. Let’s focus on updating this hook_menu for now. Register the last two operations, delete and status changes.

  1. $items['user/%user/' . SIMPLE_RECIPE_BASE_PATH . '/delete'] = array(
  2. 'title' => 'Delete Recipe',
  3. 'description' => 'Delete recipe',
  4. 'page callback' => 'drupal_get_form',
  5. 'page arguments' => array('simple_recipe_delete_form'),
  6. 'access callback' => '_simple_recipe_access_check',
  7. 'access arguments' => array(1),
  8. 'type' => MENU_CALLBACK,
  9. );

Since delete operation is quite destructive, we want to make confirmation form for this operation. The status change operation will be done via ajax, so we don’t need to create a form for that. The placeholder %user tells drupal to load a user object as a first argument, and the last % is a placeholder for recipe id.

  1. $items['user/%user/' . SIMPLE_RECIPE_BASE_PATH . '/status/%'] = array(
  2. 'title' => 'Update a Simple Recipe status',
  3. 'description' => 'Update recipe status',
  4. 'page callback' => 'simple_recipe_update_status',
  5. 'page arguments' => array(4),
  6. 'access callback' => '_simple_recipe_access_check',
  7. 'access arguments' => array(1),
  8. 'type' => MENU_CALLBACK,
  9. );

Implement helper functions to handle add/edit/update operations

Now we have all the menu item path re-arranged, we are going to need few functions to help us create, load and update recipes. The old simple recipe save function is not very flexible. It only allows us to save a new recipe and use a hardcoded value for status. Let's change that. Basically, I want to insert and update to be one function, that's why I am using db_merge function here. This function can be view as a combination of db_insert and db_update, so when rid (recipe id) present in the key() function, it will do an update. Otherwise, it will do an insert operation

  1. /**
  2. * Update simple recipe db, insert or update.
  3. * @param array $values
  4. */
  5. function simple_recipe_save_recipe($values = null) {
  6. global $user;
  7. $query = db_merge('simple_recipe')
  8. // Check if rid exist or not, if found do update otherwise do insert.
  9. ->key(array('rid' => isset($values['rid']) ? $values['rid'] : 0))
  10. ->fields(array(
  11. 'uid' => isset($values['uid']) ? $values['uid'] : $user->uid,
  12. // Make sure serialize form_value before passing to this function.
  13. 'form_values' => isset($values['form_values']) ? $values['form_values'] : '',
  14. 'status' => (int) $values['status'],
  15. 'timestamp' => REQUEST_TIME,
  16. ));
  17. $query->execute();
  18. }

Next, we are going to add delete function. This is really straight forward.

  1. /**
  2. * Delete a database record from db.
  3. * @param int $rid
  4. */
  5. function simple_recipe_delete($rid) {
  6. if (is_numeric($rid)) {
  7. $num_deleted = db_delete('simple_recipe')
  8. ->condition('rid', $rid)
  9. ->execute();
  10. }
  11. }

There are two functions to get recipes, one load a recipe for a given the recipe id. The other loads recipes for a given user and recipe status.

  1. /**
  2. * load a recipe from db.
  3. * @param int $noid
  4. * @return db record.
  5. */
  6. function simple_recipe_get_recipe($rid) {
  7. return db_select('simple_recipe', 'sr')
  8. ->fields('sr')
  9. ->where('rid = :rid', array(
  10. ':rid' => (int)$rid,
  11. ))
  12. ->execute()
  13. ->fetchAssoc();
  14. }
  15. /**
  16. * Load recipes from a given user.
  17. *
  18. * @param int $uid
  19. * User id.
  20. * @param int $status
  21. * recipe status, 0 disabled, 1 enabled, other load everything.
  22. * @return array of recipes objects
  23. */
  24. function simple_recipe_get_recipes($uid, $status = 2) {
  25. $query = db_select('simple_recipe', 'sr')
  26. ->fields('sr')
  27. ->condition('sr.uid', $uid);
  28. // Decide the what to load.
  29. switch($status) {
  30. case 0:
  31. // Disabled recipts.
  32. $query->condition('sr.status', 0);
  33. break;
  34. case 1:
  35. // Enabled recipts.
  36. $query->condition('sr.status', 1);
  37. break;
  38. default:
  39. // Load every recipts.
  40. break;
  41. }
  42. $result = $query->execute()
  43. ->fetchAll();
  44. return $result;
  45. }

Now, we are ready to update operations related to recipes.

Implement functions to handle recipe status changes via ajax call.

Here is the todo list:

  1. register a path for recipe status callback.
  2. create a callback function to change recipe’s status
  3. use drupal default ajax library to ajaxify the status update link
  4. update the recipe status operation label by using javascript

Step 1: register a path for recipe status callback.

We have registered the path user/%user/simple_recipe/status/% in the hook_menu already.

Step 2: create a callback function to change recipe’s status.

Let's implement the simple_recipe_update_status callback function. We load a existing recipe from database and flip the status value then save it.

  1. /**
  2. * Flip status flag for the given simple recipe id.
  3. * @param int $rid
  4. */
  5. function simple_recipe_update_status($rid) {
  6. $recipe = simple_recipe_get_recipe($rid);
  7. $recipe['status'] = (int) !$recipe['status'];
  8. simple_recipe_save_recipe($recipe);
  9. }

Step 3: use drupal default ajax library to ajaxify the status update link. 

Let’s create the link in the recipe listing page. Since the listing page is not a form. We can’t piggy-back on the form api to perform a ajax call. Therefore, we are going to use the core ajax library to ajaxify this link. Its very simple, we need to do two things. load the library and then update the link class. Modify _simple_recipe_list_recipes function, let's add the following line to the top of the function.

  1. drupal_add_library('system', 'drupal.ajax');

Then we need to add use-ajax class to the $operation variable which holds text either Enable or Disable.

  1. l(t($operation), "user/$account->uid/simple_recipe/status/$recipe->rid", array(
  2. 'attributes' => array(
  3. 'title' => 'Title here.',
  4. 'id' => $status_id,
  5. 'class' => array('use-ajax'), // Ajaxify this link.
  6. ),
  7. )),

Now, it's time to update the link text after each successful ajax call. We want to display label Enable when the recipe with status is 0 and Disable for status 1. We are going to do this using javascript. Add this line right after the for each loop.

  1. drupal_add_js(drupal_get_path('module', 'simple_recipe') . '/js/simple_recipe.js');

Step 4: update the recipe status operation label by using javascript.

Make sure you create a new directory call js inside our simple_recipe directory, then create a new file call simple_recipe.js. In order to update each recipe’s status, we need to be able to detect which recipe’s status link were clicked. In the Jquery ajaxSuccess function, we have a setting.url property, which stores the request url. We know the last segment of the path user/%user/simple_recipe/status/% holds the recipe id, so by extracting the id from the request URI we will be able to target the right element. add the following code to simple_recipe.js file.

  1. (function ($) {
  2. Drupal.behaviors.simple_recipe = {
  3. attach: function (context, settings) {
  4. // listen to ajax success event.
  5. // Then we are going to use url to determine which
  6. // recipe has been fired via ajax.
  7. // Once we get the id, then we can alter the recipe state text.
  8. $(document).ajaxSuccess(function(event, xhr, settings) {
  9. // Recipe id is after the string status/
  10. var pattern = /status\/(\d+)/;
  11. var str = settings.url;
  12. var result = str.match(pattern);
  13. // Only update recipe status if we have a valid id.
  14. if (result[1].length > 0) {
  15. var id = result[1];
  16. var id_selector = '#status-' + id;
  17. // Update text.
  18. if ($(id_selector).text() == 'Disable') {
  19. $(id_selector).text('Enable');
  20. }
  21. else {
  22. $(id_selector).text('Disable');
  23. }
  24. }
  25. });
  26. }
  27. }
  28. })(jQuery);

Implement functions to handle delete recipes.

Let's create a new form to display in the formation page. This form will have a hidden field that stores the recipe id.

  1. function simple_recipe_delete_form($rid) {
  2. $rid = arg(4);
  3. $recipe = simple_recipe_get_recipe($rid);
  4. $recipe = unserialize($recipe['form_values']);
  5. $form['warning'] = array(
  6. '#markup' => '

' . t('Are you sure you want to delete @name?', array([email protected]' => $recipe['name'])) . '

', ); $form['rid'] = array( '#type' => 'hidden', '#value' => $rid, ); $form['delte'] = array( '#type' => 'submit', '#name' => 'delete_btn', '#value' => 'Delete', ); return $form; }

Once the form is submitted, we will check for the hidden recipe id and delete it from the database. I am using very similar approach to distinguish the insert and update operation on the simple_recipe_form form. Note that instead of using drupal_goto we are using form_state to do the redirect, that's because we want to give the; other module a chance to process form as well.

  1. function simple_recipe_delete_form_submit($form, &$form_state) {
  2. if (!empty($form_state['values']['rid']) && !empty($form_state['triggering_element']['#name']) && $form_state['triggering_element']['#name'] == 'delete_btn') {
  3. $rid = $form_state['values']['rid'];
  4. simple_recipe_delete($rid);
  5. global $user;
  6. $form_state['redirect'] = 'user/' . $user->uid . '/' . SIMPLE_RECIPE_BASE_PATH;
  7. drupal_set_message(t('Delete successful.'));
  8. }
  9. }

Find the source code here:

Download Source Code

Need help with a Drupal project? Did you know that Cheeky Monkey Media works with other agencies that need extra hands on projects? Our Drupal Web Developers are ready to help. Call us!

Web Development

Would you like to know more about what we do?

View Our Services

Graphic Design Cheeky Monkey

Have a look at some our client work

View Our Work

Cheeky Monkey Discovery

Learn more about Cheeky Monkey Media

About Us

Comments