Monday 16 November 2015

Using NPM as a Task Runner.

In our website we may have some commands that we need to use over and over again.  Let’s say for example that we want to uglify a JS file .  We can write a command for that like . 

‘node_modules/.bin/uglifyjs src/models/* src/frontend.js -m -c -o build/app.js’  

I can then add this to the scripts object in the package.json  

“scripts”: {
“uglify”: “uglifyjs src/models/* src/front.js -m -c -o build/app.js"
”,

Tip: you can run files sequentially with ‘&&’ or the same time with ‘&’

For 

“build”: “npm run copy-files && npm run uglify"



Thursday 12 November 2015

Using Javascript to create dynamic styling choices

Here's a little bit of code but the use of this goes well beyond just matching up a couple of heights like I have here .

I'll be using posting up some more examples of how to use it for other calculations soon.


 
var rowHeight = $(".views-row-first").height();
            // now to write that value into the css
            $(".offer-cards .match-heights").css("height", rowHeight);
        } 

Monday 9 November 2015

Drupal 7 Changing the tag attributes in an image .

Here I needed to change a tag inside an image. the 'foaf:Image' and replace it with a default tag instead. Here's my code.


function MYTHEME_preprocess_image(&$variables) {

  $image_attributes_array = $variables['attributes']['typeof'];

  if ( in_array('foaf:Image', $image_attributes_array )) {

    foreach ($image_attributes_array as $key => $image_attribute) {

      if ( $image_attribute == 'foaf:Image') {
        // start: find out what filetype the image is and make a tag accordingly
        $image_file_type_array = explode('.', $variables['path']);
        $image_file_type = end($image_file_type_array);
        $tag = 'image/' . $image_file_type;
        // end:
        $variables['attributes']['typeof'][$key] = $tag;
      }
    }
  }
}



If you're interested in the post you may be intereseted in ' SEO Drupal Best Practice ' 

Monday 19 October 2015

Advanced CSS questions answered.

This is from the excellent and well recommended Advanced Sass Team Treehouse course.

The following Sass uses the @at-root directive within a media query. Sass considered @media to be root, so how can you update this so that the .barselector is at the absolute root of the document?



.foo {
@media (min-width: 400px) {
display: flex;
@at-root ( without: rule media ) {
.bar {
display: inline-block;
}
}
}
}



In the following code challenge, we are hard-coding the name of the nested selector .foo-bar. How can we update this to inherit the parent selector of .foo?

.foo {
@media (min-width: 400px) {
display: flex;
@at-root (without: media rule) {
&-bar {
display: inline-block;
}
}
}
}

Wednesday 14 October 2015

TypeError: this.form_*.options is undefined */sites/all/libraries/chosen/chosen.jquery.min.js?v=1.1.0 Line 2

This post is relevant to Drupal 7 chosen module and using Views and having an exposed filer.

So using Pages to set this up the first dropdown list wasn't displaying correctly .  And in Firebug error I could see the message

TypeError: this.form_*.options is undefined */sites/all/libraries/chosen/chosen.jquery.min.js?v=1.1.0 Line 2

What made this even stranger is that when calling the panel for the exposed filter again on the page the second version works fine.  Swap them around and it's always the top one that fell down.

In the end I found the code at fault in a customized file in themes.



 if (typeof $selects.chosen === 'function' && categoryLocation !== 'client-stories' ) {

        $selects.chosen({ 

          disable_search_threshold: 1,

          placeholder_text_multiple: 'Choose options',

          placeholder_text_single: 'Choose'

        });

      } 

A temporary fix was to ignore for the page I was on.  But does anyone know why the issue is occurring , I'd love to know.  Here's my fix .


             // an issue with the dropdown on 'client-stories' that's linked to this page - going to ignore this code for that page

        // 1. lets get the folder we're in.



        var pathArray = window.location.pathname.split( '/' );

        var categoryLocation = pathArray[1];

        // 2. and ignore the following if we are on the client-stories page .



      if (typeof $selects.chosen === 'function' && categoryLocation !== 'client-stories' ) {

        $selects.chosen({

          disable_search_threshold: 1,

          placeholder_text_multiple: 'Choose options',

          placeholder_text_single: 'Choose'

        });

      }



Thursday 8 October 2015

drupal 7 mini panels not being picked up in pages add content


drupal 7 mini panels not being picked up in pages add content



What you need to do here is set the category in the Mini Panel to 'Mini panel'  .

You'll then see it listed in 'mini panel' when adding content in pages.


Wednesday 23 September 2015

drupal 7 how to add exposed form view to pages

Go to the view you want to use the Form from . 

In advanced you can add ‘Exposed form in a block ‘ 

SAVE - Clear Cache. 

Once you do this then go the Page you are changing in Pages

Add content to a Panel 


> in the tab Views you will now see the form . starting with ‘exposed : ‘

Thursday 17 September 2015

To Add a New Display in Drupal 7 Display Suite.


> Navigate to ‘ Structure > Display suite > View modes > add a view mode


drupal 7 display suite mode not showing


Then go to the Display of the Article Type etc

> structure/types/manage/ARTICLE TYPE /display

> scroll down and find 'Custom display Setting' 

> select your display suite mode from here and save. 

Monday 14 September 2015

Drupal 7 Feed Importer Notes.

Just a couple of notes I've made regarding the Feed Importer.

Using Views and Feeds to Import. 



