University of Oregon

JS Tweak to the Drupal 7 Contact Form

I tweaked our Drupal 7 Contact form today.
The goal was to allow users to select the reason for contact and potentially the subject via the URL.
We had this in place for our Drupal 6 site and the code ported over nicely.

The process was similar to the last post: JS Tweak to the Drupal 7 Menu Management Screen.

The JS consists of two parts, get the URL Var and value and update the form.
I use a stand alone function (getURLVars) to get the URL Var. Then I drop it like it’s hot (so to speak) using jQuery.

Sample URL: /contact?cid=4&subject=What%20is%20all%20this%20then.

Sample JS to try in your console:

if (typeof getURLVars !== 'function') { 
  function getURLVars(urlVar) {
    if(!urlVar){
       return false;
    }
    if(typeof (document.location.href.split('?')) === 'undefined') {
       return false; 
    }
    if (typeof (document.location.href.split('?')[1]) === 'undefined') {
       return false;
    }
    varArray = document.location.href.split('?')[1].split('&');
  
    for(var x=0; x<varArray.length; x++)
    {
      var tmp = varArray[x].split('=');
      eval(unescape(tmp[0]) + '="' + unescape(tmp[1]) + '"');
      if(urlVar == tmp[0]){
        urlVar = eval(unescape(tmp[0]) + '="' + unescape(tmp[1]) + '"');
        return urlVar;
      }
    }
    return ;
  }
}
//getURLVars('cid')

cidVal = getURLVars('cid')?getURLVars('cid'):'';
if(cidVal !== ''){
  theArray = jQuery('#edit-cid').children().map(function() {return jQuery(this).val();}).get();
  if (jQuery.inArray(cidVal, theArray) !== -1){
    //alert('yup');
    jQuery('#edit-cid').val(cidVal);
  }else{
    //alert('nope');
  }
}

subjectVal = getURLVars('subject')?getURLVars('subject'):'';
if(subjectVal !== ''){
  jQuery('#edit-subject').val(subjectVal.trim());
}

Full JS w/ Drupal.behaviors code wrapper where needed:

/**
 * JS to update the contact id based on a URL var. Ported from D6. 
 */

if (typeof getURLVars !== 'function') { 
  function getURLVars(urlVar) {
    if(!urlVar){
       return false;
    }
    if(typeof (document.location.href.split('?')) === 'undefined') {
       return false; 
    }
    if (typeof (document.location.href.split('?')[1]) === 'undefined') {
       return false;
    }
    varArray = document.location.href.split('?')[1].split('&');
  
    for(var x=0; x<varArray.length; x++)
    {
      var tmp = varArray[x].split('=');
      eval(unescape(tmp[0]) + '="' + unescape(tmp[1]) + '"');
      if(urlVar == tmp[0]){
        urlVar = eval(unescape(tmp[0]) + '="' + unescape(tmp[1]) + '"');
        return urlVar;
      }
    }
    return ;
  }
}

/** Set Defaults
 * Reason for Contact
 * if url var = cid
 * and 
 *   val is in the list of vars then jQuery('#edit-cid').val(2);
 *
 * Subject
 * Set subject
 */
 
(function () {
  Drupal.behaviors.setCid = {
    //for use on Attachment content edit screens
    attach: function(context) {
      if(typeof context !== 'undefined'){ //run only if there is a context var
        /*
          Check the type of the context var and type. Process if context = [object HTMLDocument]
          Note: when context == [object HTMLDocument] then this is page load. You may wont some script to run only on page load. Some not and some all the time.
        */
        if(typeof context == 'object' && context.toString().indexOf('HTMLDocument')!=-1){
          //Page Load
          cidVal = getURLVars('cid')?getURLVars('cid'):'';
          if(cidVal !== ''){
            theArray = jQuery('#edit-cid').children().map(function() {return jQuery(this).val();}).get();
            if (jQuery.inArray(cidVal, theArray) !== -1){
              //alert('yup');
              jQuery('#edit-cid').val(cidVal);
            }else{
              //alert('nope');
            }
          }
          
          subjectVal = getURLVars('subject')?getURLVars('subject'):'';
          if(subjectVal !== ''){
            jQuery('#edit-subject').val(subjectVal.trim());
          }
        }
      }
    }
  }
})();

