# Question
Title: Drupal 7 site display unexpected symbols
My site working very effectively on my localhost, but when I move the working site's all folders and files to Live Server i.e to cPanel, Its only display unexpected symbols that are given below.

```
‹Ý0M™å‘/ðë¥R!ŒH6L¨½¯Tl³/)4-/`4A‹.iÌ$³·†1‚š–b·Ê¹¢jZ-"¯i!¶=Ç¡Wô¶Ö¢c.kžu›pW:W_R–ÚF½¶™Õj!jWÒj5ƒ°µöÃb‚¹hB:=ú…4Íçÿ Ÿ>ÿ’ubK-NeýS¥#™Ú÷<‘FªR%•ûöËÝÍÍ—õm{£òùÅ<CR€u"Ôµ±/”hŒJ¨w}F{¼”Zï¦‘‡oýùZ,Oä¿G{ð&i:¯y`ðŠkë#o¥ F`xMû&©Lh¥26ˆÊaäÁ(•¤l¬æ š×+8]r¯Bš%êðÐ¸¢Zœ%<_I6Ðq¤*dÏÔ¡zssSyAþƒT²É¶iDƒ¡âž™r t%K,¡¨²,i©LLùzxI{¨å‘ÀŸêŸG°²ƒ#ˆÔ    ¬Ë$KÔk¾„÷À;ÈB;ß^¬gå‘%éZÀ£kÒOX·™sß—“fêIùk—†<6©{[õzuÃüçà5¸W} µ—Em«(½‚öWEm·^¯„ÍŠv²Ï˜ªS6“„*°iY2qh·HÈ|NÁõÕúG§¤HšëÖHñµ’):àR âÈ¡–}j.•¬†E»êv×µ@1G³”Êb“–ÈêÂ¶N€Ê]™’q'”±P‹ØM¹ø‘¦1Ãº‰+n;Øûxm%ø}ð0úG,_VŒ6q;zVLsÌ½k–Ô6j¯1ç]Îß`5å•pˆl›Â½ÆkàUÏÜ'¬00Ø½~öY‰¬©Ëœ”“z´XRVŽ6?õÊÅ•“€È&aEaµè!Î‹c¹}ËìóˆÉL%j[®HÓ]Htd¦ôÜ®/wI†,qÖ¥i F®*kèèþÕøDqºÙW3ß`þ©êˆ.Úw=Y.½fž2ëÌKZÖñ¦GÉ<Ÿˆ9$Ø¡pù#gk> W%!:Žçèt©#ÆÔ"ƒƒU~–¸’¿šµÚVù<±"ä"òXNas•øý$i€¨3Õ¬·>i¦_Õ6WÅõrQËªåQ‡C%œÙyÙ)…lÒòºmŽ™OÅÉ”s¼•Ÿ“ìý|ò÷ÑC'ÔÚwùõ'Ygçô8Ú<áZ›í_¯ò´J- .xwø„*¾‹…œ€õ‘â;°`Ð|Ê£íí» ‡ƒþmÛql»ÕøñÓÁáþåþ'ÇiaãÚÕ_õ´‹üõC³OI¦”I„~µ0ÑpFUßÚ³ÚŽUµb(Ÿ%¬Ëo¡ê¸ý`FìBUX{_--ô#uGG‰kA÷ÎÇƒóð ÷ã«wÿ•þ>è½ ¶w½_Þ~<Œ/6?ü1ŒÞ}8í¥ÁÕ[  °WQã:l"ko£:Þ–mà¥Žbç-µe;¦nÑúoã´s÷ÒßÝÚS›Ý`±KÆ–K³7ª»Éd©vO³?´ó ¢=‡X–Ü»Ï‡›ðÃíŽ¹4 %‡:…Ò,†öÄj0üL;Ã‡€—ÙRà…Z ªì@XXÍ·ª…\¹âM¢¬=™4Êž3¨HúÝ1j”Ì[8°HÒÍ7Q=‘S{àR\‰“Û.ò`í"v/âÍÌt’k\:_• o²WóI%¢ÚÓy©qôFö1‘GJÕù£v)´`}fùv‘j¥ˆî   ™e|ÚÙŸ{BëtN{,±sÈ}KÞŸÌƒ˜9?È>÷ðU Ó!”Ù&lýDK¿\Ù‹DÄòÉrŒ¼wjÿžÊï#:£|R¿[ý\hD¼§ùö Ûs]èŒæeŽ`s‹À¶4tŠ<ì¾6:òÉQwä‰~€ÿ²ž¿áyQKÅpümÓfLå'Ù7x†¬¼¨yœf«á+Ûp#%ºÙ%Ä [·@ÿ /¡ôØoY!ûŽ¿ð)Ià¦øÚŽp¿iåXD?‹lZƒµ(ˆG4°Ç›•&«uÐ"¶¬9seN   UP’Cú¸§Ë˜FÅÞ Vk#\ë÷£“äŸÿìC7î³†ß‰i79ó—S#%Æ Ê––r¬nÊ”Œ",–Ð J5)ÓViavy"a· ’Ï|â'"öÅY§ÙR„¹ˆ;" 8.Ï,—©ob ,ãÓð“Õº\ãú…•É”ŽíP«zmŽ$*ÈÌábÈîZÑ—}FD4‡Ï äßÓ4!X¼×"(´š0†úÄÏR€×È‚f…ûOhŒc«u†Ÿ»&o¶ô¿ø,åÐÎq!‚²&£ÂÖkhÏÜ½¬CŸ7=e§_‡Õ*McÑ¢AÌÚ5˜Âl}cqáæ–5¬ÍPÚû¤dó` ¢žQü37öqëâòã#²rHÞì_¼{zBÞœž“w§¿5œx;S•¢˜LÞó ivtà`AŒ(f[zI–IxžLÃßÌ+õ9ÆªsYF=›£;%ý¬«´d   §5¼µ¡a  Má˜Ð!   „ˆg…ý ~Çc;/³Pã-+‹guƒƒ Ï@ë8]lxº7Ì Ç  ë–™”…{–«ÝÈÊTm~¯Éz¹Y‡c˜Îm6Íúœcgƒ….øÇÉ.oºh8šØLM8F3¬ÖÑ¨§Ì}F„¾8hÏVÔÏ¥Õ×ÎÊ¥Q„âåÔ¬ˆõ§ýó÷ót]J&¤¡-K%þ.Üá!œÓî“NÌ_u9>·É!í3ù€Î†9$Ï?Ò—·§¾¸PÍ7¨ùP%…¸B¹â@ïÈf”Ev]ˆ   ÈduYYÃ!^gø¾ß©ß%å´=˜fúcšÌ&Ü{“Êö&Ø_‹mj´/¹ø«iáÿÑÍéUi) Ì-LpüÂò‹i´–fÇyk‹ñéãRZ`RùË¡¤=]éB›g°K»©·¼t1œå6Æáf³ùÀe5Ó°vfÖtÙ¬&Oókw»¸g6ª3Œõ¹wžöì×‚ª•ûð9æõ×¾#ƒùHô\,s.ÇKÛÚ]æ¶5Ó=(0ö8ÓË/’¦.Ë²_áÖW0w;¼ïnŸû‘×É1lI×Ççwïÿ¼&ºí¦RD]æê© ôóÜ~o8K`UàwüîŸÑüâÄ÷”„ åÿ¹c¼IÂb&žÍðVÝv…POðšcc³dÿ†FÄsB[¼…Û|l3ÚÆß>7f2ÏiD'-ñí‚¥SH‚ÂaÊüÜšÁq!ÓÌ¾,16S¦9I7)‰S®Ìºb”Kç §¯ŠÜ`œðõ†¶ÄgßxYˆ9YÝD.ò¦±Äé\ ÄPÚPó¹¾ˆ±Z—ØBþ†ñ/ä h¿/¾¬+ÀÎ_ ‚kPiÙ±¸7Ä+&ÓžÑ8×½äL÷N¤9—°Ò¼_Ö§–Y‹mÏ0õÙ¶¸1f‹*b7šÈ4ô»güS+x;Añíû(NÕQHy°’¥.ÞœºŒ(ADš|c0|cB!lëN‹,oÖ£‡½ööŸÂ¶Iþ'uÀƒ$a‘g±)sY„j9ñ  ™ê*RùJ FTÄB”Çbe{}šHŒ±>\¾±w,æ1]ëñà’C¢K˜Ã³ñ^¿&E¯3i_žkXYÏ‘þŽïD:Á?ö’0¿¸¿ìs<1#z(äÝ5«õïÅu1   °YŽVTz`„‘ÍþŠ)hê›uÉÿ_ÌÅ…ô´ÓÃÜÜÆæŽ5Æâ##î\4fí”©ÂDÀ!ªD7o0”E\Ð½MY™L>ÞiáísßgQŽGvÜ”~ö‹£†?<¦    lÀ'[gþßøûm/¾Ýýø×ôìXþöúUxö·íŸÅîéÉka„¸ƒJ  ÿÈx:Úx:zÀvI ›ZÚ\×™µY>ÜóLÄ-žˆ‡ÙMÊ?ÿ›Œÿ‰©r ³v¶!7|ªïKðdý/oþŽ¿;K

```

I also change the permissions of `index.php` but nothing works for me. Also my `index.php` works, when I write `die('test')` in index.php it displays "test" on the page. I think the problem is in these two lines of code in `index.php`,

```
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

```

If any one know how to fix this error, Please let me know I'll be very thankful to all of you. Thanks in Advance...

# Answer
> 3 votes
Every time I have encountered this problem, it has been because I have

* page level caching enabled on admin/config/development/performance
* page compression enabled on admin/config/development/performance
* output compression enabled in .htaccess or httpd.conf (eg, mod\_deflate)

The cause is that pages are being compressed twice on the server side, but only decompressed once on the client side. The solution is to disable page compression in Drupal.

You can add an override to your settings.php

```
$conf['page_compression'] = FALSE;

```

and alter the performance page

```
function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  $form['bandwidth_optimization']['page_compression']['#default_value'] = 0;
  $form['bandwidth_optimization']['page_compression']['#disabled'] = TRUE;
  $form['bandwidth_optimization']['page_compression']['#description'] = t('Handled by Apache.');
}

```

---
Tags: 7, ssl
---


# Question
Title: open a lightbox2 containing a flowplayer video from a menu link
Is it possible to make a link from a main menu to open a lightbox2 that will contain a flv video?

I have flowplayer installed but not swf tools

I thought of doing it with javascript but I'm sure there is another way

# Answer
> 1 votes
Add **rel="lightvideo"** tag, it will popup the video, It also have the option to set the size of the modal window, for more information see the readme.txt

```
<a href="#" rel="lightvideo">Google video example</a>

```

# Answer
> 0 votes
I think if you just add rel="lightbox" to the link that should do it?

# Answer
> 0 votes
As was said before add the lightvideo tag to any link with the rel attribute, you can add the size like this. rel="lightvideo\[width:600px; height:500px;\]"

Adding it to a standard drupal menu item is a bit more difficult as you need to narrow down which menu item you want to apply it to. You could add it to the menu item with jQuery though, something like this:

```
$('.menu li a').attr('rel', 'lightvideo[width:600px; height:500px;]');

```

You'll need to narrow it down to the exact menu item you want, that will apply it to all of them.

---
Tags: routes, files, javascript
---


# Question
Title: Display menu items of unpublished nodes to users without "Administer Content" permission
I have a content editor who is building out a section. All the nodes are yet unpublished. The problem is unpublished nodes are not displayed in a menu. While this is correct behavior with a user viewing a site, the editing experience is lacking in that way. How can I build a representation of a menu of unpublished items?

# Answer
I ended up using a module called Menu view unpublished which is a ...

> Small module that allows users to view menu links to unpublished nodes.
>
> The menu system from Drupal core hides menu links that link to nodes that are unpublished. This modules provides a permission that undoes this behavior, but only if the user has access to view the (unpublished) node.
> 2 votes

# Answer
If I recall correctly, by default the menu items are shown when the path is accessible. So if the menu item is enabled and point to an unpublished node, it won't be visible to anonymous users but should be visible to privileged users (with 'administer content' permission, for example).

Edit: view\_unpublished module may work in this case.
> 1 votes

# Answer
You could use Views to make a list of all unpublished nodes. That way it is easy for people to find pages they are working on.
> 0 votes

---
Tags: 7, routes
---


title: Where to use menu_link_save

text:
# Question
Title: Where to use menu_link_save
I want to create some menu items, i have code for it

```
   $item = array(
  'link_path' => 'guarantee/validto' ,
  'link_title' => "meeeeeeeeeeeeeeeeeeeeeeeeeeeeeenu",
  'plid' => 0,
  'hidden' => 1,
        'weight' => 0,
        'menu_name' => 'main-menu',
        'module' => 'guarantee',
   );
   menu_link_save($item);

```

But nowhere i can find where i should place this part of code. Can someone could suggest me where to place it to create manu items? I have my moudle enabled/installed and i need to create 10 menu items like above. What will be the best solution? is

# Answer
You don't need to put in the update function. It can go anywhere in your module just Remember to clear the cache after you update the module so you can see it.

If you're adding new menu items in a module update you should put:

```
cache_clear_all('*', 'cache_menu', TRUE);

```

In the mymodule\_update\_7000 function and it will clear the menu cache automatically when you update the module.

Additionally: You might be better using hook\_menu for the menu items in your module.

something like this:

```
function mymodule_menu() {
  $items['guarantee/validto'] = array(
    'title' => 'meeeeeeeeeeeeeeeeeeeeeeeeeeeeeenu',
    'type' => MENU_NORMAL_ITEM,
    'weight' => 0,
    'menu_name' => 'main-menu',
    'page callback'   => 'drupal_goto',
    'page arguments' => array('guarantee/validto'),
  );
  return $items;
}

```

It can go anywhere you like in your mymodule.module file but generally goes near the top. Again, you don't need to put in the update function but remember to clear the cache after.
> 2 votes

---
Tags: routes
---


# Question
Title: Ajax error and weird white space when connected
When connected in Drupal (the problem does NOT happen when logged out), I see a strange � character.

The character seem to break Ajax calls all over the admin (I get an alert, with code 200, and the result of the Ajax request). I get the error when editing views, adding some contents, etc. Anything that requires Ajax.

The character also appears on every pages of the website, but only if I'm logged in Drupal. Otherwise, it doesn't appear.

I figured, the problem can't be in a file, or it would happen when I'm logged out too ?

Is there some files that are only called when logged in ?

Thanks !

# Answer
> 1 votes
Finally found a solution so I'm going to post in case anyone has a similar problem.

First, I made sure I had no unnecessary PHP closing tag, just like Drupal recommands. I also checked for the character in the database, just in case.

I started commented the page\_top, page and page\_bottom of my html.tpl.php to see where the problem was.

Turns out, with nothing in the html.tpl.php, (and I mean NOTHING), I still had the character.

I created a random "test.php" with simply an empty and still had the problem. A similar "test.html" (HTML is the key here), it worked.

Someone had activated a "mod\_deflate" in the .htaccess and it seemed to have issues with my version of PHP.

So there it is, hopefully it can help someone.

Thanks !

# Answer
> 0 votes
Content on your Drupal site varies depending on the role of the user. Authenticated users have different menus and menu structures, different block might be displaying etc.

When Drupal renders the page conditional code outputs different html depending on whether the user is autheticated or not. You have most likely copied something from a word processor over into a theme file and now you are stuck with a character that is nor properly encode by the browser. Look at the surrounding html tags to this character to give you an idea about where it is generated. If it is surrounded by div tags with class of field, check which node this field belongs to, which block or region etc.

And you possibly have misformed html. Right click on your web page and inspect the source. Copy the whole lot and go look online for a HTML verifier to check your code for you, ie. HTML Validator

---
Tags: ajax
---


# Question
Title: the javascript for dragging and dropping not loading - drupal 7
for some reason when I add new modules the tabledrag.js is not loading. Tried taking the modules out, clearing cache several times. Aggregated js as well. Can anyone help.

# Answer
I solved this by installing http://www.drupal.org/project/speedy

it minifies core javascript files
> 0 votes

---
Tags: javascript
---


# Question
Title: search in node-with-comments plus in unpublished nodes
I need on my site a search. It should index the comments too, fulltext index is fine, they could be seen as part of body.

But as I use workbench with many steps, most nodes are unpublished. And I guess that ist not possible with builtin search.

So I checked search\_api and it works for all content and its fields but NOT the comments.

Any suggestions what I could try?

# Answer
I found the search\_api (plus search\_api\_db) sufficient. I use the search\_api\_views also FYI

in node index -\> fields I add at the bottom another relationship and Comment-\>body extra

AND of course in the filter: Do not check "exclude unpublished nodes".
> 0 votes

# Answer
You can use hook\_searchapi\_entity\_property\_info\_alter:

```
function mymodule_searchapi_entity_property_info_alter(&$info) {
    if (isset($info['node']['bundles'])) {
        // For each content type.
        foreach ($info['node']['bundles'] as $bundle_type => $bundle) {
                $info['node']['bundles'][$bundle_type]['properties']['comments'] = array(
                    'label' => 'node comments',
                    'description' => 'the comments of the node',
                    'type' => 'text', // or whatever you want here
                    'getter callback' => 'mymodule_searchapi_get_whatever', // name me whatever you want

                );
            }
        }
    }
}

```

and your callback

```
function mymodule_searchapi_get_whatever($entity, $options, $name, $entity_type, &$info) {
    // return the comments here, as you have everything in the function variables - i.e. use return.
}

```

Look at example implemntations of this hook and it should be enough to get your started.
> 1 votes

# Answer
Have you worked before https://drupal.org/project/views\_bulk\_operations module.. If not just try it. it provides to create custom filter based on various relation in a format of view where you can add all types of filter from admin/backend.

Just try it.
> 0 votes

---
Tags: search, comments
---


# Question
Title: How can I attach a line item field to a custom checkout pane?
How can I attach a line item field (as form element) to a custom checkout pane ?

I tried the following with `commerce_line_item_save($line_item);`

```
function MODULE_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {
  //...
  //1st TRY, which in my opinion should be the right API fn ?
  global $language;
  field_attach_form('commerce_order', $order, $pane_form, $form_state, $language->language, array('field_name' => 'field_paxsup'));

```

Which returns

> Fatal error: Cannot access empty property in field.attach.inc on line 208.

field.attach.inc on line 208 `$items = isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : array();`

Precision: the custom checkout pane is working great with a basic field as below

```
$pane_form['nickname'] = array(
 '#type' => 'textfield',
 //and so on...
);

```

# Answer
> 0 votes
Got the answer just after posting : so the correct one is

`field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode = NULL, $options = array())`

**First parameter**

`entity_type` is the entity type you want to attach, not the one you want to attach *to* (see why non native english speakers have problems sometimes... Duh !).

**Second parameter**

`entity` expects an object , not a string ! Don't do

`field_attach_form('commerce_line_item', 'my_line_item_type' ...`

but :

```
$line_item = new stdClass();
$line_item->type = 'line_item_liberte';

field_attach_form('commerce_line_item', $line_item, $pane_form, $form_state, $langcode, array('field_name' => 'field_paxsup'));

```

In checkout pane context, load the line item

```
function MODULE_pane_checkout_form($form, &$form_state, $checkout_pane, $order) {

  $line_item = commerce_line_item_load($order->commerce_line_items['und'][0]['line_item_id']);
  field_attach_form('commerce_line_item', $line_item, $pane_form, $form_state, $langcode, array('field_name' => 'field_paxsup'));
  //...

```

---
Tags: entities, commerce
---


# Question
Title: Sublimetext 2 does not recognize .module file as php file
I have seen a few posts suggesting how to customize SublimeText for better drupal development, although I did not see any mention of and not sure how SublimeText2 would recognize my custom module's .module as php file and show the various color highlighting for it.

Currently it just treats my .module file as an unknown file and does not show any color highlighting on it.

Thanks.

# Answer
When you have the .module file open, go to:

```
View -> Syntax -> Open all with current extension as

```

and select PHP. This will then default all .module files to use PHP syntax.
> 20 votes

---
Tags: 7
---


# Question
Title: Update Webform and not Add if there is an existing value in one of the fields
In Drupal 7, I have a field which stores Usernames of the user. If a submission is made by a user, it stores its username.

All I want is that if there's an existing submissions made by a user, and that user makes an entry in the form, the webform should update the previous entry rather than create a new one.

Any idea how it can be achieved?

Thanks.

# Answer
this would be heavy on resources since it needs to search all 'submissions', searching for the user. An alternative idea:

* use Rules to create a 'submission' at new user registration, setting the user as author.
* use Node Limit to limit each user to one of that type
* use Rules to check when trying to create a new 'submission' (url contains...) and redirect to the existing 'submission' page for that user
> 0 votes

---
Tags: forms, webforms
---


# Question
Title: How to hide share content option under profile type?
There is an option "Share Content" under every profile type. It is being displayed to all users apart from admin. I just want to hide it. I searched for it enabling Devel module but did not get anything belongs to the option. Please share your answer if anybody knows how to do it?

# Answer
Presumably this is a field, so under Profile2 you can change 'Manage Display' for all fields - set it hidden
> 0 votes

---
Tags: users
---


title: Slide show inside of Body Content

text:
# Question
Title: Slide show inside of Body Content
There are no shortages of options for slide shows in Drupal: views, modules, themes, etc. However, I need an option for ***inside the Body Field***. I'm dreaming of an option that

* Content editors can assemble without manually entering Javascript or CSS in the body or Code Per Node field
* Accessible to screen readers (Jaws, Voiceover, Orca) by having Aria roles and landmarks in place
* Is a module which, perhaps, employs an input filter.

Does such a solution exist? Is this a time to begin exploring Polymer more deeply?

In all my searches, I've seen blocks and views, but nothing that can be dropped into the Body Field.

# Answer
Well I'm liking the idea of just building a input filter module (on github).

PHP

```
function _MYMOD_process($text, $filter, $format, $langcode, $cache, $cache_id) {

  preg_match_all("/\[slideshow:(#[\S]+)\]/", $text, $matches);

  // If no match return and be done.
  if (! isset($matches[1])) {
    return $text;
  }

  // gather information
  $text_to_remove   = $matches[0];
  $elementid        = $matches[1];

  // remove filter trigger text
  $text = str_replace($text_to_remove, '', $text);

  // TODO: Inject javascript file
  drupal_add_js(drupal_get_path('module', 'MYMOD') . '/slider.js', 'file');

// TODO: Start process
drupal_add_js('jQuery(document).ready(function () { var s = new SlideShow("' + $elementid +' "); s.process(); });', 'inline');

  return $text;
}

```

JavaScript:

```
function SlideShow(parentContainerId) {

    this.BEGINNING  = 'Beginning';
    this.END        = 'End of list';
    this.FIRSTINDEX = 0;

    this.length     = jQuery(parentContainerId + ' img').length;
    this.container  = jQuery(parentContainerId);
    this.imgs       = jQuery(parentContainerId + ' img');
    this.index      = this.FIRSTINDEX;
    this.status     = 'beginning';           // beginning, end

    this.moveByIncrement = function(n) {

        // [in|de]crese
        this.index =  this.checkBounds(this.index + n);

        // return child
        return this.returnChild()
    }

   this.moveTo = function(n) {
        this.index = this.checkBounds(n);
        return this.returnChild();
    }

    this.returnChild = function() {
        return this.imgs.eq(this.index);
    }

    this.checkBounds = function(n) {
        // ensure index number is not beyond limits
        if (n < this.FIRSTINDEX) {
            n = this.FIRSTINDEX;
            this.status = this.BEGINNING;
        }
        if (n > this.length) {
            n = this.length;
            this.status = this.END;
        }

        return n;
    }

    this.process = function() {
        jQuery(this.imgs).hide();
        jQuery(this.returnChild()).show();
    }
}

```
> 0 votes

# Answer
that's a hard point that i'm also dealing with.

Actually i imagine 2 differents ways to solve this :

* i install the module paragraph It is pretty anwsome by changing the way a user contribute. But it doesn't allow to add a slideshow in a Body field.
* Creating a plugins for CKEditor that create (a new button) that will add the slideshow HTML in the Body Field. This button will be like "Create a table" button, you will decide how many images is needed and you will just add the to it. The HTML is quite simple, for bxSlider (http://bxslider.com/) for Exemple you will need to add this :

> ```
> <div>
>   <ul class="bxslider">
>     <li><img src="/images/pic1.jpg" /></li>
>     <li><img src="/images/pic2.jpg" /></li>
>     <li><img src="/images/pic3.jpg" /></li>
>     <li><img src="/images/pic4.jpg" /></li>
>   </ul>
> </div>
>
> ```

And for SlidesJS it's :

```
<div id="slides">
  <img src="http://placehold.it/940x528">
  <img src="http://placehold.it/940x528">
  <img src="http://placehold.it/940x528">
  <img src="http://placehold.it/940x528">
  <img src="http://placehold.it/940x528">
</div>

```

I didn't start this plugins yet because i finally decide to use Paragraph but i think this plugins for CKEditor can be a good tool in the futur.
> 1 votes

---
Tags: javascript
---


# Question
Title: Serve a different admin theme for a user role
I am making a news website. I want the administrator to have the default drupal 7 theme `Seven`. But I want to give the editor a custom theme that is more usable and streamlined for the task they do.

I have seen this module called ThemeKey. As far as I read it gives a lot of functions. For me as now only thing I want is when the user of the role editor login, they should be served with different admin theme. Thats all. Is there any hooks or something? Are there any examples or recommendations for achieving this?

# Answer
> 5 votes
I think that this module does exactly what you need, I used it on a project and works very well

Role theme switcher module

# Answer
> 2 votes
I like your question. However, I would follow a different approach. Rather than creating a whole new theme for editors, I would add a unique class into the `classarray[] = 'newclassuserrole';` { page preprocessor } in the body element via user role and then write all my css like this

```
body.newclassforuserrole region content .. and so on  {}

```

I would create extra variables and regions to be used on certain pages like \['node/%node/edit'\]\` etc

This way you can save extra php processing and can accomplish the theming part as well.

# Answer
> 0 votes
The Themes By Role module works for your purpose; I don't think RTS does what you want.

---
Tags: 7, users, theming
---


title: Use Redis for Drupal sessions

text:
# Question
Title: Use Redis for Drupal sessions
I've been looking online for a while and I haven't seen anything on setting up Drupal to use Redis for session handling. I've found tutorials and blogs about settings Redis up as a replacement for Memcached for caching.

Anyone know how to do this? I was hopping there was something in the $conf variable in the settings.php file that would allow me to override where sessions are stored and retrieved.

Thanks for any help in advance,
FatGuyLaughing

# Answer
> 4 votes
a quick google search: http://lmgtfy.com/?q=drupal+redis+sessions

and the 2nd result talks about redis session handling: https://www.drupal.org/node/2250195

from that issue thread i recommend looking Session Proxy. This allows you to override the default session handler by Drupal -- which is explained in the above issue:

> This is because Drupal will override your session handler and use its own, it goes straight to the database. I'd recomend that you try using this module: https://drupal.org/project/session\_proxy

Session Proxy provides the following, I believe your attempting #2:

> ships three different session managing implementations:
>
> 1. Database session handling: core default, ported to the object oriented API. It comes with an additional SQL query done more than core session.inc default implementation due to the API strong encapsulation.
> 2. Native PHP session handling: by selecting this session management mode, you explicitely remove any core session management, and let PHP manage it. This can be useful if you intend to use low-level PHP extensions, such as Memcache or PhpRedis to handle session in PHP low-level layer instead of core. This allow to use any PHP native session storage to work gracefully: some of them are high performance.
> 3. Cache based storage engine: Using the same session handling than core, but deporting raw session storage into a cache backend instance. You can use any already-functionning cache backend to store sessions. Sessions will use their own bin, and won't be cleared at cache clear all time.

Again from the linked issue after installing session proxy you likely need to configure your php.ini to something like:

```
session.save_handler = redis
session.save_path = "tcp://localhost:6379"

```

---
Tags: 7, sessions, database
---


title: Sub pages result in 404

text:
# Question
Title: Sub pages result in 404
I'm running Drupal 7, and I've cleared the cache through drush many times (drush cc all). I'm trying to access any subsequent pages beyond the front page and it results in a "Object not found error" error.

Does anyone have any idea? I feel like it's most likely an Apache or site configuration issue but I can't figure out what it is.

# Answer
Sounds like the problem is that clean URL's are enabled in Drupal but not supported by your Apache configuration (make sure that mod\_rewrite is enabled and the folder/vhost has AllowOverrides enabled) or the .htaccess file is missing.

You can verify that this is the problem by accessing the non-clean version of the URL. For example, instead of example.org/something, try example.org/?q=something.

See http://drupal.org/getting-started/clean-urls for more information.
> 5 votes

# Answer
Change the following line in the .htaccess worked for me,

```
RewriteRule ^ index.php [L]

```

so it would now be:

```
RewriteRule ^(.*)$ /index.php?q=$1 [L,QSA]

```
> 0 votes

---
Tags: 7
---


title: Views exposed form delta

text:
# Question
Title: Views exposed form delta
My question is ,I have a views named for sale and it is exposed with some fields . I have created other 2 instances of this view using override this feature of views now I want to alter all three views seperately , for this i have used form alter but I am not getting the seperate ids for delta nor the #id for those .how can i alter those delta .

# Answer
You can achieve this goal via implementing hook\_form\_alter

Let e.g.

```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page_1') {
       // do your alteration stuff
    }
    if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page_2') {
       // do your alteration stuff
    }
}