Tips -

  1. Save as ‘Windows Comma Separated Value’  
  2. Just Import New nodes
  3. We can expire nodes here. 
  4. FEED TAMPER - use if you want to make modifications to any fields. i.e. many php functions like rewrite, regex etc.  


Whats comes with Feeds. 


  1. Feed import
  2. Feed Import Base
  3. Feeds
  4. Feeds Admin Ui
  5. Feeds News
  6. Feeds Xpath Parser 

Twitter API working locally but not Live.

I had this issue recently and could not find and resolutions for it online.


After checking in Firebug > Dom >  I could see this issue


2015-08-25 10:03:24PHP errorPHP Fatal error: Cannot redeclare class OAuthException in jquery-social-stream/twitter.php on line 0 request_id="v-863a6920-4b10-11e5-bfa3-22000a22a668”


The solution for me here was to in the JQuery Social Stream JS file.  There is a class call for OAuthException  .  By wrapping that in an argument that checks whether it exists fixed my issue.




// redclare issue fixed by if statement

if (!class_exists('OAuthException')) {

  class OAuthException extends Exception {

    // pass

  }

}


 



Thursday 10 September 2015

error: unable to unlink old 'sites/default/settings.php' (Permission denied)

Here's and easy one I keep forgetting.

Not only do you need to change the permission on the file but the folder too.

Tuesday 8 September 2015

Write the Compass sprite configuration that assembles a sprite sheet by placing each image in the "ui" sprite map where it best fits.


Write the Compass sprite configuration that assembles a sprite sheet by placing each image in the "ui" sprite map where it best fits. 

The answer for this is 

$ui-layout: smart;

What can catch you out here from the examples is the UI value ; which was ICONS in the video example will need to change depending on the map/folder being used.  



Friday 4 September 2015

Error : Errno::EACCES on line * Permission denied


The answer for me was to delete all my .css files that where being created. 

Tuesday 18 August 2015

SASS how to add styling to all classes that preceed with X

I saw this on a Treehouse lesson earlier and wanted to keep it in mind for my future CSS code. What it does is add my chosen styling to all the classes that preceed with the chosen markup.

Friday 14 August 2015

SASS Placeholder selector

I've found this nugget of information hard to find on Google for some reason.

All I need to is make a placeholder and call it up again.

/* Placeholder selector */
%my-placeholder {
border: 1px solid black;
}


p {
@extend %my-placeholder;
}

Monday 20 July 2015

Avoid using comma and extra classes - using Sass compiler for CSS

Just seen this little nugget of code on TreeHouse and thought it quite useful for writing tidier code.

Rather than writing

.block, .foo {

  color: orange ;

}


you can use


.block {

color: orange;

}



.foo {

@extend .block;

//  the rest of my CSS for foo is already here

}


Wednesday 15 July 2015

Drupal 7 using Node Nid to get Entity Data

Ok I'm using this blog as a bit of a code bin.

Here's a quick sample of code if you need to get some Entity data from within - you'll need to add protection against any data not being available.

/*
 * Implements template_preprocess_node(&$variables)
 */


function rcnjobs_preprocess_node(&$variables) {
 $nid = $variables['nid'];

  $this_node = node_load($nid);
  $this_node_wrapper = entity_metadata_wrapper('node', $this_node);
  $recruiter = $this_node_wrapper->field_recruiter_reference->value();
  $recruiter_name = $recruiter->name;

  $location_tid_info = $this_node_wrapper->field_job_location->value();

  $location = $location_tid_info[0]->name;

}






Wednesday 24 June 2015

Webform conditional Jquery conflict with Chosen Module

My issue is that I have a select dropdown that when I use a Conditional on it , it then becomes greyed out.   These drop downs are also being run through the Chosen module.

After investigating in JQuery update I've found that if I change the version to 1.5 the dropdown shows, but this is not a suitable solution.

The solution in the end was for me to update chosen to the latest version - 7.x-2.0-beta4+1-dev

Wednesday 17 June 2015

Unable to use entity_ui_form_submit_build_entity on Node Entity_metadatawrapper

I was having issue with the following code when building an entity from form data.

$node = entity_ui_form_submit_build_entity($form, $form_state);


Here's the code I used that worked

$node = $form['#entity'];
      node_submit($node);

      $node->job_listing_node_form = TRUE;

      field_attach_submit('node', $node, $form, $form_state);

      $wrapper = entity_metadata_wrapper('node', $node); 

Monday 8 June 2015

Drupal 7 webform change single Radio button into checkbox

Here’s a quick one. 
I wanted to set up a tick box that when click on reveals some extra options.  This box can also be unticked if you don’t want the options.  

What you need to is when adding your type as ‘Select Options’ in the Form Component of Webform.
On the next page you’ll need to set only one options in the Option section. 

And then tick the ‘multiple’ selection above. If you don’t do this webform will create a radio button that cannot be unticked once it’s been clicked on.

Wednesday 3 June 2015

Drupal 7 Webform how to create Multi step form

When you're setting up 'Webform' in 'Form Component'  .

To start a new page you need to choose 'Page Break' in the the TYPE dropdown.

Tuesday 2 June 2015

CSS content text not adding space after comma

Using CSS content for some reason after a comma the space that follows would not appear.  It's fine for a full stop however.   Here's what I needed to add

 
.pane-content:before {

      content: "a sentance,\00a0 and a space. ";

 }

Monday 1 June 2015

Drupal 7 move Navbar to the left hand side in Administration

I’ve seen this Module being showcased on the lefthand side.  But after installing there is no configuration from Modules, so I was a little confused on how to move Navbar to the Lefthand side. 