Again I implemented this in a block w/ the Code Per Node (cpn) CSS and JS additions.
Here are the specifics:

Block title:
None;
Block description:
JS for Contact Page
Block body:
 
Text format:
Code input (custom type allowing html)
Pages – Only the listed pages:
contact;
CSS:
#block-block-55 {
  display: none;
  visibility: hidden;
}

*Note the specific block ID in that id selector

JS:
As pasted above

JS Tweak to the Drupal 7 Menu Management Screen

I tweaked Drupal Menu management screen today.
Previously after editing a menu item the menu page would reload and you’d be at the top of the menu list, essentially losing your place.

This was a problem for one of our admin users when digging through 390 menu items, so I thought I’d give it a quick fix.

Now when you edit a menu item and land back on the menu page, the JS below will scroll you to that last element and highlight the row.

Here’s a screenshot:

Screen Shot of menu management screen after editing a menu item

Sample JS to try in your console:

function scrollToReferrer(){
  //get the referrer URL
  referrerArr = document.referrer.split('/');
  //check if referrer was menu item edit screen
  if(referrerArr[3] == "admin" && referrerArr[5] == "menu" && (referrerArr[8] == "edit")) {
    referrerArr.pop(); //ditch edit
    //capture mlid - alt referrerArr[6]
    referrerMlid = referrerArr.pop();
    //scroll to mlid
    location.hash = "#edit-mlid"+referrerMlid+"-operations-edit";
    //slide up a "pinch" to keep the element visable (in the case of Admin Menu)    
    var x = pageXOffset, y = pageYOffset;
    scrollTo(x,y-60);
    //remove 'drag-previous' class from tr's on the page
    jQuery('tr').removeClass('drag-previous');
    //set waring class on this tr to highlight it
    jQuery("#edit-mlid"+referrerMlid+"-operations-edit").parents('tr').addClass('drag-previous');
    return true;
  }else{
    return false;
  }
}
scrollToReferrer();

And here’s the code in D7 Drupal.behaviours format as I implemented it:

(function ($) {
  Drupal.behaviors.scrollToReferrer = {
    //for use on admin/structure/menu/manage/main-menu
    attach: function(context) {
      if(typeof context !== 'undefined'){ //run only if there is a context var
        if(typeof context == 'object' && context.toString().indexOf('HTMLDocument')!=-1){ //Page Load
          //get the referrer URL
          referrerArr = document.referrer.split('/');
          //check if referrer was menu item edit screen
          if(referrerArr[3] == "admin" && referrerArr[5] == "menu" && (referrerArr[8] == "edit")) {
            referrerArr.pop(); //ditch edit
            //capture mlid - alt referrerArr[6]
            referrerMlid = referrerArr.pop();
            //scroll to mlid
            location.hash = "#edit-mlid"+referrerMlid+"-operations-edit";
            //slide up a "pinch" to keep the element visable (in the case of Admin Menu)    
            var x = pageXOffset, y = pageYOffset;
            scrollTo(x,y-60);
            //remove 'drag-previous' class from tr's on the page
            jQuery('tr').removeClass('drag-previous');
            //set waring class on this tr to highlight it
            jQuery("#edit-mlid"+referrerMlid+"-operations-edit").parents('tr').addClass('drag-previous');
            return true;
          }else{
            return false;
          }
        }//end if(typeof context == 'object' && context.toString().indexOf('HTMLDocument')!=-1){ //Page Load
      }//end typeof context !== und
    }//end function(context)
  }//end Drupal.behaviors
})(jQuery);

Now, the way to implement this correctly would be a custom module or perhaps adding the js to the themes’ .js file.

I added it via Code Per Node (cpn) to a new block that has user and page restrictions in our admin theme.
Here are the specifics:

Block title:
None;
Block description:
JS Seven Menu Page Scripts
Block body:
 
Text format:
Code input (custom type allowing html)
Pages – Only the listed pages:
admin/structure/menu/manage/main-menu;
CSS:
#block-block-53 {
    display: none;
    visibility: hidden;
    }