```
> 1 votes

---
Tags: views
---


# Question
Title: View contextual filters to work as needed
I have content type A with some vocabulary for it and content type B with same vocabulary. On the node page of type A I want to show block with some content of type B wich has any same terms as node page we're viewing. Is it possible?

Thank you!

# Answer
This is extremely easy using Panels as Panels is context aware. You can pass this context to the view, which displays the results based upon the contextual filter.

Look at http://nodeone.se/sv/node/702 and the next episode to get the hang of it.
> 1 votes

---
Tags: taxonomy-terms, views
---


title: Altering main menu in drupal 7

text:
# Question
Title: Altering main menu in drupal 7
I am new to drupal, and i am trying to alter the code generated by my main menu. I would like to replace this :

```
<span thmr="thmr_249"><ul id="main-menu" class="links inline clearfix">
<li class="menu-227 first active"><span thmr="thmr_250"><a href="/" title="" class="active">Link1</a></span></li>
<li class="menu-377"><span thmr="thmr_251"><a href="/link2" title="Au détail">link2</a></span></li>
</ul></span>

```

By this :

```
<a class="act" href="/"><em><em>Link1</em></em></a>
<a href="link2"><em><em>link2</em></em></a>

```

The code i have added on my page.tpl.php

```
print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix'))));