In Css I made the existing admin menu disappear


#admin-menu-wrapper {

    display: none;

}



After this you can use the button on the right hand side of the NavBar menu and this will move the Navbar to the left hand side. 



Drupal 7 issue with moving Media Module 1.x to 2.x

I had an issue with Drupal 7 Media Module and specifically in that the Library was displaying as blank.

So instead I updated to Media Module 2.x ; Here's my configuration notes incase they're of help to anyone.



  1. Turn on modules ‘Entity API’ and ‘Entity tokens’ 
  2. Turn on modules ‘Media Bulk Upload’ - ‘Media Field’ , ‘Media WYSIWYG’ & ‘Media WYSIWYG View Mode’ 
  3. Media Permission - 'Administer media browser’ & 'Use the media browser’
  4. Enable ‘File Entity’ permissions .
  5. Go to ‘Status Report’ and ‘use Database updates Scripts. ‘Apply Appending Updates.
  6.  Check admin/config/content/wysiwyg  that Media Browser is installed. 

Friday 29 May 2015

Inside the array literal, add three object literals. In other words, the objects array should have three values. Each object should have 2 property/value pairs.

var objects = [
  {
    object: 'Car',
    description: 'A2B'    
  }, 
  {
    object: 'Surfboard',
    description: 'Fun'   
  }, 
  {
    object: 'house',
    description: 'home' 
  } 
];

 

Tuesday 19 May 2015

Drupal zend server 'The specified file temporary://* could not be copied '

The specified file temporary://f* could not be copied, because the destination directory is not properly configured. This may be caused by a problem with file or directory permissions. More information is available in the system log.



In Drupal 7 Admistration Go to the Media paths configurations.

> /admin/config/media/file-system

Set up the ‘Temporary Directory’ 

for example ‘/tmp’ 


In the scenario you’ll need to create and chmod a folder to 755 

ZendServer_init has not been started because it does not have the proper security settings

Here's the error I'm getting

“Library/StartupItems/ZendServer_init” has not been started because it does not have the proper security settings.  

And in the log file a 'zend server fix Symbolic links issue' warning.



I'm using Mac OsX Mavericks


$ ls -la /Library/StartupItems/ZendServer_init
total 32
drwxr-xr-x 5 root zend 170 Oct 28 11:44 .
drwxr-xr-x 3 root wheel 102 Nov 12 12:59 ..
-rw-r--r-- 1 root zend 274 Oct 3 2011 StartupParameters.plist
-rwxr-xr-x 1 root zend 312 Oct 3 2011 ZendServer_init
-rwxr-xr-x 1 root zend 5097 Mar 11 2013 zendctl.sh

$ sudo chown -R root:wheel /Library/StartupItems/ZendServer_init

$ ls -la /Library/StartupItems/ZendServer_init
total 32
drwxr-xr-x 5 root wheel 170 Jun 25 08:20 .
drwxr-xr-x 4 root wheel 136 Oct 31 11:45 ..
-rw-r--r-- 1 root wheel 274 Oct 3 2011 StartupParameters.plist
-rwxr-xr-x 1 root wheel 312 Oct 3 2011 ZendServer_init
-rwxr-xr-x 1 root wheel 5097 Mar 11 2013 zendctl.sh

Monday 18 May 2015

MaxMinds GeoIp could be the solution for you if you want to run country specific redirects.



First off you’ll need to get a License Key.  

In your index.php ( or sub category etc that you want to redirect from )


At the top of this page call the JavaScript file from MaxMind . 


First of all lets make a variable called ‘redirect’ and implement the redirection 