*Note the specific block ID in that id selector

JS:
As pasted above

A quick fix out and out.

Updating select lists in bulk – w/ jquery, drupal

So I wrote this script 1 year and 1/2 ago about bulk label operations (Drupal 7 CCK – Creating ‘Label Bulk Operations’). Well the updateLabels() function from that code came in handy today.
I needed to update dozens of CCK formats from various defaults to editable. If you’ve used editable fields you know it can come in handy but if you have a lot of fields you’ll be in a carpel tunnel conundrum if you try to change then all.
So I pulled up the updateLabels() function opened the Firebug console and set all the various defaults to editable. And then back again. (more…)

bash function – cddrush

This is a quick function that reduces the keystrokes for using ‘drush dd’ in a cd command like so:

cd `drush dd @my.site.alias:%site`

Which is great but this is simpler

cddrush my.site.alias

Oh, that’s nice!
(more…)

bash function – git-patch()

We’ve been trying to review more Drupal 8 patches on Drupal.org with this workflow:

$ cd #to your local Drupal 8 Dir.
$ curl https://drupal.org/files/patch_url... | git apply --stat
$ curl https://drupal.org/files/patch_url... | git apply --check
$ curl https://drupal.org/files/patch_url... | git apply
# If no errors occur you can use
$git am --signoff &lt; fix_empty_poster.patch

I found that be cumbersome so I created a bash function to simplify this.
Usage example: $ git-patch stat URL.patch
That triggers a

  • wget to retrieve the file,
  • runs $ git apply –stat
  • and prompts you for the next step.

In addition if you call the function with no vars it returns a simple usage message.
It works great, it’s more efficient and I don’t have to refer back to the patching best-practices if I forget*.
(more…)

Added a new admin block: Nodes that link to this page

I created a new admin block: “Nodes that link to this page.”
It checks the LinkChecker table in the database for any links on the site to the current page URL and lists those on the right.
Screen shot
(more…)

Added a new tool for selecting taxonomy terms

I added a new tool to aid in selecting taxonomy terms.
It appears as a link in a block positioned in the right side bar on edit pages.

Screen shot

A new option is available in the right sidebar: "Suggest keywords" containing one link: Highlight Terms.

Upon clicking the Highlight terms link a script searches the body of the node and does two things:

  1. Highlight taxonomy terms found in the body
    (more…)

Record Count for Multiple Displays for Drupal 6 Views 2 – Update

Yesterday I posted about displaying record counts for multiple displays in Drupal6 using Views2. Well I’ve found a side effect of that method that overwrites your node title on any page that this method is used.
I posted an update here: http://drupal.org/node/131031#comment-3667720.
All’s well that ends well!
Here’s screen cap. of that block:
Screen shot
(more…)

Record Count for Multiple Displays for Drupal 6 Views 2

*Note: Posted Update Here.

I was trying to summarize the status a site migration and found (once again) that I couldn’t display the record count of a view result.
A number of other folks have been looking to solve that issue too so I found a number of resources and after synthesizing the data I found that you need to use a separate ‘views_get_view()’ call for each display and then use

$view->execute_display('display_name');

I posted examples on the drupal.org forum: Count view query results with footer PHP snippet here: http://drupal.org/node/131031#comment-3658090

Turns out execute_display() is the key to getting multiple display results. Thanks to the view2 docs for that!

(more…)

Drupal module in progress: Book Child Links

Hey all,
I just finished a simple book override module that I wanted to share: Book Child Links

It overrides the ‘Add child page’ link to include all the allowed book types for the individual user.
________________________________________
General overview:
When to act:
* Check if the current node type is a book
Permissions:
* Check if user has access to add content to books.

if(user_access('add content to books'))

* if so build the link list based on whether the user has access to create each content type’s content.

if(user_access('create '.$type.' content') || ($type==="webform" &amp;&amp; user_access('create webforms')))

* ?Consider adding roles too

Action options:
* Build the link list and append it the bottom of the body content
* Append the link array (http://api.drupal.org/api/function/book_link/6) (more…)