```

I have been looking around and found that it could be achieved by using theme\_menu\_link & theme\_item\_list in my templatye file....no success so far.

Can anyone show me the proper way to do it ? Thanks

# Answer
> 2 votes
It's a bit unusual request, but if you want to clear main menu from `ul` anl `li` tags and print just links, you can do that in this way:

**template.php**

```
/**
 * Main menu
 * Implements theme__menu_tree().
 */
function YOURTHEME_menu_tree__main_menu($variables) {
  return $variables['tree'];
}

/**
 * Main menu
 * Implements theme__menu_link().
 */
function YOURTHEME_menu_link__main_menu(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $element['#localized_options']['html'] = TRUE;
  $output = l('<em>' . $element['#title'] . '</em>', $element['#href'], $element['#localized_options']);
  return $output . $sub_menu . "\n";
}

```

go to `admin/structure/block` and place main menu in header region (or wherever you want)

**Result**

```
<a class="active" href="/some-path"><em>Link1</em></a>
<a href="/another-path"><em>link2</em></a>

```

# Answer
> 0 votes
The only way to change (alter) item in menu tree, including any dynamic values, before the item is rendered (not created or updated) is to use hook\_translated\_menu\_link\_alter(). This is the only hook that runs after item processing, but before item render. But, due to performance issues, it runs only on items that have $item\['options'\]\['alter'\] = TRUE. So to make it work, 'alter' should be set to TRUE programmatically.

This allows not only to work around standard menu access callbacks and implement your own ones, but also change values of menu $item\['href'\] or any other property.

```
/**
 * Implements hook_translated_menu_link_alter().
 */
function YOURMODULE_translated_menu_link_alter(&$item, $map) {
  if ($item['menu_name'] == 'your-menu') {
    if ($item['link_title'] == 'Awesome Menu Link') {
      $item['access'] = TRUE;
      $item['href'] = 'new/link/path';
    }
    else {
      $item['access'] = FALSE;
    }
  }
}

```

Full discussion: https://www.drupal.org/node/1897326#comment-9034011

---
Tags: routes
---


# Question
Title: The previous published revision should be available for the visitors while the current revision is in needs review state
I am using Workbench Moderation module for moderation on nodes. I notice that it creates revision of the nodes.

I have a node which is in live/publish state therefore it is available for the site visitors. Then when an editor edit that node, I programmatically put that node in needs review state and create a new revision for that node.

After that the site visitors are not able to access that node until its state change to publish.

I want that the new revision should be needs review state and the previous publish revision of the node should be available to site visitors.

The code which I am using for setting the state of the node is as following.

```
$node->status = 0;
$node->revision = 1;
node_save($node);
workbench_moderation_moderate($node, 'needs_review');