var redirect = (function () {


Next up lets build the URL . To do this we make a variable call ‘redirectBrowser’  and inside that pass a Site variable to build the uri . The site variable will be assigned once we’ve made decision on which countries IP we are passing onto.   Here’s that variable and it’s function. 

var redirectBrowser = function (site) {
  var uri = "http://" + site;
  window.location = uri;
};

The variable ‘sites’ which is different to ‘site’  is an array of all the country codes we’ll be using.   You can find a list of the ‘Maxmind Country Codes’ here. 


In the following code I assign Nordic IPs and GB.  

var sites = {
  "no": true,
  "se": true,
  "gb": true,
  "dk": true,
  "fi": true
};

Change these to Lower Case

var code = geoipResponse.country.iso_code.toLowerCase();

Let’s have a look at this example .  As long as the sites are listed in the county codes then if they have no redirect here then they’ll stay on the existing website.  Otherwise they’ll be forwarded to the ‘else’ redirect. 

if ( sites[code] ) {

  if (code == 'gb'){
    var site = “theukwebsite.co.uk"
      redirectBrowser(site);
  }
}
else {
  redirectBrowser(“theworldwidewebwebsite.com");
}

So eventhough we don’t mention the Nordic countries here they will still be dealt with differently to countries that aren’t listed in the ‘sites’ variable. 

Let’s add onError forwarding also.  So here’s the full code. 

var redirect = (function () {
  /* This implements the actual redirection. */
  var redirectBrowser = function (site) {
    var uri = "http://" + site;
    window.location = uri;
  };

  /* These are the country codes for the countries we have sites for.
   * We will check to see if a visitor is coming from one of these countries.
   * If they are, we redirect them to the country-specific site. If not, we
   * redirect them to world.example.com */
  var sites = {
    "no": true,
    "se": true,
    "gb": true,
    "dk": true,
    "fi": true
  };
  var defaultSite = "gb";

  var onSuccess = function (geoipResponse) {
    /* There's no guarantee that a successful response object
     * has any particular property, so we need to code defensively. */
    if (!geoipResponse.country.iso_code) {
      redirectBrowser("gb");
      return;
    }

    /* ISO country codes are in upper case. */
    var code = geoipResponse.country.iso_code.toLowerCase();

    if ( sites[code] ) {

  if (code == 'gb'){
    var site = “theukwebsite.co.uk"
      redirectBrowser(site);
  }
}
else {
  redirectBrowser(“theworldwidewebwebsite.com");
}

  /* We don't really care what the error is, we'll send them
   * to the default site. */
  var onError = function (error) {
    redirectBrowser("theworldwidewebwebsite.com
");
  };

  return function () {
    geoip2.country( onSuccess, onError );
  };
}());

redirect();

Tuesday 12 May 2015

zend server how to find my web server document root directory on Mac OS X

Explains that a default installation of Zend installs at 


usr/local/zend/apache2/htdocs/

mac Mamp issue - Do you already have another mysqld server running on port: 3306

I’m using Mamp and am setting up Zend Server Z-Ray.  After installation I noticed the SQL on my other site ( running on MAMP ) failed. 

To fix this in MAMP - 

Click on the General tab.  

In Mysql Port -> select a new number > valid numbers are from 1024 to 65535


Monday 11 May 2015

How to turn off jshint on grunt.js .

Near the end of the Gruntfile.js file we have the code 

grunt.registerTask('build', [
  'compass:dist',
    'jshint'
]);


Changing this to 


grunt.registerTask('build', [
  'compass:dist',
    'jshint'
]);

solved my issue.


Thursday 30 April 2015

Blog about Improving the Drupal CMS User Experience.

I'm currently working for this Drupal Development Company in Newquay, Cornwall  . At which we've got round to adding Blogs.  Where I will be blogging regularly.

Check my latest blog

Improving the Drupal CMS User Experience


Basically it's my notes from Drupal Camp London on the Seminar of the same name. 

Tuesday 21 April 2015

Drupal 7 Taxonomy Ordering

What I need to do was Order my taxonomy from Parent to Child .

There are a couple of solutions to this; but I had issue with both .  Lets have a look at those first before I give my programmatical solution.

Hierarchal Term Formatter : https://www.drupal.org/project/hierarchical_term_formatter

Unfortunately installing this on my existing Drupal site causes all the fields in any views that contain taxonomy to disappear :/ Shame as this would have been perfect.

2. to order them BY ID, or NAME, or WEIGHT.
You need to create in Advance (Views) a Relationship pointing to that Taxonomy Vocabulary
Then you can add a Sort Filter



However this was the code that sorted the issue for me.

/**
 * @file Orders Taxonomy

 *

 * @param $tid - expecting a tid  

 * @param $no_results - the number of results that you'd like to return

 * @param $order - which tid first - child or most senior parent ?

 *

 * @return returns a string .

 */



function rcn_taxonomy_order($tid, $no_results = 1, $order = 'first') {



  $wrapper = entity_metadata_wrapper('taxonomy_term', $tid);

  $all_parents = $wrapper->parents_all->value();



  ($order == 'last') ? $all_parents = array_reverse($all_parents) : $all_parents;



  $stitch_term_array = '';

  foreach ($all_parents as $key => $term) {

    ($key < $no_results) ? $stitch_term_array .= $term->name . ", " : '';

  }



  return rtrim($stitch_term_array, ', ');



}

Tuesday 14 April 2015

Drupal 7 - Error Reported in log - array_splice() expects parameter in template.php


In Report Logs we we’re getting these errors on Clearing the Cache.  

Warning: array_splice() expects parameter 1 to be array, null given in omega_theme_registry_alter() (line 458 of */sites/all/themes/contrib/omega/omega/template.php).

Warning: array_search() expects parameter 2 to be array, null given in omega_theme_registry_alter() (line 445 of /Users/DJ/Sites/mampsites/sccbb/sites/all/themes/contrib/omega/omega/template.php).

Warning: array_unshift() expects parameter 1 to be array, null given in omega_theme_registry_alter() (line 447 of /Users/DJ/Sites/mampsites/sccbb/sites/all/themes/contrib/omega/omega/template.php).

Warning: array_splice() expects parameter 1 to be array, null given in omega_theme_registry_alter() (line 449 of /Users/DJ/Sites/mampsites/sccbb/sites/all/themes/contrib/omega/omega/template.php).

Notice: Undefined index: preprocess functions in omega_theme_registry_alter() (line 445 of /Users/DJ/Sites/mampsites/sccbb/sites/all/themes/contrib/omega/omega/template.php).


To test this I locally ran this test in the omega/template.php at line 445

// @todo temporary debugging code to look for an error
// check to see if this is an arry
if (!is_array($registry[$hook]['preprocess functions'])){
  watchdog('!array preprocess func', $hook);
}
if (!isset($registry[$hook]['preprocess functions'])){
  watchdog('!isset preprocess func', $hook);
}
// @todo end debugging



This report any hook preprocess functions that are not as should be .   Which returned the one result .  

‘block_swiper’



On checking we have a Swiper module installed. When disabled we no longer receive a PHP error message.   Also note on checking Clear Cache needs to be run each time. 

Thursday 2 April 2015

Drupal 7 - Adding a Delete Button to open in Modal PopUp

The task here was to add to existing code ; where we where adding a delete button like those being called in an already existing module.

The task check list. 
1. Find a delete Quiz result function in the Quiz module.   If there isn’t one this will need to be created. 

2. Create menu callback for modal form. 

3. Set in hook_menu

4. Write an access rule for this . 

5. Call up in View. 




1.  There was no Delete form so lets create one in modules/custom/rcni_saqs/includes/form.inc 

[code]

/**
 * @file
 * Custom forms.
 */

/**
 * Form builder.
 *
 * @param array $form
 *   An associative array containing the structure of the form.
 * @param array $form_state
 *   An array which stores information about the form.
 *
 * @return array
 *   Completed form array.
*/
function rcni_custom_delete_form($form, &$form_state, $quiz, $quiz_result_id) {
  $quiz_result = quiz_result_load($quiz_result_id);

  if (!$quiz_result) {
    return array('error' => array('#markup' => 'Could not find quiz result.'));
  }

  $form['quiz_result'] = array(
    '#type' => 'value',
    '#value' => $quiz_result,
  );

  try {
    $w_quiz = entity_metadata_wrapper('node', $quiz);
    $quiz_title = $w_quiz->label();
  }
  catch (EntityMetadataWrapperException $e) {
    watchdog_exception(‘my_custom', $e);
    $quiz_title = '';
  }

  $message = t("Are you sure that you want to delete your answers for %quiz_title?",
    array("%quiz_title" => $quiz_title));

  try {
    $w_quiz_result = entity_metadata_wrapper('quiz_result', $quiz_result);
    $redirect = "portfolio/portfolio/{$w_quiz_result->field_custom_field->raw()}";
  }
  catch (EntityMetadataWrapperException $e) {
    watchdog_exception(‘my_custom', $e);
    $redirect = 'eportfolio';
  }

  $form['submit_redirect'] = array(
    '#type' => 'value',
    '#value' => $redirect,
  );

  $caption = t("This action cannot be undone.");

  return confirm_form($form, $message, $redirect, $caption, t('Delete'));
}

/**
 * Form submit handler.
 *
 * @param array $form
 *   An associative array containing the structure of the form.
 * @param array $form_state
 *   An array which stores information about the form.
 */
function my_custom_delete_form_submit($form, &$form_state) {
  quiz_delete_results(array($form_state['values']['quiz_result']->result_id));
  $form_state['redirect'] = $form_state['values']['submit_redirect'];
}

[/code]


2.  Lets add that callback now to /cutom/rcni_modal/includes/saqs.inc

/**
 * @file
 * Modal form wrappers for SAQs.
 */

/**
 * CTools modal form wrapper function.
 *
 * @param object $quiz
 *   The quiz node the results belong to.
 * @param int $quiz_result_id
 *   The rid of the quiz result we're deleting.
 * @param bool $js
 *   Whether javascript is enabled.
 * @param bool $refresh
 *   Whether to refresh the base page on form submission.
 */
function my_modal_custom_delete_form_modal_callback($quiz, $quiz_result_id, $js = FALSE, $refresh = TRUE) {
  if (!$js) {
    if ($quiz_result = quiz_result_load($quiz_result_id)) {
      $portfolio_id = rcni_modal_get_parent_portfolio_id($quiz_result);
      $options = $portfolio_id ? array('query' => array('destination' => "portfolio/portfolio/{$portfolio_id}")) : array();
      drupal_goto("node/{$quiz->nid}/quiz-results/{$quiz_result_id}/delete", $options);
    }
    else {
      drupal_goto("eportfolio");
    }
  }
  else {
    $form_state = array(
      'ajax' => TRUE,
      'build_info' => array(
        'args' => array(
          $quiz->nid,
          $quiz_result_id,
        ),
      ),
      'rcni_modal' => TRUE,
    );

    $form_id = ‘my_custom_delete_form';
    form_load_include($form_state, 'inc', ‘my_custom', 'includes/form');
    my_modal_custom_form_modal_callback($form_id, $form_state, $refresh);
  }
}

3.  Build the menu item that it gets sent to. 


/**
 * Implements hook_menu().
 */
function my_modal_menu() {
  $items = array();

  $items['node/%quiz_menu/quiz-results/%quiz_rid/delete'] = array(
    'title' => 'Delete answers',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('rcni_saqs_delete_form', 1, 3),
    'access callback' => 'rcni_saqs_quiz_result_delete_access',
    'access arguments' => array(3),
    'file' => 'includes/form.inc',
  );

  return $items;
}


4.  The Access rule. 

/**
 * Access callback for deleting a quiz.
 *
 * @return bool
 *   True if user can delete quiz result.
 */
function rcni_saqs_quiz_result_delete_access($result_id) {
  if (user_access('delete any quiz results')) {
    return TRUE;
  }

  global $user;
  $quiz_result = quiz_result_load($result_id);

  if (!$quiz_result) {
    return FALSE;
  }

  return user_access('delete results for own quiz') && $user->uid == $quiz_result->uid;
}

5. 

[code]
.


[/code]

Tuesday 31 March 2015

Drupal 7 Form API - Reveal Input on drop down condition

Here’ the task :  I have a drop down list , a simple ‘yes’ or ‘no’  .  If yes fill in the the input box. 

At first I thought this would need a simple Ajax form call but in fact its even easier than that.   We can use the ‘States’ and ‘visible’ values of the Form API [https://api.drupal.org/api/examples/form_example%21form_example_states.inc/function/form_example_states_form/7]

Here’s my code that solved this issue

$form['addtoportfolio'] = array(
  '#type' => 'select',
  '#prefix' => "Your score was $score%; the pass rate is $pass_rate% ",
  '#title' => t('Would you like to add this to your portfolio ?'),
  '#required' => TRUE,
  '#options' => array(
    'n' => t('No'),
    'y' => t('Yes'),
  ),
  '#default_value' => t('No'),
  );



$form['timetaken'] = array(
  '#type' => 'textfield',
  '#title' => t('Time Taken ?'),
  '#required' => FALSE,
  '#description' => "Please enter the time in minutes that it took you to do this quiz.",
  '#size' => 4,
  '#maxlength' => 10,
  '#states' => array(
    'visible' => array(
      ':input[name="addtoportfolio"]' => array('value' => 'y'),
    ),
  ),

);

Friday 27 March 2015

Drupal 7 how to save values to an Entity in Form Submit.

Yes you can add a field with a db_query like this

time_taken_updated = db_update('quiz_node_results')
 ->fields(array(
 'time_taken' => $time_taken ,
 ))
 ->condition('result_id', $result_id, '=')
 ->execute();


but it's better to do it with Entity_Metadata_wrapper in your hook_form_submit

like


$saq_results = entity_load('quiz_result', array($result_id));

$saq_results_wrapper = entity_metadata_wrapper('quiz_result', $saq_results);

$saq_results_wrapper->time_taken->set($time_taken);

Wednesday 25 March 2015

Modular CSS with Sass notes.


The @content directive lets us pass custom styles to a mixin when including it.


With SMACSS, element state selectors are usually prefixed with .is- 

The @at-root directive lets us nest a Sass rule without nesting the output.

In a conditional mixin, which directives are used to set the conditions? 
if and else


Now onto that last question 


Add the statement that instructs @at-root to output the nested state rule outside the @media query.  Anyone know the answer?

Friday 20 March 2015

Drupal 7 Theme TouchM make Portfolio Images Link to Node or Page.



> Copy these two pages from sites/all/modules/tabvn/portfolio/    
  1. portfolio_4c.tpl.php
  2. portfolio_filter.tpl.php

>  Paste them into sites/all/themes/touchm/templates

> OPEN 

/sites/all/themes/custom/touchm/templates/portfolio_4c.tpl.php

CHANGE LINE 35 to . 











Thursday 19 March 2015

Drupal 7 Views Display SQL Query

How to display the SQL query on Views.

admin/structure/views/settings  tick ‘Show the SQL query’

Friday 13 March 2015

Adding OG Tags to a Drupal 7 website

)pen Graph tags are tags that are used to grab content by some of the major Social Medial site. 


I’ve added code to the themes template.php that will display this .


The main issue here was the 'image' tag which I've cross referenced the database for . These fields will be different for others ; depending on the tables that store your images.


/** * Implements template_preprocess_html() * * @param $vars *   An array of variables to pass to the theme template. *   The name of the template being rendered ("html" in this case.) */
function theme_preprocess_html(&$vars) {

  /* * @ file Open Graph Meta tags - for LinkedIn and Facebook * * The following code writes the relevant metatags required for Open Graph. * check 'open graph' on  https://developer.linkedin.com/docs/share-on-linkedin * for more information * There's 2 images in the node that we can add  1. field_image and 2. field_header_image * We'll try field header image first. * Lets get the node id. */  global $base_url;


  $og_url = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  $site_name = variable_get('site_name');
  $og_title = $vars['node']->title . ($site_name ? ' | ' . $site_name : '');
  $od_dec = $vars['page']['content']['metatags']['node:flexible_article']['description']['#attached']['drupal_add_html_head'][0][0]['#value'];
  $page_node_attribute = $vars['attributes_array']['class']['6']; //  $page_node_attribute_array = explode('-', $page_node_attribute);
  $nid = end($page_node_attribute_array);

  drupal_add_html_head(array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:title',
      'content' => $og_title,
    ),
  ), 'node_' . $nid . '_og_title');

  drupal_add_html_head(array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:description',
      'content' => $od_dec,
    ),
  ), 'node_' . $nid . '_og_description');

  drupal_add_html_head(array(
    '#tag' => 'meta',
    '#attributes' => array(
      'property' => 'og:url',
      'content' => $og_url,
    ),
  ), 'node_' . $nid . '_og_url');


  $result = db_query('SELECT fm.filenameFROM {field_data_field_header_image} fhi LEFT JOIN {file_managed} fm ON fhi.field_header_image_fid = fm.fid  WHERE fhi.entity_id = :nid  LIMIT 1', array(
    ':nid' => $nid,
  ));
  $image_file = $base_url . '/';
  foreach ($result as $record) {
    $filename = $record->filename;
    $filename_fixed = str_replace(' ', '%20', $filename);
    $image_file .= 'sites/default/files/styles/article_header/public/header_images/' . $filename_fixed;
  }

  if (!isset($filename) && $filename == NULL) {
    $result2 = db_query('SELECT fm.filenameFROM {field_data_field_image} fhi LEFT JOIN {file_managed} fm ON fi.field_image_fid = fm.fid  WHERE fi.entity_id = :nid  LIMIT 1', array(
      ':nid' => $nid,
    ));
    $image_file = $base_url . '/';
    foreach ($result2 as $record) {
      $filename = $record->filename;
      $filename_fixed = str_replace(' ', '%20', $filename);
      $image_file .= 'sites/default/files/styles/article_header/public/header_images/' . $filename_fixed;
    }
  }

  if ($filename != NULL) {
    drupal_add_html_head(array(
      '#tag' => 'meta',
      '#attributes' => array(
        'property' => 'og:image',
        'content' => $image_file,
      ),
    ), 'node_' . $nid . '_og_image');

  }
}

This code was inspired by http://kahthong.com/2012/08/add-open-graph-protocol-meta-data-your-drupal-node-page

Thursday 5 March 2015

Some tips on checking your code in Drupal

Before I start it's worthy of note that this is not really a blog but more of a place where I copy and paste my own notes on things.  If the following is of help to anyone then thats great also.  Conversation on better techniques are also more than welcome.

There’s  a handful of different methods for checking your code.  One way is to run the ‘Code Sniffer’ from inside PHP Storm .  This is a great way to keep a running score of anything you might need to fix. 

As well as John’s notes on this here . 


and the jet brains instruction on this is here.  


Check in Project Settings > inspections > Enable ‘PHP Code Sniffer validation'












From here on you get a list of suggested changes on the right hand side.  You can see these by clicking on the yellow box and then running down the righthand side are some yellow markers; click on these for suggested code changes needed. 



Another way though is to install project/coder module on your drupal installation .  I find this easier to use; especially if you’re reviewing a module. 

Thursday 26 February 2015

Drupal 7 views search api add displaying count

If you'd like to let your users know how many search terms there has been on a search then .


Go to the View you are using for the search page .


administration > Structure > Views


> go to the display you are on  ie 'page'

> in the middle panel find 'HEADER'

> click add

> find 'Global: Results summary'

>  this will be pre filled with 'Displaying @start - @end of @total'  which you can change and add extra tokens if you need.

Monday 23 February 2015

drupal 7 search api facets change Show more text

Go to > Administration > Configuration > Search and Metadata


Edit >  'Facet "more" link text

And Edit 'Facet "fewer" link text 
 ‘ 


SAVE 

Friday 20 February 2015

drupal 7 how to make a view from indexed search


drupal create a search view for indexed node solr

The key here is to choose the name of the search index from the ‘show’ drop down box when you ‘Add a new view’  .  Check this page for full instructions. https://www.drupal.org/node/1597930 

Tuesday 3 February 2015

MAMP Pro issue with changing php.ini files

The issue here is caused by trying to be too clever and changing php.ini files in the address given in you php info.

when what you need to do is use the MAMP Pro UI


 MAMP PRO > FIle > Edit Template  > php.ini > your default 

Tuesday 27 January 2015

Drupal Theming - Bootstrap Import errors - import not found or unreadable: bootstrap.

here was the error

error sass/bootstrap/test/dummy_sass_only/import_all.sass (Line 1: File to import not found or unreadable: bootstrap.
Load paths:
  */sites/all/themes/*/sass
  /Library/Ruby/Gems/2.0.0/gems/compass-0.12.2/frameworks/blueprint/stylesheets

  /Library/Ruby/Gems/2.0.0/gems/compass-0.12.2/frameworks/compass/stylesheets   Compass::SpriteImporter)


The fix was to change this line in /sites/all/themes/my_theme/sass/custom.scss

@import 'bootstrap/assets/stylesheets/*';


to 

@import 'bootstrap/assets/stylesheets/bootstrap’;

Adding Excerpts to Solr Search Results - Including attachments

First off I’m going to address the question ‘ How to Add Excerpts to the Solr Search API ‘ .

This is worthy of note as the obvious way is to do it through the Search API UI; when in fact this method needs to be disabled and instead edited on the Solr Server Settings ‘ Still within Search API setting ‘ 

Step-by-step guide


  1. Check the following is disabled.
> admin > configuration > filters > under ‘Processors
> check that ‘Highlighting’ is unticked
>  SAVE SETTINGS
 > admin > configuration > 'Your Server' > edit

2. 
> under 'Advanced' > tick 'Return an excerpt for all results.'
> 'Save settings’

3. Then in your view for the search you have add ‘Search: Excerpt’  Field. 


Adding an excerpt from an Attachment 

There’s is a bug with Search API and Excerpts; currently there is a patch which isn’t on the development release. Go to this page to get this 

Friday 23 January 2015

Drupal 7 - how to make a panelled Search page.

Instructions on how to make a panelled Search page .  Like this

Step-by-step guide

Add the steps involved:
  1. in > admin > Structure > Blocks
  2. Search for your facets and select the block you want them to go in . ie 'Sidebar First'

  3. SAVE

  4. open your View > Page .

  5. under FORMAT change Show to 'Panel Fields'

  6. In Settings choose your Panel Layout from the list. ie 'AT One Column' should display the above block example.



7. And then still in the VIEW - making sure you are in the 'Page' display; otherwise you won't see this option. Under 'Advanced' - you should now see under 'Exposed Form' the text 'Exposed form in block:' - Change this to Yes.
8. Once you've added this to the view you'll now be able to go back to > structure > blocks.
And see the exposed form here to move to the block you wish.

Thursday 22 January 2015

Drupal 7: Programatically Make Solr 'Read Only' on none live environments . Acquia

The following code is no longer needed once 'Adding Multiple Search Cores' is set up.  However it's worth documentation as the Multi search core facility may not be available for all.

Here's a piece of code I wrote to make a search 'Read Only' - also in here is how you can set an index up - and leave that one live for testing. 



if ($_ENV['AH_SITE_ENVIRONMENT'] == 'prod' ) {
  // check for live environment
}
else {

  $result = db_query('SELECT name, server, read_only, machine_name
 FROM {search_api_index}
 ');
  $rowcount = $result->rowCount();
  //print "Query $rowcount 
";
 foreach ($result as $record) {
  // print_r($record);
 $read_only_value = $record->read_only;
    // print "Read only value = $read_only_value - v1
";
 // machine_name check here has only been added for pre testing before going live with this search
 // delete when this search is added for real.
 if ($read_only_value == '0' && machine_name != 'candidate_cv_search'){
      $updated = db_update('search_api_index') // Table name no longer needs {}
 ->fields(array(
              'read_only' => 1,
          ))
          ->condition('read_only', '0', '=')
          ->execute();
    }
  }

}


Wednesday 21 January 2015

Drupal 7 Commerce : How to send Emails to Users of a Certain Role



  1.  'store settings' > checkout settings > click on the 'checkout rules’ tab  >
  2.  Click on ‘Add a Checkout Rule’ 
  3. Fill out a name
  4. Add Event - Completing the checkout process
  5. Add Actions > Under system > Send HTML mail to all users of a role’ 
  6. SAVE

Tuesday 20 January 2015

Drupal 7 commerce can i remove order statuses

The Situation:

I have a role of 'Sales Manager' - they have access to manage the orders.

On the dropdown for Order statuses I can see the following . 



What I'd like to do though is limit this to - Pending, Process and Completed.

To fix this the following code works a treat.

/***
 * Implements hook_commerce_order_status_info_alter
 */


function my_commerce_patch_commerce_order_status_info_alter(&$order_statuses){

 global $user;

  if (in_array('sales manager', $user->roles)) {
    unset($order_statuses['cart']);
    unset($order_statuses['checkout_checkout']);
    unset($order_statuses['checkout_shipping']);
    unset($order_statuses['checkout_review']);
    unset($order_statuses['checkout_payment']);
    unset($order_statuses['checkout_complete']);
  }

}

Drupal 7 commerce cart not showing titles - after kickstart installation.

I found this one a little difficult to find.  So here’s where it’s at. 

Look for the view Shopping cart form .  and click on Edit.

> on the right hand side click on 'Add' next to 'Relationships'

> Add 'Line items referenced by commerce_line_items) Commerce Line item: Product

> Then in Fields add 'Commerce Line item: Product'

> click on 'rearrange' next to fields.  drag above 'Global text'

In that View what you need to edit if the field Custom text’  



> and then rearrange the tokens in the Text that you wish.   I added [line_item_title]


Drupal 7 : Saving Views prints machine code

This is something thats happened a couple of times to me on different projects; so I though I'd document it.

On saving a view I was getting a page of output that started with  
[{"command":"settings","settings":{"basePath”:  

The issue here is with JQuery.  So take a look at what JQuery is being used or install the 'JQuery Update' module. 

Drupal 7 adding User to Menu Link.




Adding %user to Menu Link  - use tokens -  try the ‘Menu Token ‘  module. 

Here's how I solved this one. 

Installed the Module Menu Token  .  I had to use the Development Release here as the Recommended release did not work for me.  It also needs the Universal Unique Id module .

1. Add the module 'Menu Token'
2. Go to the Modules 'configuration'
3. Add the entities that you'll be needing the tokens from ..
4. Add your path link following the modules instruction - ie user/[current-user:uid]/profile
5. tick 'use tokens'
6. Select how you want this relationship to work from the dropdowns. ie 'Method for Users' = 'User from context'

For menus go to add links and then follow the instructions from stage 4. 

Monday 19 January 2015

Drupal 7 Commerce : Drupal Page Manager Views not showing in Pane selection


Drupal Page Manager Views not showing in Pane selection


Enable the module ' View Content Pane '

Drupal 7 Commerce : All products to be listed on one page.

Here's the look we're trying to achieve. 




Step-by-step guide

  1. Install this Module - 'Commerce Add to Cart Extras ' - https://www.drupal.org/project/commerce_add_to_cart_extras
  2. Add a View
  3. Type = 'Commerce Product'
  4. I've used a Megarow Table as the Format in my example. 
  5. in Fields I've Added 'Commerce Product: Product ID' , 'Field: Title' 

Drupal 7 Commerce : Inventory Stock Ordering Page.

For Inventory Administration we would like an easy to use page where stock can easily be update. 

Step-by-step guide

  1. Install 'Commerce Stock' module .  - https://www.drupal.org/project/commerce_stock
  2. install ' Editable Views ' module .  https://www.drupal.org/project/editableviews
  3. Add a new view
  4. Select 'commerce product' 
  5. Display Format should be set to 'editable table'
  6. Add the fields you wish.  using (editable) version for where you want to be able to edit it. 



Drupal 7 Commerce : How to Return a list of a Users Orders in Views.

The aim here is to reduce the checkout process as much as we can; as in the website we are currently  creating we do not need  user address, Shipping and payment.

Step-by-step guide

  1.  Login to 'Store settings'
  2. Drag and drop 'Review' and 'Shipping Service' under 'Disabled'
  3. See images for further setup instructions
  4. You can then use CSS to get rid of things that don't need to be seen






Drupal 7 - Page Manger - Panels - No gear button - Can't add Views

In the eventually you can't see the 'Gear button' on Panels / Panelizer .   Like this



This is a JQuery issue.

You should either add the module 'JQuery Update'  ; if you have already installed this module then you may well need to check the settings.  Try changing the default JQuery version or the 'Alternate jQuery version for administrative pages'  .  Save and Clear Cache.