```

# Answer
I solved it.

Before the revisioning I loaded the original node first. Then first save the new revision and then save the original node.

My code now looks like this.

```
$original_node = node_load($nid);
$node = node_load($nid);
$node->revision = 1;
$node->workbench_moderation_state_new = 'needs_review';
node_save($node);
node_save($original_node);

```
> 0 votes

---
Tags: 7, workbench
---


# Question
Title: Show relationship summary using Entity Reference
First question, hope I can get some answers. I have this information schema:

**Books**: Title and Author (Entity Reference field to Books content type)

**Author**: Name and Books (Entity Reference field to Author content type)

I created a view to show the authors with their ID's. I want to also show in the Books field the ID's for the books that reference them. I already created the relationship and turned aggregation on and asigned it to the books field. The view looks like it's working and aggregation also seems to be working, however, no results are showing in the books field. Any ideas?

I'll appreciate any answer. Thanks!

# Answer
> 0 votes
First off, you only need an entity reference field on the content type *Books* that points to *Author* in your example. It would be a pain in the long run to manually maintain the two relationships and all data needed to describe your relationship is given in the *Book-\>Author* field.

Now let's create a View that lists books.

*(I've removed the second column in the screenshot from Views as no settings were done there)*

Add the entity reference relationship under *Relationships*. Add Content: title and use your relationship. Under Format and Settings, set group by to the *Content: Title* field you created in the step before.

Now all books are listed and grouped by their author.

In my example I also sort by the authors name. If you rather show the Nid of the content, just switch from *Content: Title* to *Content: Nid*.

---
Tags: views
---


title: Code for viewing comment reply form

text:
# Question
Title: Code for viewing comment reply form
I would like to add\_css when comment reply form is viewed (not new comment form) and there is an example code below. How could the line $comment-\>nid == $node-\>nid (presumed to be responsible for viewing comment reply form) be changed and adapted to a function?

```
function hook_??? (???) {
  if ($comment->nid == $node->nid) {
    drupal_add_css(drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE.css');
  }
}

```

# Answer
As stated in the comments it's a bit of a guess what you are trying to achieve. And my answer is also a guess but it was too long to add as a comment :)

The code below would go in to template.php in your theme. So if comments are listed on a node and it happens that the page you are at is the some node id as the comment add some css file.

```
function MYTHEME_preprocess_comment(&$variables) {
  $node = menu_get_object('node');
  if($node && $variables['elements']['#comment']->nid == $node->nid) {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . '/css/MY.css');
  }
}

```
> 1 votes

---
Tags: 7, hooks
---


title: Managing blocks in a responsive theme

text:
# Question
Title: Managing blocks in a responsive theme
I'm just starting a responsive theme based on Omega, concentrating on the mobile layout at first.

There are certain blocks that will probably be deemed too 'heavy' to include on the mobile layout, and other blocks that will need to be introduced specifically for that layout (watered-down menus, toned-down user-bar etc).

I could easily hide the unwanted blocks on the mobile layout with CSS, and include the mobile-specific blocks on the default layout and hide those (so they're only shown for mobile), but that seems like quite a backwards way of thinking about it. If the blocks aren't shown, the extra overhead they incur would really be unacceptable (especially considering the number of extra db queries that the content in hidden blocks would add).

I'm thinking there must be a nice clean way to intercept the block decision-making process early on in the page build, and exclude/include blocks based on some os-detection, but I'm drawing a blank on how that might be possible.

I'm also going to throw in the fact that Varnish is running in front of this site, which should make things more fun :)

Are there modules/known strategies out there that can help with this?

I should add that using the Context module isn't an option as the site is already fully-fledged, and moving it into Context would be a massive undertaking at this point.

# Answer
> 4 votes
> intercept the block decision-making process early on in the page build, and exclude/include blocks based on some os-detection
>
> Varnish is running in front of this site

As noted in the comments already, this requires you to configure varnish to *not* cache only on the request URL, but also vary on the user-agent. There is a relevant example in the varnish wiki, VCLExampleNormalizeUserAgent.

Once the request actually *does* hit the site, you need to determine which blocks to show and not to show. I would consider it no less than a disaster to do this with eval, so the most common options left then are Context and Panels.

With the site already built. redoing all pages/block placement with either module is probably not an option, but with a profiler, and applying 80-20, it could be possible to make significant performance gains by redoing specific pages only.

# Answer
> 10 votes
I can't go into a *lot* of details, as I've not used either module for ages (I build all my sites with Context from the word go and I've not picked up responsive on something I haven't built for a while, so I've not had this problem before), but I think you should be able to put something together with Mobile Tools and Spaces.

**Spaces**

> Spaces is an API module intended to make configuration options generally avaliable only at the sitewide level to be configurable and overridden by individual "spaces" on a Drupal site. It has been described as:
>
> * A way to make one Drupal site act like several sites
> * A way to provide much more configurable, full-feature Organic Groups or user homepages
> * A generalized API for contextual configuration

**Mobile Tools**

> The Mobile Tools module provides Drupal developers with some tools to assist in making adjustments to your site based on the visitor's device.

The project page for MT does say it's not ready for production though, which might be a problem - it depends when it was last updated, as the last commit was this month.

**\*EDIT**

I COMPLETELY FORGOT ABOUT THESE!

Browscap

> Browscap provides an improved version of PHP's get\_browser() function.

Browscap block

> Browscap Block adds visibility options to block configuration settings to allow you hide or show blocks in mobile devices.

Browscap does depend on your server setup, but if you can use it then the second module gives you extra visibility settings for each block on the block edit page.

# Answer
> 0 votes
you can use a jQuery cross browser support to get the screen resolution:

```
var browserWidth  = $(window).width();
var browserHeight = $(window).height();

```

Add simple PHP script to display setting of related block.

# Answer
> 0 votes
You could use Mobile Detect Block but I'm currently looking for a solution that works with window width and either *`AdaptiveTheme`* or Breakpoints module media queries so as not to duplicate that code and weigh down the end-user download any more than it is. I also had mixed results with Mobile Detect not picking up on one device I tested it with, which makes it rather useless like Browscap if it can't provide reliable results.

Some discussions have some people wanting to get away from Browscap for one reason or another, hence the move to Mobile Detect.

---
Tags: blocks, theming
---


title: media module - simple picture upload

text:
# Question
Title: media module - simple picture upload
Currently if using media module and users can upload pictures, they are presented with modal window where they can select a file for upload. On the same page there is a dropdown for selecting folder (taxonomy) and on second page there are fields for adding alt aln title text. Which is quite complicated for uploading one picture.
Question:Is there any way of simplifying the process? Setting default upload directory for users and not to be asked to fill alt title fields? Thank you.

# Answer
> 0 votes
You'll find the settings to skip field settings under

> admin/config/media/file-settings

---
Tags: 7, media
---


# Question
Title: drupal identify which content type is not used
I have a drupal existing project which is slow in performance and many irrelavent extra stuff. what aprroach is best where i can identify that which content type is used or not . Or we can say that which content type is used where

Similar for field/taxonomy that which field/taxonomy is associated with which content type.

# Answer
Just go to http://example.com/admin/content as user 1 and filter content by content type. If there is nothing, then content type is not used. Note that there may be views or modules that expect some content types to exist, even if you are not using them at the moment, so always make a backup before dropping them.

For fields, go to http://example.com/admin/reports/fields \- you will get a nice list what is used where.
> 3 votes

---
Tags: entities, taxonomy-terms, nodes
---


# Question
Title: redirect in hook_init makes body text disappear
What is wrong with this code. It makes my body text disappear in all of my nodes.

```
function MYMODULE_init() {
  if (arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
    $node = node_load(arg(1));
    if ($node->type = 'event') {
      if ($items = field_get_items('node', $node, 'field_event_date')) {
        $date = date_create($items[0]['value']);
        drupal_goto('news/events/day/' . date_format($date, 'Y-m-d'));
      }
    }
  }

```

I'm using the Calendar module. I don't want to display the full event node, I want to redirect to the Calendar's day display. The redirect works fine. Just when I go to view other nodes there is not body text. I also have Workbench moderation installed. On all of my non-workbench managed nodes I also get a workbench draft tab and errors related to workbench. It is not workbench related as I uninstalled workbench and body text is still not visible.

It seems to be related to node\_load, as all is well when I remove that area of code.

# Answer
Okay, got the answer. hook\_init() needs to document what functions are ok/not ok to call

Documention of hook\_init() should mention that it's not allowed to call ... node\_load() within this hook. The correct way to redirect is as follow:

```
MODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'MODULE_node_page_view';
}

MODULE_node_page_view($node) {
  if ($node->type == MODULE_NODE_TYPE) {
    $referenced_node = MODULE_get_related_node($node);
    drupal_goto('node/'. $referenced_node->nid);
  }
  else {
    return node_page_view($node);
  }
}

```
> 1 votes

---
Tags: nodes, hooks
---


title: Correct way to use hook_menu_alter

text:
# Question
Title: Correct way to use hook_menu_alter
What is the correct way of using hook\_menu\_later.

I did this in my module to redirect (see also redirect in hook\_init makes body text disappear):

```
function MYMODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'citykidz_node_page_view';
}

function MYMODULE_node_page_view($node) {
  if ($node->type == 'event') {
    if ($items = field_get_items('node', $node, 'field_event_date')) {
      $date = date_create($items[0]['value']);
      drupal_goto('news/events/day/' . date_format($date, 'Y-m-d'));
    }
  }
  else {
    return node_page_view($node);
  }
}

```

And this got me wondering: what if other modules are also overriding hook\_menu\_alter and setting their own page callbacks on 'node/%node'? Or even on access or whatever. This is the standard Drupal way of doing things, but surely it will lead to problems (that can be hard to detect). I see there is a module Chain Menu Access API that addresses this. Has anyone had success using this module? And has this issue been addressed in Drupal 8?

# Answer
If two modules are altering the same menu item / form / page etc, last one will "win".

If you need some control over this, and are expecting collisions, you need to implement `hook_module_implements_alter`:

> This hook is invoked during module\_implements(). A module may implement this hook in order to reorder the implementing modules, which are otherwise ordered by the module's system weight.

Do your best to have your hook fire last, and if menu item you are altering does not look like the one you are expecting (it was altered already), write a warning message to watchdog.
> 3 votes

---
Tags: 7, routes
---


# Question
Title: Export data to CSV programmatically in drupal 7
I am using the following code to extract all the users belonging to a group:

```
// Send response headers to the browser.
drupal_add_http_header('Content-Type', 'text/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment;filename=csvfiles.csv');

$output = '';
$keys = array(t('User id'), t('Username'), t('Email'));
if ($keys) {
  $output .= implode("\t", $keys) . "\n";
}
$members = _get_users_in_group($gid);
foreach ($members as $member) {
  $user = user_load($member->uid);
  $output .= $user->uid . ',' . $user->name . ',' . $user->mail . "\n";
}
print $output;
exit;
}

```

Even though I load all the users correctly the output I get is in Chinese. That means something is breaking the CSV format. Any ideas how to export data to CSV in Drupal 7?

# Answer
@potney i have updated your code.Please check

```
drupal_add_http_header('Content-Type', 'text/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachment;filename=csvfiles.csv');

$output = '';
$keys = array(t('User id'), t('Username'), t('Email'));
if ($keys) {
  $output .= implode("\t", $keys) . "\n";
}
$members = _get_users_in_group($gid);
foreach ($members as $member) {
  $user = user_load($member->uid);
  $output .= $user->uid . ',' . $user->name . ',' . $user->mail . "\n";
}
ob_clean();
print $output;
exit;
}

```

I have used this code it works for me

```
            $filename='filename.csv';
            ob_clean();
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment;filename='.$filename);
            header('Cache-Control: max-age=0');

        $contents="Date  \n ";
$contents.='11/05/2014';

echo $contents;

```

Please check this.Hope this will work
> 5 votes

---
Tags: organic-groups, importing-exporting
---


# Question
Title: How to automate setting up Services or RESTws?
It looks like xmlrpc.php is of almost no use. I want to use XML-RPC to control my sites but I don't want to set up Services or RESTws manually on dozens of sites. It doesn't look like Services has support for Features.

Is there a way to automate setting up Services or RESTws on many sites at once?

# Answer
The Services module doesn't have any Drush integration (Drush being the standard way of running code against multiple sites at once). So I would assume that nothing currently exists that does what you're looking for.

However, Services does use the ctools plugin API, so you can probably piggy-back off that to some degree. It will mean you need to code a Drush plugin yourself to manage the export/import, but you can probably get most of the boilerplate code from somewhere like the Drush CTools Export Bonus module.

Bottom line, I think it's unlikely you'll find a pre-existing solution for this, you'll probably have to get stuck in and make your own.
> 1 votes

---
Tags: 7, services
---


title: Find all entities of a given type?

text:
# Question
Title: Find all entities of a given type?
I am working on an admin interface for a module that uses a custom entity type. Is there a function or some way that I can use to find all entities of a given type, so that I can show users a list of them?

# Answer
> 7 votes
You're looking for the `EntityFieldQuery` class:

```
$query = new EntityFieldQuery;

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->fieldCondition('field_my_field', 'value', 'a_value')
  ->propertyCondition('status', 1)
  ->fieldOrderBy('field_my_field', 'value', 'DESC');

$results = $query->execute();
if (isset($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  foreach ($nodes as $nid => $node) {
    // Do something with the node object
  }
}

```

The above code loads all node entities with a content type of `article`. It filters on a custom field called `field_my_field` and the `status` property of the node. I only put that in for reference you wouldn't need it to load all nodes without any filters. Same goes for the order by statement.

Hope that helps.

# Answer
> 1 votes
You may also try the following simple two-liner:

```
$res = (new EntityFieldQuery)->entityCondition('entity_type', 'node')->execute();
$entities = entity_load('node', array_keys(reset($res)));

```

Or the following one-liner (PHP \>= 5.5), ready to use with `drush eval`:

```
print_r((new EntityFieldQuery)->entityCondition("entity_type", "node")->entityCondition("bundle", "page")->execute());

```

To remove them, please check: Can I delete nodes of a given content type with Drush?

---
Tags: 7, entities
---


title: Exposed Filter Alteration

text:
# Question
Title: Exposed Filter Alteration
I have a custom content type that has a date field. I have created a view with a exposed filter. The issue i have is that the exposed filter is in the form Y-M-D and i wan it to be just M-D. I have altered the exposed form, setup the #format to M-D and now the Y field is hidden. But it's still trying to validate it. and nothing shows up when you select values in the filter.

# Answer
> 0 votes
i have created a custom module.

```
function date_filter_form_alter(&$form, &$form_state, $form_id) {
  if($form['#id'] == 'views-exposed-form-birthdays-sliders-panel-pane-1') {
  $form['field_birthday_date_value']['value']['#date_format'] = 'm-d';
}
}

```

And query alter looks like:

```
function date_filter_views_query_alter(&$view, &$query) {
  if ($view->name == 'birthdays_sliders') {
    if (!empty($query->where[1]['conditions'][2]['field'])) {
    $query->where[1]['conditions'][2]['field'] = "DATE_FORMAT(field_data_field_birthday_date.field_birthday_date_value,
     '%m-%d') = :field_data_field_birthday_date_field_birthday_date_value";
}
  }
}

```

---
Tags: 7, views
---


title: linkd not displaying for anonymous user

text:
# Question
Title: linkd not displaying for anonymous user
I'm trying to make node/add URL appear on front of site to anonymous user and when clicked, it redirects to login or register page. drupal hides links automatically, any help please. I'm using drupal 7

# Answer
> 0 votes
You can do that by creating a block as follows

Go to `admin/structure/block` and add a new block as follows

set show block for anonymous user.

and set the Region where you want to display the link on Front page. and if you want to display the link only at front page. make the following settings

---
Tags: navigation
---


# Question
Title: How does #value_callback really work (nested elements, ...)?
**EDIT: Separated 4th question.**

I've just recently started working with custom elements and already came across some weird behavior / questions I'd like to see answered.

**1)** How does `#value_callback` work, what should you return in it, etc. ?

Imagine you have pretty simple custom element without set `#element_validate`:

```
function TST_element_process($element, &$form_statem, $form) {
  $element['testing_test'] = array(
    '#type' => 'textfield',
    '#default_value' => 'ABC',
  );

  return $element;
}
function TST_value_callback_1($element, $input = FALSE, &$form_state) {
  //example of input retrieving magic
  return ($input['testing_test'] . '_valc_');
}
function TST_value_callback_2($element, $input = FALSE, &$form_state) {
  //example of input retrieving magic
  return array($input['testing_test'] . '_valc_');
}

'TST' => array(
  '#input' => TRUE,
  '#tree' => TRUE,
  '#process' => array('TST_element_process'),
  //'#element_validate' => array('TST_element_validate'),
  '#value_callback' => 'TST_value_callback_1', // or TST_value_callback_2
),

```

And form:

```
$ar['inp'] = array('#type' => 'TST');

```

*1A)* When you use `TST_value_callback_1`, the callback gets called and runs but doesn't alter the result value in any way (in submit the `$form_state['values']['inp']['testing_test']` contains pure input -\> `ABC`).

*1B)* In case of `TST_value_callback_2` the `$form_state['values']['inp']['testing_test']` still contains unaltered input but there's also value in `$form_state['values']['inp'][0]` which contains the 'right' value (`ABC_valc_`).

My questions are:

**1.1** what exactly are you supposed to return in `#value_callback` and why do the individual callbacks work in the way they do (or don't do in case of the first one).

**1.2** is there any way how to make the `#value_callback` store the data in 'element root' (`$form_state['values']['inp']`), i.e. in the same place as if I used form\_set\_value in `#element_validate`?

---

**2)** How do individual `#value_callback` work on custom element that is made of other elements?

Let's say you have a custom element (`A`) that is made of a nested set of other elements with set `#value_callback`.

```
for($a = 0; $a < 10; $a++) {
  $element['indiv_elems'][] = array(
    '#type' => 'indiv_element',
  );
}

```

Then a number of things can appear in `$form_state[values][<element_name_in_FAPI_array>]` depending on how you approach `#value_callback` in the custom event (`A`) (and some of those things make little sense to me).

*2A)* When you don't use `#value_callback` in (`A`) at all, the `$form_state[values][<element_name_in_FAPI_array>]` will contain array of raw inputs (not processed by its `#value_callback` function) from each `phone_numbers` element.

*2B)* When you set `#value_callback` in (`A`) but let it return (let's say) empty array(), the `$form_state[values][<element_name_in_FAPI_array>]` will contain array of inputs from each `indiv_element` element processed by their (individual `#value_callback` function) .

My question is:

**2.1**) Why do the values not get processed by individual `#value_callback` when parent element's `#value_callback` is not set. Basically why is there difference between *2A)* and *2B)*.

---

**3)** Do I understand this flowchart correctly that `#value_callback` is called before `#element_validate`?

---

I'm also aware that it will be quite time consuming to answer this question, so many thanks and love ahead! :)

# Answer
> 2 votes
One thing i want to add before replying to your questions. Drupal core FAPI doesn't allow multiple `#value_callback`. It allow only one `#value_callback` per element type. Even You don't have to add `#value_callback` key in your `hook_element_info()` if your value callback follow the format `form_type_' . $element['#type'] . '_value'`.

```
// See code in include/form.inc from function _form_builder_handle_input_element line 2034

$value_callback = !empty($element['#value_callback']) ? $element['#value_callback'] : 'form_type_' . $element['#type'] . '_value';

```

***1)** How does `#value_callback` work, what should you return in it, etc. ?*

> value\_callback provides a way to process values before they are returned to the form submit function. You need to provide a `#value_callback` if you want to do fancy processing on the input. If you just want #value set to #default\_value, you don't need this hook at all, since that will happen anyway. This function is mainly useful if you need to do something non-standard with the value, like transpose an array into an option list.
>
> Value callbacks should consider three conditions:

1. Input is being provided directly. This happens when a form is submitted.
2. No input is provided, but the field definition has a default value.
3. No input is provided and there is no default value.

***1.1)** what exactly are you supposed to return in #value\_callback and why do the individual callbacks work in the way they do (or don't do in case of the first one).*

So value callback is supposed to check the `$input !== FALSE` and then modify the `$input` value as per your logic. If its false that means `$input` value is not provided in this case you can return the `$element['#defalut_value']`. So in your first value callback `TST_value_callback_1` if you want to make that work you have to return the value with the **same array key** something like.

```
function TST_value_callback_1($element, $input = FALSE, &$form_state) {
  //example of input retrieving magic
  $input['testing_test'] = $input['testing_test'] . '_valc_';
  return $input;
}

```

In your **second value callback** `TST_value_callback_2`  it was adding value to `$form_state['values']['inp'][0]` because you was returning an array with index 0 having the value `ABC_valc_` like `array(0 => 'ABC_valc_');`

```
// code from include/form.inc from function _form_builder_handle_input_element line 2109

// Set the element's value in $form_state['values'], but only, if its key
// does not exist yet (a #value_callback may have already populated it).
if (!drupal_array_nested_key_exists($form_state['values'], $element['#parents'])) {
  form_set_value($element, $element['#value'], $form_state);
}

```

***1.2** is there any way how to make the #value\_callback store the data in 'element root' ($form\_state\['values'\]\['inp'\]), i.e. in the same place as if I used form\_set\_value in #element\_validate?*

Setting the `#tree` to `false` in your form element should do the trick.

```
$ar['inp'] = array(
  '#type' => 'TST',
  '#tree' => FALSE,
  );

```

you will be able to get the value in `$form_state['values']['inp']` but in this case `#value_callback` will not do any affect, and `$input` in `#value_callback` is set to `NULL` i don't know why. So you better use the `($form_state['values']['inp']['testing_test'])`

***2.1)** Is there any way to enable 2.2 behavior without setting #value\_callback in ?*

***2.2)** Why are individual #value\_callback functions run (and their outputs are saved to $form\_state) only when parent (A) #value\_callback is run (even if it doesn't reference or call the individual functions in any way)?*

Hopefully my above explanation help you to understand the role of `#value_callback`. Even though custom element that is made of a nested set of other elements, are also elements so individual value callback will be called for each subelement. There is too much too explain Please take a look at \_form\_builder\_handle\_input\_element

***3)** Do I understand this flowchart correctly that #value\_callback is called before #element\_validate?*

yes `#value_callback` is called before the `#element_validate` callback. For more explanation See Creating Custom Elements

For practical example see examples module.

See also:

https://api.drupal.org/api/examples/form\_example%21form\_example\_elements.inc/function/form\_type\_form\_example\_checkbox\_value/7

https://api.drupal.org/api/examples/form\_example%21form\_example\_elements.inc/function/form\_example\_phonenumber\_combined\_value/7

# Answer
> 1 votes
2) The problem lied in the fact that individual `#value_callback`s get run after the (`A`)'s callback is run (the higher the element is, the sooner their callbacks get run (which is IMHO counter intuitive)).

Therefore, when the `#value_callback` of (`A`) is not set, default behavior happens which means that raw input from all individual sub-elements is set as element's value (in $form\_state) in the end of \_form\_builder\_handle\_input\_element.

And finally when individual `#value_callback` get run (and they get run) their outputs can't be stored in $form\_state\[values\] because of the fact that the place is already occupied by (above mentioned) individual elements' raw input.

```
  // Set the element's value in $form_state['values'], but only, if its key
  // does not exist yet (a #value_callback may have already populated it).
  if (!drupal_array_nested_key_exists($form_state['values'], $element['#parents'])) {
    form_set_value($element, $element['#value'], $form_state);
  }

```

---
Tags: 7, forms
---


# Question
Title: Is it safe to delete 'sites/modules.sav'?
After the upgrade to the newest Drupal v7.31 I've found a new directory called sites/modules.sav with some subdirectories like

* entity
* entityreference
* securelogin
* securepages
* session443

What is the purpose of this directory?

Can I safely delete this entire directory 'modules.sav' after the successful upgrade?

# Answer
Yes, as far as *Drupal* is concerned, it's safe to delete that folder. Whether it's needed for something outside of Drupal I obviously couldn't say.

Drupal didn't put it there, and unless you've got a very abnormal setup (which you'd undoubtedly know about already), it's not going to be looking in that folder for any files.

It's probably a remnant of whatever automated method you used to update Drupal; if you'd done the upgrade manually that folder wouldn't have appeared.

To be sure, take a full backup, remove the folder on a dev version of the site, and run the usual tests you would after a normal upgrade. If those all pass, you'll know 100%.
> 2 votes

---
Tags: 7, upgrading, backups
---


# Question
Title: Why isn't my integer value processed correctly with PHP in Rules?
My articles have a field collection field and one of the fields is an integer. Users can add as many fields as they want. I'd like to reward them some userpoints, equal to the total value in their saved fields, but with an overall maximum of 5.

*e.g. A user saves a first field with a value of 3. Therefore, he's awarded 3 points. When he saves another field with a value of 4 afterwards, he must be rewarded 5-3=2 points.*

I wrote a rule that sums all the old and new values in the integer fields via a loop (the results are saved as variables 'Old total' and 'New total') when a new field collection is saved. Before I can grant userpoints to the user, I have to do some calculations to prevent the total amount of earned points to be larger than 5. I tried doing that by adding the following PHP code in the 'Process value' box of a 'Grant points to user' action:

```
if (old-total > 5) {$value = 0;}
elseif (new-total > 5) {$value = 5 - old-total;}
else {$value = [field-collection-item:field-my-integer];}
return $value;

```

However, when the action runs, the code seems to be ignored, because the value doesn't change at all. I don't get any errors.

What did I do wrong? How can I solve this?

# Answer
> 0 votes
I was able to solve this problem after finding the answer on my question 'How to use variables in a PHP evaluation in a rule?'.

Instead of activating the Rule when an event "After saving a new field collection item" occured, rather use "After updating existing content" and grant the Userpoints for the first Field Collection item in a different Rule. Afterwards, follow the instructions in the referenced answer and use the code underneath.

```
<?php
if ($old_total > 5) {return 0;}
elseif ($new_total > 5) {return 5 - $old_total;}
elseif ($new_total == $old_total) {return 0;}
else {return $new_total;}
?>

```

---
Tags: 7, rules, tokens, entities
---


# Question
Title: How do I check the logged-in user username/password/role using a function to validate them?
I am allowing users to register an account on my site. They get a specific role using `user_save()`.

When they log in for the first time, I have to verify the login credentials.

Is there a function to verify the login credentials?
Is there a function to get the user roles?

# Answer
> 5 votes
To check login credentials in Drupal 6&7:

```
$uid = user_authenticate($username, $password);

```

In Drupal 8:

```
// Inject user.auth service..
$uid = $this->userAuth->authenticate($username, $password);
// or
$uid = \Drupal::service('user.auth')->authenticate($username, $password);

```

To check roles:

```
/**
 * Check User roles
 * @param $role
 * @param null $user
 * @return bool
 */
function user_has_role($roles, $user = NULL) {
  if ($user == NULL) {
    global $user;
  }
  if (!is_array($roles)) {
    $roles = array($roles);
  }
  if (count(array_intersect($roles, $user->roles))) {
    return TRUE;
  }
  return FALSE;
}

```

# Answer
> 0 votes
```
$username = 'Username';
$pass = 'Password';

$uid = user_authenticate($username, $pass);

user_login_submit(array(), $uid);
$load_user = user_load($uid);

if (in_array('role_name', $load_user->roles)) {
  // Add functionality that you want to do like if you want to redirect or anything else
}

```

---
Tags: authentication-authorization
---


title: Send a message when a comment is left

text:
# Question
Title: Send a message when a comment is left
I want to send a message to users that have commented on a node each time a new comment is left.

I think I am half way there.

I have created a component of the content type, added a loop that looks at the “node:comments” and set the email up using referenced mail list

I have also created a rule that triggers the component on the event of a new comment.

The problem I have is that I want to exclude the node author as they get notified anyway when a new comment is left in a separate rule.

Also, that if you have left more than 1 comment on the node you get more than 1 email so I need to filter it down.

I am fairly new so as much detail as possible would be appricatied.

Many thanks :-)

David

# Answer
> 1 votes
How about the modules -

Comment Notify

> Comment Notify is a lightweight tool to send notification e-mails to visitors about new, published comments on pages where they have commented. Comment Notify works for both registered and anonymous users.

or

Notify

> The notify module allows users to subscribe to periodic emails which include all new or revised content and/or comments of specific content types, much like the daily newsletters sent by some websites.

and see Email notification for new comments

# Answer
> 0 votes
The better method would be to use the Message stack of modules together with Message Digest, but that requires coding and as you are new it will be a daunting task (however, it will do exactly as your use case demands).

In your instance I will look at Conditional Rules through which you can easily combine complex logic into a single rule. Then also check out this post for good advice: How to build an Email Diggest using Rules

# Answer
> 0 votes
Add to @Geoff modules there is a similar module called Thank You Commenter

> As the name says, a small and simple module which send a mail to a person who comments on nodes. You can choose from logged in users only or for anonymous users as well.
>
> We also plan to add settings per content type based.

---
Tags: rules
---


# Question
Title: Redirecting a registration link in logintoboggan
I've got a register link and a log in link that is augmented by logintoboggan. All I want to do is redirect the register link from the user account form page to a new page I've just made. It seems very simple, but I can't find where the I can change the link. Any help would be amazing, thanks.

# Answer
Use a hook\_menu\_alter to alter the *user/register* path and add your own *page callback* to it.
> 0 votes

# Answer
You can also try the Redirect module. Here is a quote about it (from the module's project page):

> Work in progress for a Drupal 7 integration and collaboration between redirection-type modules:
>
> Current features:
>
> * Common API for loading, saving, and deleting redirects.
> * Case-insensitive redirect matching with a hook to allow other modules to narrow-down the candidate redirects.
> * Redirect counter and last used timestamp, with automatic cleanup of inactive redirects.
> * Integration with Drupal's page cache to optimize redirects and performance.
> * Complete individual redirect access API.
> * Views API integration.
> 0 votes

# Answer
Also you can do it in your template.php of active theme or custom module

```
 function YOURthemename_preprocess_page(&$vars) {
      // this will give you a good idea of the page content and variables
      if(arg(0)=='user' && arg(1)=='register'){
              drupal_goto('newregisterpath');
      }
        if((arg(0)=='user' && arg(1)=='login') || if(arg(0)=='user' && arg(1)=='')){
         drupal_goto('newloginpath');
       }
    }

```

And further you have modules like **Path\_redirect** etc already mentioned in the previous comments.

Hope it willhelp you!
> 0 votes

---
Tags: 7, users
---


# Question
Title: How to set If-Modified-Since HTTP header in my drupal site
I want to implement If-Modified-Since HTTP header in my drupal site. How do I ensure the If-Modified-Since HTTP header is supported and that it is active?. If it is supported but not active then how to make it active?

# Answer
As you can see in `drupal_serve_page_from_cache` function, Drupal knows and uses this headers. Exact quote is:

> If the request is conditional (using If-Modified-Since and If-None-Match), and the conditions match those currently in the cache, a 304 Not Modified response is sent.

How can you test? Obviously you can forge HTTP request in your user agent and see. Or you can believe in built-in tests.

Of course if you will not turn any cache on, there is no reason to react to If-Modified-Since, because you have no cached data to serve if content is **not** modified. Default cache is located under http://example.com/admin/config/development/performance, and you can use other cache modules and mechanisms, too. Then, it's up to them to react to cache-related headers properly.
> 2 votes

---
Tags: caching
---


# Question
Title: Automatic adding of the subject to the contact form
I have the block that is shown in every node of one content type. The block contains the link (the anchor tag) which leads to the page with contact form.

Is it possible to add subject automatically to the contact form depending on which page the user clicked on the link and came to contact form page? The subject would be the title of that page.

I use Webform module for the contact form.

# Answer
I have created a custom module, but the form\_alter can just as well be placed in the theme template file.

```
function MYMODULE_block_info() {
  $blocks['contact_at_webform_block'] = array(
    'info' => t('Contact Us'),
  );

  return $blocks;
}

function MYMODULE_block_view($delta = ''){
  $block = array();

  switch ($delta) {
    case 'contact_at_webform_block':
      if (user_access('access content')) {
        $block['subject'] = t('Contact Us');
        $block['content'] = l('Contact Us', 'contact', array('query' => array('subject' => drupal_get_title())));
      }
      break;
  }
  return $block;
}

function MYMODULE_form_alter( &$form, &$form_state,$form_id ){
  //dpm($form); dpm($form_id);
  if ($form_id == 'webform_client_form_5') {
    $qp = drupal_get_query_parameters();
    $subject = isset($qp['subject']) ? $qp['subject'] : '';
    $form['submitted']['subject']['#default_value'] = $subject;
  }
}

```

So the important part of the link in the block is to add the page title as a query parameter, so the href of the anchor will look like this contact?subject=PAGE\_TITLE. If you use a block from views or created from the block UI then make sure to output the link in similar fashion.

The form alter code picks up the query parameter and inserts it into the webform subject text field. You will have to adapt the code here as your form id and text field will be different. Install devel module, then uncomment the dpm statement that is relevant. First dpm the value of your $form\_id and replace mine (webform\_client\_form\_5) with yours. Then dpm $form and inspect $form\['submitted'\]. Look for your subject field.
> 0 votes

---
Tags: 7, webforms, tokens
---


# Question
Title: View with Page display won't show menu tab for an alias
I want to add a few views (members and challenges) to a specific content type called group. I don't want the views to display all on the same page, this is easily done with the block display type. But I want to have menu tabs at the page, this is also easily done (`/node/%/members`) if you only use one content type. But I'm using multiple content types what than also will have the Members tab.

Basically I'm asking how to manage the visibility of a menu tab.

---

This is what I tried so far for the view Group Members (User):

```
Path: /group/%/members
Menu: Tab: Members

```

nothing showed up..

---

This is what I tried so far for the view Group specific Challenges (Content):

```
Path: /node/%/challenges
Menu: Tab: Challenges

```

It showed up on every node.

# Answer
> 1 votes
Create your views as follows:

**Challenges -**

path: node/%/challenges

tab: menu tab with title Challenges

filter criteria: type = group

Contextual filter: nid, and in section WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED specify validation criteria: Validator Content, Content types group

**Members-**

path: node/%/members

tab: menu tab with title Members

filter criteria: you con't need any as you are displaying users (you have a view of users)

relationship: add a relationship to the node table such as: User: Content authored. This will bring in the related nodes.

Contextual filter: nid, in the section rlationships nodes must be selected. Specify validation criteria as Validator Content, Content types group

And these two tabs will now show up only for node type group. If you need it on other content types as well then adjust your views filter criteria and contextual filter validation as required.

---
Tags: views, path-aliases, routes
---


# Question
Title: How to programmatically set permissions for a custom content type created in a module?
I have a module which creates a node type as part of hook\_install. I want to be able to automatically set permission to authenticated users to create nodes.

I have tried the following code:

```
 /**
  * Implements hook_enable().
  */
function my_module_enable() {
  $permissions = array('create my_module_content_type content');
  user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, $permissions);
}

```

But I receive this error.

```
Notice: Undefined index: create my_module_content_type content in user_role_grant_permissions() (line 3111 of ...

```

If I delete the two lines of code, the module installs fine. And when I run those 2 lines of code in an "execute PHP" window after install, they work as desired.

I believe hook\_install should execute before hook\_enable so the content type should exist when hook\_enable is run. Are permissions defined later? Thoughts on how to handle this?

# Answer
> 4 votes
The problem is that the `user_permission_get_modules` function fails to get the permissions at the point of install (too early in the process, not all the caches have been reset). So you would have to copy the `user_role_grant_permissions` function to your new module, it should look something like this:

```
/**
 * Custom user_role_grant_permissions function
 * does the same thing as user_role_grant_permissions
 * but it can run at install time
 * @see user_role_grant_permissions
 * @param int $rid
 * @param array $permissions
 */
function _my_module_grant_permissions($rid, array $permissions = array()) {
    // this line doesn't work on install / enable hooks
    // $modules = user_permission_get_modules();
    // Grant new permissions for the role.
    foreach ($permissions as $module => $permission_list) {
    foreach ($permission_list as $name) {
        db_merge('role_permission')
        ->key(array(
            'rid' => $rid,
            'permission' => $name,
        ))
        ->fields(array(
            'module' => $module,
        ))
        ->execute();
    }
    }

    // Clear the user access cache.
    drupal_static_reset('user_access');
    drupal_static_reset('user_role_permissions');
}

```

This is slightly different than the `user_role_grant_permissions` module in that the permissions are keyed to the module, so you call it like this:

```
function my_module_enable(){
    $permissions = array(
        // module key
        'my_module' => array(
           // permissions in the module
           'do module things',
           'modify module things',
        ),
    );
    _my_module_grant_permissions(DRUPAL_AUTHENTICATED_RID, $permissions);
}

```

# Answer
> 0 votes
Not all functions are available in the install file.

You will need to look at the code user\_role\_grant\_permissions and probably copy the database statement into your hook\_enable, also remember to remove it in hook\_disable

---
Tags: users
---


# Question
Title: Install routinely failing after database authentication
I am having the worst time installing drupal 7 on Ubuntu 14.04 on an amazon aws ec2 instance and I don't know why. I've never had this much trouble before. No matter how closely to a T I follow these instructions: https://www.digitalocean.com/community/tutorials/how-to-install-drupal-on-a-virtual-server-running-ubuntu-12-04 (i really can't imagine 12.04 being that different from 14.04, i'm not doing anything fancy) it always results in the following failure:

So I get the LAMP stack installed and set up and verify it's working correctly. And I create the database and the database user and verify that that's all working. And I download and move all the files to `/var/www/html` and start the install. Everything goes fine until I hit the database connection stage. I put in the credentials, it thinks, then the database connection page refreshes and the fields are empty. At this point I go and I check the database and there are 31 tables created by Drupal, so it is connecting and modifying the database.

So what else can I do but restart the install, and when I do it jumps to the site information page, so I add that information, save it and I get the following error:

`Fatal error: Call to undefined function field_attach_load() in /var/www/html/includes/entity.inc on line 321` (which would otherwise be a WSOD, but at least I have development debug turned on)

If I just go to the site now, the default drupal page comes up but only with: `Page not found
The requested page "/" could not be found.`

It's really throwing me here, I've Googled the error and the results are just so all over the place and I have no idea why I can't even get this thing installed before something goes wrong. This is not my first time installing a drupal site, have done it many times before on ubuntu servers from amazon aws and non-virtual servers.

# Answer
> 1 votes
Guess there are a ton of answers here for the exact same problem: https://www.drupal.org/node/1171756.

Don't really want to duplicate them.

**update:** In my case I needed to `chown -R www-data` the directory my drupal files were in, apparently ownership was somehow changed from the apache server, had to change it back. there you have it.

---
Tags: 7, installation
---


# Question
Title: views_embed_view use to append new HTML from view
Using drupal 7, I have a view that created an aggregated table like this:

Animals 44

Plants 25

I want that when user clicks on 'Plants', on the same view, without refreshing, the list of the 25 plants (coming from another view) comes out, appending the HTML to the Plants div.

I think that views\_embed\_view might be the solution. I am on the right track? how do I specify on which DIV the generated view should be appended to?

thanks

# Answer
You are on the wrong path.

Install the Views Megarow Module. Then create another view that will list the respective Animals and Plants together. Set the path as well, in this example I will assume a path of

megaitems/%

Note the argument.

Then add a contextual filter of 'Content: Type'. When the filter value is not in the URL, display content of no results found. Verify that it works by typing the content type (animal or plant, ie the machine name of your content) in the preview contextual filters section at the bottom. It should only show the nodes for the specific content type that you type in.

Back to the original view, select the Format as Megarow table. Add a field 'content type', and set its display to hidden. Move this field so that it is the first field in the list. Then add a field Megarow links. In the megarow settings, there is a section 'Links'. Add this:

View|megaitems/\[type\]

This will now create a link which when you click on it loads your content using AJAX. You might have to adjust your view slightly as you are using aggregation.

Good luck!

I have just created this view with aggregation active and views megarow does not play nice with it. But all is not lost. Install Views Field View also. Then create a new view wherein you embed a field of a view. This field must then use the view of your aggregation and append as an argument that is passes the node type again. Then in you original aggregated view you have a contextual filter by type and you do your aggregation as normal. This aggregated view will then return your aggregation result per content type to the new view, and in the new view you add your megarow field.
> 0 votes

---
Tags: views
---


# Question
Title: Remove XMLRPC to avoid vulnerability exploit
How is `xmlrpc.php` from Drupal core affecting functionality?

Given the fact that a vulnerability was discovered for it, details in this article

* is it safe to remove `xmlrpc.php` file?
* Is it bad practice? If so, why?
* Is there any way to neutralize this security risk without removing this file?

# Answer
> 6 votes
> is it safe to remove xmlrpc.php file?

Yes, if you're not expecting anyone to use it.

> Is it bad practice? If so, why?

Could be construed as such; any change to core creates an additional step when updating (I'm sure we're all aware of the dangers of 'hacking core' by now, but if not: Never Hack Core).

> Is there any way to neutralize this security risk without removing this file?

Update your core to 7.31, where the vulnerability has been fixed.

---
Tags: security
---


# Question
Title: how to distingush multiple ajax submit in single ajax callback
I trying to do add more functionality for adding video urls which I am able to do by using Ajax callback.I am referring a drupal examples for it.It has one remove one button which removes last created text field from form. **But I want a remove button for each text-field to remove it.**

I am creating textfields and remove button in form hook like

```
for ($i=0; $i < $form_state['num_names']; $i++) {
        $form['names_fieldset'][$i]['title'][$i] = array(
            '#type' => 'textfield',
            '#title' => t('Video Title'),
            '#default_value' => $webinar_videos[$i]->title,
        );
        $form['names_fieldset'][$i]['url'][$i] = array(
            '#type' => 'textfield',
            '#title' => t('Video Url'),
            '#default_value' => $webinar_videos[$i]->video_url,
        );
        $form['names_fieldset'][$i]['remove'][$i] = array(
            '#type' => 'submit',
            '#value' => t('Remove'),
            '#submit' => array('webinar_add_more_remove_one'),
            '#validate' =>false,
            '#ajax' => array(
                'callback' => 'webinar_add_more_callback',
                'wrapper' => 'names-fieldset-wrapper',
            ),
        );
}

```

Now a 'webinar\_add\_more\_remove\_one' submit callback is like

```
function webinar_add_more_remove_one($form, &$form_state) {

    if ($form_state['num_names'] > 1) {
        $form_state['num_names']--;
    }
    $form_state['rebuild'] = TRUE;
}

```

and 'webinar\_add\_more\_callback' this callback returns a wrapper element like

```
function webinar_add_more_callback($form, $form_state) {
    return $form['names_fieldset'];
}

```

My question is **How I can pass a video id to particular remove submit button so that I can delete particular video in 'webinar\_add\_more\_remove\_one' callback?**

Thank you in advance

Any help appreciated.

# Answer
> 2 votes
Last time I had to do this I used this method:

When creating the form create an array to hold deleted ids:

```
$form_state['deleted_items'] = array();

```

And give each remove button an ID relating to that items index:

```
$form['names_fieldset'][$i]['remove'][$i] = array(
    '#type' => 'submit',
    '#value' => t('Remove'),
    '#submit' => array('webinar_add_more_remove_one'),
    '#validate' =>false,
    '#ajax' => array(
        'callback' => 'webinar_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
    ),
    '#attributes' => array(
        'id' => 'item-'.$i,
    ),
);

```

Then in webinar\_add\_more\_remove\_one check the id of the button that was pressed:

```
function webinar_add_more_remove_one($form, &$form_state) {
    $form_state['deleted_items'][] = str_replace('item-', '', $form_state['clicked_button']['#attributes']['id']);
    $form_state['rebuild'] = TRUE;
}

```

And then when building the form check the array of deleted items:

```
for ($i=0; $i < $form_state['num_names']; $i++) {

    if(in_array($i, $form_state['deleted_items']) continue;

    // rest of code....
}

```

You will also need to check the deleted item array in the submit and validate functions as we don't actually removed the deleted item from the $form\_state array.

# Answer
> 0 votes
Noticed one missing bracket in this line: if(in\_array($i, $form\_state\['deleted\_items'\]) continue;

there is a missing ) before continue;

it should be : if(in\_array($i, $form\_state\['deleted\_items'\])) continue;

---
Tags: 7, ajax
---


title: How to execute jQuery on body elements?

text:
# Question
Title: How to execute jQuery on body elements?
I'm screwing around with jQuery for the first time, and I'm unsure of where to add a call in Drupal to allow it to alter classes of elements within the body tag.

I'm looking at utilizing something like the following:

```
$('header').toggleClass('Scrolling', $(document).scrollTop() > 0);

```

Without any custom modules at this point, the only robust method I have available seems to be using my custom theme. I've included a script in my custom theme's .info file:

```
scripts[] = scripts/mine.js

```

Within that file I've added a test script:

```
(function($) {
  var e = document.getElementsByTagName("body");
  alert(e.length);
  for (var i = 0; i < e.length; i++) {
    alert(e[i]);
  }
})(jQuery);

```

The result is an empty array. When I change "body" to "html", "head" or "script", I get an array populated with HTML objects. This leads me to believe that because the script is included in the header of the HTML page, it doesn't have access to body elements, as they haven't been loaded yet.

What am I missing that would allow this type of script to interact with body elements, and therein let me add a class to an element via my first line of code?

# Answer
If your question is "**How do I add theme javascript to the footer instead of the header?**", I have this snippet in my starter theme's template.php file:

```
/**
 * Add a custom, theme-specific JS file. Added here so it can be placed in the
 * footer instead of the header which is where the info file places JS.
 */
$options = array(
  'type' => 'file',
  'scope' => 'footer',
);
drupal_add_js(drupal_get_path('theme', 'bootstrap_starter') . '/js/theme.js', $options);

```

Change `bootstrap_starter` to the name of your theme and make sure the folder `js` contains a file named `theme.js` within your theme folder.

See `drupal_add_js()` for more info.
> 0 votes

---
Tags: javascript, theming
---


# Question
Title: Promoted to frontpage teasers in a block
**General:**

I am new with Drupal; so, I was trying to add new regions to Zen (sub)template, but got very confused why contents of my new-created region "content 2" appears on page **above** the original so called "promoted to front page teasers", which I considered to be a "content"...

Now, it seems "promoted teasers" are not in a block - and that's why they are not in a "content region"?

If so, How to put "promoted teasers" in a block?

Also confusing - what do "main page content" block? - It seems I cannot disable it and if I put "main page content" in a "content" region - my new "content 2" region appears above the "promoted teasers" ; if I put this "main page content" block in "content 2" - both content of "content 2" and "promoted teasers" appear next each other in the same row (?!)....

May be it depends somehow on CSS also?

I don't know, I just somehow assumed that "promoted teasers" are "content" region's content, but it's not - so, what should I do with it now?

**Ingredients used**:

Drupal 7.30

Zen 7.x.5.x

Display Suite

Views

few others...

```
<div id="main">

    <div id="content" class="column" role="main">
      <?php print render($page['highlighted']); ?>
      <?php print $breadcrumb; ?>
      <a id="main-content"></a>
      <?php print render($title_prefix); ?>
      <?php if ($title): ?>
        <h1 class="page__title title" id="page-title"><?php print $title; ?></h1>
      <?php endif; ?>
      <?php print render($title_suffix); ?>
      <?php print $messages; ?>
      <?php print render($tabs); ?>
      <?php print render($page['help']); ?>
      <?php if ($action_links): ?>
        <ul class="action-links"><?php print render($action_links); ?></ul>
      <?php endif; ?>
      <?php print render($page['content']); ?>
      <?php print $feed_icons; ?>

    <?php
    // content - 2 region , my own added
      print render($page['content2']); ?>
     <?php print render($page['content3']); ?>
     <?php print render($page['content4']); ?>
     <?php print render($page['content5']); ?>
      </div>

```

# Answer
> 2 votes
Use Views:

* Create view of content
* Create "Block" display
* Use filters to only show ones with "promoted to frontpage" selected
* In Format section set Show: Content | Teaser
* Put your block on the frontpage

That's all.

# Answer
> 0 votes
What I finally found and did:

In page.tpl.php

```
<?php if ($title): ?>
        <h1 class="page__title title" id="page-title"><?php //print $title; ?></h1>

```

---\> Commented out the Headline/ page title **//print $title**

Next: the lines:

```
<?php print render($page['content']); ?>

```

I changed to :

```
<?php
      if (!drupal_is_front_page()){
  print render($page['content']);} ?>

```

// Before I found this I also unchecked "promoted" , but I think anyway, this removes all that default staff; and also I added earlier several additional 'content 2n' regions, so I don't mind missing that on front page.

---
Tags: blocks, theming
---


# Question
Title: Drupal 7 Click tracking / traffic per node
I'd like to track the number of times a node shows up in search results, the number of times it's clicked on in a search result, and the number of times it is displayed. I'd like all of this information to be readily available - perhaps stored in the content type? I could use some help determining the best practice here.

Alternatively. Could I use google analytics to track all of this somehow such that I could access the results from a custom designed module (which, can anyone point me in a direction on?)

Ultimately I want uses to look at a node and be able to see how much traffic came from in-site linking, off-site linking, and how many times users followed a link from the node to an external website.

Can I export google analytic data for each node somehow to drupal?

# Answer
The google\_analytics\_reports module is a starting point for you to look at. I don't think it will cover all your requirements.
> 1 votes

# Answer
you can do all this by:

1. using google analytics module (it covers basic tracking, tracking clicks in external links, file downloads, you can also use it to pass tokens into custom variables)
2. you should add javascript to your node type of choice to add events when clicking in internal links

actually, at the moment, best approach would be to go with Google Tag Manager, where you can enable click tracking in all elements and pick in GTM, which one should be tracked.

take a look at following modules:

https://www.drupal.org/project/google\_tag

https://www.drupal.org/project/datalayer

First one installs GTM on your page, second one enables passing many variables and taxonomies to be passed to dataLayer. It also has an alter function, if you'd like to add some extra data (since the module is written in a general way and i.e. extracting taxonomies from json arrays on the GTM side can be complicated).

WARNING! keep in mind, that GA has a limit of events sent during one session, and for one user per day. First one is 500, second one AFAIK is around 200k. It might look that it's more than enough, but if you plan to track no of displays for many elements, you'd use up all your "event credits" right a way - another caveat is, that after the page load, you have a credit of 10-12 events, and each second it adds 2 tokens - it's an DDoS mechanism implemented on server side in GA.

So... what you're describing is more of a adserver mechanism where you want to measure click through rate (CTR) of your "promotional banners" - even if it's a node teaser, if you want to measure CTR, you should think about it as a banner.

Another way to measure it (clicks only) is to add a suffix to node link, which would later on allow on identifying where click came from, but you can also do this with standard reports on a page level, where you can check navigation summary for each page - it won't be as precise to tell you that specific teaser was clicked, but you'll know previous page.
> 0 votes

---
Tags: 7
---


title: Override theme for date field output?

text:
# Question
Title: Override theme for date field output?
I have a field that accepts a date range using the Date module. This is the theme function for outputting the date (found in `sites/all/modules/contrib/date/date.theme`):

```
/**
 * Returns HTML for a date element formatted as a range.
 */
function theme_date_display_range($variables) {
  $date1 = $variables['date1'];
  $date2 = $variables['date2'];
  $timezone = $variables['timezone'];
  $attributes_start = $variables['attributes_start'];
  $attributes_end = $variables['attributes_end'];

  // Wrap the result with the attributes.
  return t('!start-date to !end-date', array(
    '!start-date' => '<span class="date-display-start"' . drupal_attributes($attributes_start) . '>' . $date1 . '</span>',
    '!end-date' => '<span class="date-display-end"' . drupal_attributes($attributes_end) . '>' . $date2 . $timezone . '</span>',
  ));
}

```

I somehow need to override that and replace the 'to' in the return with a hyphen... I know, it's nitpicky but it underlines a more important point - I honestly have no way to alter this. I've tried overriding it in my `template.php` but that doesn't take. I literally just copy and pasted this code but replaced `theme` in the function with the actual name for my theme.

So yeah... how do I alter this theme function "the Drupal way"?

# Answer
> 3 votes
With the help of hook\_theme\_registry\_alter you can override(actually by passing) any theme function.

Usually module's will define their theme functions in hook\_theme(), however using hook\_theme\_registry\_alter you can alter those information.

For your case below code will achieve the desired functionality,

```
/**
 * Implements hook_theme_registry_alter().
 */
function <my_module>_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['date_display_range'])) {
    $theme_registry['date_display_range']['function'] = 'theme_custom_date_display_range';
  }
}

/**
 * Returns HTML for a date element formatted as a range.
 */
function theme_custom_date_display_range($variables) {
  $date1 = $variables['date1'];
  $date2 = $variables['date2'];
  $timezone = $variables['timezone'];
  $attributes_start = $variables['attributes_start'];
  $attributes_end = $variables['attributes_end'];

  // Wrap the result with the attributes.
  return t('!start-date - !end-date', array(
    '!start-date' => '<span class="date-display-start"' . drupal_attributes($attributes_start) . '>' . $date1 . '</span>',
    '!end-date' => '<span class="date-display-end"' . drupal_attributes($attributes_end) . '>' . $date2 . $timezone . '</span>',
  ));
}

```

So whenever you call **theme('date\_display\_range', $variables)**, **theme\_custom\_date\_display\_range()** function will be invoked instead of **theme\_date\_display\_range()**.

Don't forget to clear the caches after adding hook\_theme\_registry\_alter

# Answer
> 0 votes
If all you want is to change "to" to "-", then hook\_theme\_alter is overkill.

You can simply use the translation layer:

At least 2 options:

1. in settings.php:

$conf\['locale\_custom\_strings\_en'\]\[''\] = array('!start-date to !end-date' =\> '!start-date - !end-date');
2. use stringoverrides module, which provides a GUI for same.

---
Tags: 7, theming
---


# Question
Title: Bootstrap Theme: Theme hook suggestion for user profiles
I've tried to create theme hook suggestions in my template.php to use template files in combination with view modes. My code snippet:

```
function blogtheme_preprocess_user_profile(&$vars) {
 if ($vars['elements']['#view_mode'] == 'blog_user_preview') {
  $vars['theme_hook_suggestions'][] = 'user__blog_user_preview';
 }
 if ($vars['elements']['#view_mode'] == 'blog_user_full') {
  $vars['theme_hook_suggestions'][] = 'user__blog_user_full';
 }
}

```

But it doesn't work – he standard user-profile.tpl.php is always being used for these two view modes. I activated the zen theme to test the function and it worked smoothly. After reading the comments in the bootstrap base theme I've found the following comment in the registry.inc:

> // Due to how theme() functions, if a base hook implements // preprocess or process functions, then the base hook info is // used to invoke the necessary phase functions instead of the // suggestion hook info. To get around this, a helper function // must be appended to the base hook info so it can call the // theme suggestion implementation's phase function.

```
$function = '_bootstrap_' . $phase . '_theme_suggestion';
 if (!in_array($function, $registry[$base_hook][$phase_key])) {
 $registry[$base_hook][$phase_key][] = $function;
}

```

Could somebody help me by explaining this function? How can I get it to work?

# Answer
> 0 votes
The code in your first snippet looks correct to me. I would try the following:

1. Remove the `if` statements temporarily and get rid of the second option. It's possible that neither of them are returning true.
2. Theme functions are cached. Make sure you have cleared the cache before testing.
3. Double check that your custom template is named `user--blog_user_preview.tpl.php`.

---
Tags: theming, hooks
---