title: Structure for a list of links

text:
# Question
Title: Structure for a list of links
What I’m looking to do:

* Content type has an field (addable; unlimited entries to this field)
* In that field you select from a list of (mostly external) links.
* Each link is a sentence - has a title and pre/post text.

So a piece of content displays a number of formatted links, and these links can be pulled into a view elsewhere.

How could I build that list of links? (content type, field group, taxonomy with link as the name, haven't been able to figure out something that works)

# Answer
> 0 votes
One working solution:

# Answer
> 0 votes
Use a taxonomy, separate content type to store rich links. Use entity reference to embed those links in your content and view modes to format the display.

If you want to customize the display further without templates you can use panels.

You can also take a look at https://www.drupal.org/project/panopoly\_widgets

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


# Question
Title: How can I conditionally display something in Views header area depending on the argument in URL?
The URL of my page view looks like my-view/%1/%2 The first argument %1 is term id of either vocabulary A or B or C and all of them are hierarchical taxonomy.

How can I conditionally display something in Views header global text area depending on which vocabulary %1 is or if it's parent term or child term?

# Answer
> 3 votes
I don't know if it's standard practice to answer such an old post, but another solution may be helpful to those who don't want to do any coding. You can conditionally attach a header by using Views `Attachments`. This may not be the best practice for a production site, but that's another discussion. This answer is just to let you know of the possibilities.

Add an Attachment display for each Vocabulary you want a separate header for, and set their properties according to the images below. Notice that all attachment properties are overridden, in order to not affect your main Page or Master (default) display.

Edit: The images displayed below are for Views 3.x. Hopefully, they are helpful for Views 2.x, as well.

> **Add Attachment:**

Add an attachment for each header you want displayed conditionally (as shown above).

> **Attachment Filter:**
>
> ---

The above filter will ensure no records are displayed by the attachment, only the header.

> **Contextual Filter (1/2):**
>
> ---

Set the contextual filter for each attachment (as shown above and below).

> **Contextual Filter (2/2):**
>
> ---

Set the term to be used for this attachment (my example is "Glossary"). Be sure `Action to take if filter value does not validate` is set to 'hide', so that only the desired header is displayed.

> **Attach To Page:**
>
> ---

Be sure to attach your attachment to something (here, attached to the "Page" display). Click on `Global: Text Area` to set your header.

> **Set Global: Text Area (in Attachment Header):**
>
> ---

Click `Global: Text Area` (prev image) and set your desired header. Notice: still overridden. Also be sure to check `Display even if view has no result` since the filter for the attachment excludes all records.

> **Page/default Contextual Filter:**
>
> ---

Last, but not least, set the Contextual Filter for the main page itself (not an attachment) according to your needs.

# Answer
> 2 votes
I would suggest to use the panels module: there you can create a page that contains the view and add optional content based on available contexts.

# Answer
> 1 votes
1. add an essentially blank global header text area to the view.
2. use `hook_views_pre_render()` for the view to inspect the url arguments and insert the necessary content into the global header.
3. profit.

# Answer
> 0 votes
You have done half of the thing. If there is too much code then, I guess the best option is to write a function inside a module, call the function in Global Text Area and pass the arguments.

# Answer
> 0 votes
I'd add the Views PHP module, the add the header as a PHP header.

From there I would user the argument from the URL for my conditional.

Ex: if your path is my-view/%1/%2 and your condition is based on %1 you'd do

```
if (arg(1) == 'foo'): print 'this'; else: print 'that'; endif;

```

if your path is my-view/%1/%2 and your condition is based on %2 you'd do

```
if (arg(2) == 'foo'): print 'this'; else: print 'that'; endif;

```

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


# Question
Title: How to use standard Drupal 7 farbtastic component? jQuery error
So, this is my code:

```
  drupal_add_library('system', 'farbtastic');

```

I've added it to a page callback function (also tried putting in an implementation of `hook_page_alter()`). It doesn't seem to initialize properly, it fails on the first line of the system library farbtastic,

> Uncaught TypeError: Cannot read property 'farbtastic' of undefined

Has anyone had this issue before? Any ideas? I get the sense I'm doing something wrong because farbtastic is part of Drupal core now...

# Answer
> 1 votes
The Drupal core's farbtastic works differently. You will have to attach it to a an element eg: a form widget. Eg:

colour\_mod.module

```
$form['colour1'] = array(
    '#type' => 'fieldset',
    '#title' => t('Enter Colour:'),
    '#tree' => TRUE,
    '#description' => '<div id="color_picker"></div>',
    '#attached' => array(
        'library' => array(
            array('system', 'farbtastic'),
        ),
        'js' => array(drupal_get_path('module', 'colour_mod') . '/colour_mod.js'),
    ),

);

```

colour\_mod.js:

```
(function ($) {
  Drupal.behaviors.colour1 = {
    attach: function(context) {
                var farb = $.farbtastic("#color_picker");
   }
  }
})(jQuery);

```

# Answer
> 0 votes
I've encountered the same "Cannot read property 'farbtastic' of undefined" error and the root cause is that the color picker is not still ready/loaded when the farbtastic's markups need to be injected to that element. My solution is to enclose the farbtastic code to ajaxComplete() event:

your\_module.module

```
$form['marker_color'] = array('#type' => 'textfield',
  '#title' => t('Marker Color'),
  '#default_value' => '#18d',
  '#size' => 7,
  '#attached' => array(
    'library' => array(
      array('system', 'farbtastic'),
    ),
    'js' => array(drupal_get_path('module', 'your_module') . '/js/custom.js'),
    ),
  '#attributes' => array('id' => 'color-picker-target-textfield'),
  '#suffix' => '<div id="color-picker-container"></div>',
);

```

js/custom.js

```
(function ($) {
  Drupal.behaviors.custom_farbtastic = {
    attach : function(context, settings) {
      // Wait the HEX input field to be rendered completely to prevent
      // referencing errors. Pass the context information to speed up
      // DOM traversal/searching.
      $('#color-picker-target-textfield', context).ajaxComplete(function() {
        // Prevent multiple processing.
        $('#color-picker-target-textfield', context).once('color-picker-target-processed', function() {
          // Create a farbtastic colorpicker in the given DIV container.
          var colorPicker = $.farbtastic('color-picker-container');

          // Retrieve the target text field that contains the HEX color strings.
          var colorPickerTarget = $('#color-picker-target-textfield');

          // Make the color picker auto-update the contents of the HEX text field.
          colorPicker.linkTo(colorPickerTarget);
        });
      });
    },
  }
};
})(jQuery);

```

---
Tags: 7
---


# Question
Title: Entity references from a view with list of nodes that can be references to nodes that keeps references
I have a package (node with few entity reference fields - one per content type). Example

So on package node I can select nodes that are related (one reference per content type).

Now I have new request: create a view with a list of all products and on each row (product) make possible to select package this product belongs to - for example: set ref\_to\_shirt if product in this row is a shirt.

Note that reference field is on package and there are multiple reference fields (one per content type).

List will look something like this:

Any sugestion? I was wondering if its possible to set this as VBO action with some Rules component, but for now I'm open to any solution.

Thanks

# Answer
Edit: this approach is only for listing the assignments, not changing them.

--

First make sure that the product content types have a common view mode. Pick "teaser" for example.

Create two views:

* Products list: the "outer view" to list all the t-shirts, pants shoes.
* Packages per product: based on a contextual filter, list all package assignments of a given product. As you have different fields link the product content types with the packages you might want to start with one type. Once it works, replicate the view/view display for the other product types.

The second view now needs to be embedded into the teaser view of products. My preferred way of doing so is using panelizer to override the teaser view mode but you can also do this using the "Eva" module.

Hope this helps :)
> 0 votes

---
Tags: nodes, rules, views, entities
---


# Question
Title: Multiple currencies in commerce kickstart
How to make different prices for one product.I want to display product price in both currency that is euro/$ without any currency selector.

# Answer
> 0 votes
Commerce Multicurrency may help you, see this screencast form Commerce Guys.

---
Tags: commerce
---


# Question
Title: How to show thumbnail images on product pages using ubercart module?
I recently installed a test of Drupal/Ubercart on one of my test servers. I added a test product and uploaded 3 pictures for the product. My problem is that the 3 pictures are displayed in Full Size on every page that the product is listed. How do I enable thumbnails for these product images? I am quite sure that I have all modules that are required installed, but I see no place to enable thumbnails on product pages.

# Answer
> 1 votes
Firstly go to *\[your-domain\]/admin/config/media/image-styles* and create image style you want to use for your product images, than go to *\[your-domain\]/admin/structure/types* and click on 'manage display' on the right (for content type that you are using for products).

You will find your image field whose format is probably 'Image' and you will see a little gear on the right, click on it and for 'Image style' choose image style that you created previously (as mentioned above).

That's it. Now the images will be shown according to image style that you created.

For the list of the product I recommend that you use Views module and again to control your display image size by choosing image style for image field in Views.

---
Tags: 7, media, ubercart
---


title: Function in views tpl

text:
# Question
Title: Function in views tpl
How can I add a function in my custom views .tpl page or where can I write my function and call that function in my views .tpl ?

# Answer
> 1 votes
You can write the function in any php file that gets loaded. PHP is not sequential in loading/processing files, it will load them first then process.

# Answer
> 1 votes
For the sake of any future developer, including yourself, you should try to keep your custom functions inside your template.php file or in a module that you've created.

that is where people will expect to find functions used in templates and such.

# Answer
> 0 votes
Data transformation or processing should go in the preprocess function for that template. That way the template stays neat and only focused on presentation. In the preprocess function you can alter, remove, or add new variables as you please. These variables will then be available in the associated template. As user5482 mentions, it should go in either your theme's template.php, or in a custom module. If you are only altering or removing a variable, then your template.php will suffice. If you are creating new variables with data not readily available it should probably go into a new module and an earlier hook in the pipeline.

Make sure to document your new variable in the template as that is the first place where themers will look for information about it.

---
Tags: views
---


title: Referenced node as menu item

text:
# Question
Title: Referenced node as menu item
is it possible to create a menu item that links to the node that references the current user? I can create a more or less suitable solution with views: a page that contains the referenced node but it'd be more user friendly if the menu link contained the URL of this node.

# Answer
> 1 votes
Try Menu token

> Menu Token module provides tokens, that could be used in title or in path of menu items (links). For example, if you create a menu item with path: "user/\[current-user:uid\]", the url will be changed "on fly" to: "user/1" (assuming you are user 1).
>
> Tokens are provided by Token module. Menu Token allows to use both global tokens and entity ones: node, user, term, etc. Entity tokens have several methods of substitution: from context, random and user defined.

If that does not work, you will have to do a custom redirect, either in code or using page manager (part of ctools)

---
Tags: 7, routes, users
---


title: Modifying a single menu link title

text:
# Question
Title: Modifying a single menu link title
I'd like to replace the link title on the top link of my secondary navbar (called "explorer", links to "mysite.net/explorer", but actually just triggers a dropdown-menu) with a glyphicon and the current user's name.

According to this thread, a title callback is the way to do this. However, adding this code in my template.php has no effect at all.

```
function mythemename_menu_alter(&$items) {
  $items['explorer']['title callback'] = 'mythemename_title_callback';
}

function mythemename_title_callback($arg1, $arg2) {
  global $user;
  $title = '<span class="glyphicon glyphicon-user" aria-hidden="true"></span>'. $user->name;

  return $title;
}

```

What am i doing wrong? And why does the callback function take 2 parameters? (It doesn't work with 1 or 0 params.)

The "menu token" module almost crashed my site after installation, so I don't want to use that.

# Answer
> 0 votes
If you only want to change the title of an menu item, you should be able to do this through the administration. Go to `admin/structure/menu` and edit the correct item in your secondary menu.

To use `hook_menu_alter()` you must add it in a custom module not inside your template file. Remember to clear you cache in order for the changes to take effect. To clear the cache you can goto `admin/config/development/performance`.

# Answer
> 0 votes
One way is to use `theme_menu_link()`. Use `debug()` or Devel's `dpm()` to browse through `$variables` in order to get a grip on how the array is structured. Then locate the particular menu link in your code and theme it to your requirements. In the API documentation there are plenty of examples in the comment area that may suit your needs.

---
Tags: routes, navigation
---


# Question
Title: Load more content with ajax when clicking more link in a view
I have a custom block view. I display the last 5 node titles. If someone clicks the more link I want to load the next 5 titles underneath the current 5 node titles. No page refresh and not pager. Is this possible? How would I go about doing this?

# Answer
> 29 votes
So this is one of those problems that multiple people in the drupal world have tried to solve.

I recently gave a presentation on this exact same issue and how to accomplish it with drupal. Sadly I never posted any of my slides up anywhere where the rest of the world can see.

Here's the Break down of modules:

Views Infinite Scroll

* Does Not work with Views Ajax support -- It hacks around it to make is own ajax request
* Makes a full page request -- This is because it doesn't use the Views Ajax request
* Requires Views 3.x -- This is a plus, because the pager is plug-able in 3.x

Views Infinite Pager

* Support Views 2.x -- This is really not a good thing, because the pager isn't plug-able
* Because it works with 2.x it really hacks around the pager theme, the regular views ajax, and preprocessing behavior. So it breaks some functionality.

And last but not least is a new project in which I just added in light of this question. The reason for the project is my need for also needing views that support load more except the issues mention above we're not acceptable for my project.

Views load More

* Requires Views 3.x - This is on purpose.
* Support views regular pager options, such as offsets, page count
* Fully supports views ajax feature
    + If Ajax is enabled on the view, the load more will add content to the bottom of the list
    + If ajax is disable the page will refresh and replace the old content with the new content
    + It does not do a full page request when doing the ajax callback, it lets views do is natural callback and instead of replacing the content it appends to it.
* If you're using the waypoint module the view can be configured to automatically get new content when the user scrolls to the bottom of the page.
* Supports JQuery effects (right now only the fade effect is supported, more soon to come).

Hope this answers your question. This is my "unbiased" ;-) opinion on all the views load more module.

# Answer
> 2 votes
Another method using https://github.com/paulirish/infinite-scroll in Drupal is Transform any Drupal pager into an autopager - infinite scroll pager - load more pager.

> ### Step 1
>
> Download jquery.infinitescroll.min.js from https://github.com/paulirish/infinite-scroll and put it in /sites/all/themes/YOURTHEME/js/jquery.infinitescroll.min.js.
>
> ### Step 2
>
> Add the JavaScript file to the .info file of your theme.
>
> ### Step 3
>
> Make a custom JavaScript file /sites/all/themes/YOURTHEME/js/YOURTHEME.js containing the following code.
>
> ```
> /**
>  * Implementation of autopager @see https://github.com/paulirish/infinite-scroll
>  * All views that have the "autopager" class will have an autopager
>  */
> Drupal.behaviors.viewsInfiniteScroll = function(context) {
>   $(function(){
>     var $container = $('div.autopager div.view-content');
>     $container.imagesLoaded( function(){
>       $container.infinitescroll({
>         navSelector  : 'div.autopager .pager',    // selector for the paged navigation
>         nextSelector : 'div.autopager .pager-next a',  // selector for the NEXT link (to page 2)
>         itemSelector : 'div.autopager .views-row',     // selector for all items you'll retrieve
>         loading: {
>           finishedMsg: 'No more pages to load.',
>           img: '/sites/all/themes/YOURTHEME/images/loading.gif'
>         }
>       })
>     })
>   });
> }
>
> ```
>
> ### Step 4
>
> Add the CSS of the infinite scroll loader
>
> ```
> #infscr-loading {
>   position: fixed;
>   text-align: center;
>   bottom: 300px;
>   left: 42%;
>   z-index: 100;
>   background: white;
>   background: hsla( 0, 0%, 100%, 0.9 );
>   padding: 20px;
>   color: #222;
>   font-size: 15px;
>   font-weight: bold;
>   -webkit-border-radius: 10px;
>   -moz-border-radius: 10px;
>   border-radius: 10px;
> }
>
> ```
>
> ### Step 5
>
> Make sure jquery version is newer than 1.7.1. Use one of the methods described in http://drupal.org/node/1058168 for installing a newer version of jQuery in Drupal.

# Answer
> 1 votes
I cannot add a comment on the first answer. But you should add the new module : https://www.drupal.org/project/gd\_infinite\_scroll This module let your transform any content and pager to an infinite scroll or a load more pager.

From the page of the module:

> Provide an administration to use the infinite scroll jQuery plugin : auto-pager on custom pages using pager. You can use autoload on scroll or a load more button.

---
Tags: views, 6, ajax
---


# Question
Title: How do I know if a user has access to a private file in the node template
I have a a content type with Title, Body, File (private), and Taxonomy. I want all users to be able to see the Title, Body and Taxonomy for marketing purposes, but they should only be able to download the file if they are an authenticated and their account is related to the same taxonomy term(s) the node is related to.

I have private files set up properly and have written a custom module implementing hook\_file\_download\_access to check if the user should have access. If I go directly to the file URL, access is working as I think it should.

My problem is I'd like node page to say:

* "Register Now" if the user is not logged in
* "Contact Customer Support" if they are logged in but don't share the proper taxonomies
* or "Download Now" if all checks out.

Just not sure how to get it done?

# Answer
If your using the Pages Module then you can make different page 'variants' for different roles.
> 0 votes

---
Tags: users, files
---


# Question
Title: why does the overlaying content in the admin mode not show up anymore?
Okay, my Drupal admin interface used to work just fine until I introduced some `jQuery` and `CSS` changes this morning for the mobile adaptive interface. Now, When I'm in admin mode and for example click on the drop down to `Configure block` on my page, the page grays out but the white overlay interface to change the contents never shows up. I tried with `Chrome`, `Chromium` & `Firefox` which all yield the same result. The URL of my site is http://www.quaaoutlodge.com/ and if you resize the width `<900px` you'll see the little nav button poppintg up on to left - that's what I have changed... what did I mess up?

# Answer
Sounds like there is a JavaScript error in your nmost recent changes which is stalling some other scripts.

To get your admin interface back temporarily disable the Overlay module (core). http://www.quaaoutlodge.com/admin/modules

Then use the browsers developer console to find out where the JavaScript error is. If you've used the jQuery Update module you might need to set a different version of jquery for the Admin pages which is in the config page too. http://quaaoutlodge.com/admin/config/development/performance
> 1 votes

---
Tags: javascript, theming, modal-dialogs
---


# Question
Title: Drupal SEO module - Error on the setup wizrad and on dblog
I am using all Drupal SEO module , and all recommended module with it. I do not see any states on the Drupal SEO module reports.

When I am trying to run the setup on admin-\>config-\>search-\>seo tools-\> "+Setup wizard", I get the following error:

> Strict warning: Only variables should be passed by reference in seotools\_admin\_setup() (line 16 of xx/MYusername/public\_html/sites/all/modules/seotools/seotools.setup.inc).

In addition, in the dblog, I get many errors after trying to use Drupal SEO:

> TYPE google analytics reports
> DATE Wednesday, March 26, 2014 - 18:07
> USER Admin Admin-family
> LOCATION http://www.MySite.com/admin/reports/intel/content?return\_type=json&refresh=1
> REFERRER http://www.MySite.com/admin/reports/intel/content
> MESSAGE Code: 401 - Error: Unauthorized - Message: GDatarequiredAuthorizationLogin Required
> SEVERITY error

Drupal SEO looks like amazing module. Can you help me make it work? how can I solve this issues the problem?

# Answer
Hopefully this helps the next user.

I was having this issue and stepping through your code I noticed it sends a time stamp. Our server time was off by 12 minutes. Once I corrected it everything worked.
> 0 votes

---
Tags: google-analytics
---


title: View modes are stuck on default view

text:
# Question
Title: View modes are stuck on default view
I had my site for quite some time and just started to use the display suite view modes feature for changing the displays per node. I made new view modes and tried to change them for my nodes, but it seems that its just stuck on "default" view mode which is the full content view. I currently on display suite 7.1.x and updated to the latest as of Jan-2015 and it still does the same thing. Any hints would be great.

# Answer
> 0 votes
This seems to be an ongoing issue as there are reports of other modules conflicting with the display suite view modes feature. For some it had to do with Panels as seen here:

https://www.drupal.org/node/1919452

> Posted by drupalstrap on February 17, 2013 at 5:57am Greetings,
>
> The only view mode i am able to use is the default view mode. As long as I am using the default view mode, I can switch layouts without any problem. If I try to switch to another view mode, it still uses the settings of the default view mode. I have tried every way of troubleshooting that I can think of including changing themes, altering CSS files and tpl.php files etc in order to try to isolate the problem. Furthermore, i am not able to apply wrapper or class styles via the UI settings. They don't appear in the source code.
>
> Anyway, I have been battling this for two days now and figured I would see if anybody out there has any suggestions. On the server side, I am using php 5.3 with apc. I have tried clearing cache hundreds of times as well as restarting the server to see if there was something in memory that was stuck. I have also tried other browsers so it is something related to my development environment I guess. LAMP??? Please help. Thanks.
>
> Upload new files Comments billsdesk’s picture Comment #1billsdesk commented 2 years ago I am having the same problem. I created a view mode and set it as the view mode to use when I edited the page. Yet, the Full Content mode is always used, and not the specified view mode. The Manage Display tab always opens the correct view mode. I turned on the view mode switcher, and it correctly identifies that the page opened in the full content mode. However, it does allow switching to the correct mode. I checked the permissions, and all is good. No error messages. I am using Drupal 7.22, and Display Suite 7-2.3. report spam on user billsdesk alunyov’s picture Comment #2alunyov commented about a year ago Hello, I had same problem. In my case switching off panel for node view helped to solve the issue. I think it is something related with page manager. If you check settings page: admin/structure/ds/list/extras -\> Other -\> "View mode per node" option, in description you will find "Change view modes for individual nodes. A new tab 'Display settings' will appear on the content create form. You can also pass the name of a view mode through the URL, eg node/x?v=full. If you install the Page manager module and override the node view, Page manager will win."
>
> Added: check \_ds\_extras\_menu\_alter() in ds\_extras.registry.inc. it explains a lot report spam on user alunyov aspilicious’s picture Comment #3aspilicious commented about a year ago Status: Active » Closed (works as designed) Closing this works as designed. If you still have this issue and you DON'T have page manager enabled please reopen this one. report spam on user aspilicious Geijutsuka’s picture Comment #4Geijutsuka commented about a year ago I'm having this problem on a new site I've been developing... The strange thing is that it's only happened within the last couple weeks. Something triggered this behavior, but I'm not sure what yet (trying to figure out STR).
>
> I set up a brand-new sandbox site with everything up-to-date and it seems to work as designed... flawless. I also don't have Page Manager or Panels installed, and I definitely don't want to have to resort to changing the view mode for every single piece of content. I'm going to update the problematic site (ds is up to date, but there are a lot of other updates) and see if that fixes it... if not, I'll be back.

In my case it wasn't panels that was causing the issue but it was due to the "revisioning" module that cause the view mode to get stuck on default. There has also been reports here:

https://www.drupal.org/node/2304917#comment-9550067

I updated to the latest revisioning v7.1.9 and it still causes issues with the view mode. The only option is to turn this off if revisioning is really not necessary.

---
Tags: 7, display-suite, entities
---


# Question
Title: Could the filter order make a difference?
I have a view which has several filters, some of them exposed. I've noticed that the order of these filters seems to affect how they work. For example, I have a Boolean field, and if I check it's either zero or null.

With `((field_data_field_hide_on_closer_cornwall.field_hide_on_closer_cornwall_value = '0') OR (field_data_field_hide_on_closer_cornwall.field_hide_on_closer_cornwall_value IS NULL)` I get just two results returned, but `((field_data_field_hide_on_closer_cornwall.field_hide_on_closer_cornwall_value IS NULL) OR (field_data_field_hide_on_closer_cornwall.field_hide_on_closer_cornwall_value = '0')))`, as expected, shows all my nodes apart from one record where that Boolean field is set to 1.

I also notice that on an exposed Taxonomy filter with four taxonomy items, the first three filters return the expected list of results, but the last checkbox says there are no nodes in that taxonomy, even though there ARE nodes in that taxonomy.

I am using Better Exposed Filters to create the checkboxes with Views 3 and Drupal 7.

Here's my entire mysql for the view, including the exposed filter on Taxonomy item 27 which mysteriously returns no results, when a filter on 29 or 28 returns the expected list.

I tried making a separate view with only one filter on the Category Taxonomy, and that returned my Taxonomy 27 nodes correctly.

Could filter order make a difference? If so, how can I identify what the order should I use?

```
SELECT user_badges_badges.bid AS user_badges_badges_bid, user_badges_badges.name AS user_badges_badges_name, user_badges_badges.image AS user_badges_badges_image, user_badges_badges.href AS user_badges_badges_href, user_badges_badges.weight AS user_badges_badges_weight, node.nid AS nid, node.title AS node_title, 'node' AS field_data_field_photos_node_entity_type, 'node' AS field_data_field_sleeps_node_entity_type, 'node' AS field_data_field_phone_number_node_entity_type, 'node' AS field_data_field_searchdescription_node_entity_type, 'node' AS field_data_field_accommodation_tags_node_entity_type, 'node' AS field_data_field_category_node_entity_type, 'node' AS field_data_field_region_node_entity_type, 'node' AS field_data_field_place_on_map_node_entity_type, 'node' AS field_data_body_node_entity_type, RAND(1422056994) AS _random_seed
FROM
{node} node
LEFT JOIN {field_data_field_category} field_data_field_category ON node.nid = field_data_field_category.entity_id AND (field_data_field_category.entity_type = 'node' AND field_data_field_category.deleted = '0')
INNER JOIN {taxonomy_term_data} taxonomy_term_data_field_data_field_category ON field_data_field_category.field_category_tid = taxonomy_term_data_field_data_field_category.tid
LEFT JOIN {field_data_field_category} field_data_field_category2 ON node.nid = field_data_field_category2.entity_id AND field_data_field_category2.field_category_tid != '27'
LEFT JOIN {field_data_field_hide_on_closer_cornwall} field_data_field_hide_on_closer_cornwall ON node.nid = field_data_field_hide_on_closer_cornwall.entity_id AND (field_data_field_hide_on_closer_cornwall.entity_type = 'node' AND field_data_field_hide_on_closer_cornwall.deleted = '0')
LEFT JOIN {user_badges_user} user_badges_user ON node.uid = user_badges_user.uid
LEFT JOIN {user_badges_badges} user_badges_badges ON user_badges_user.bid = user_badges_badges.bid
WHERE (( (node.type IN  ('bronze', 'accommodation')) AND (node.status = '1') AND (field_data_field_category.field_category_tid IN  ('157', '31', '28', '29', '27')) )AND( (field_data_field_category2.field_category_tid = '27') )AND( (field_data_field_hide_on_closer_cornwall.field_hide_on_closer_cornwall_value IS NULL ) OR (field_data_field_hide_on_closer_cornwall.field_hide_on_closer_cornwall_value = '0') ))
ORDER BY user_badges_badges_weight ASC, _random_seed ASC
LIMIT 25 OFFSET 0

```

I have a number of filters there, but I can't see why putting the boolean field '='0' last in the WHERE statement works, whereas putting '=NULL' last causes the last filter to be ignored.

I'm filtering on category twice: once, an unexposed filter, to show only records that are in my four desired categories, and then another exposed filter again on category to allow the user to filter futher to just one or two categories. I wonder if this is causing a problem but if it is, I am stumped as to why this works for category 28, but not for the apparently identical category 27.

I tried removing the exposed category filter, re-ordering the categories in the taxonomy, then re-adding the filter, so that the last item in the field\_data\_field\_category.field\_category\_tid array became category 28. Sure enough, my filter is now able to find nodes filtered to category 27, but can no longer find nodes in category 28. I tried changing the form to not autosubmit, and to use links instead of checkboxes to select a category, but the same behaviour (last taxonomy term in query is dropped) persisted.

It appears that the last option in a filter is being dropped? Still can't see why.

# Answer
> 0 votes
This issue - the results displayed by a view changing depending on the order of the filters - appears to be down to my having created two filters on the same taxonomy field - an unexposed field, and an exposed field. I removed the unexposed filter.

Instead of filtering twice on the same field, I created a new text field on the relevant content types. I created a Rule to copy the name of my Category field in to the new field Before Saving node.

I hid the new text field with Field Permissions module. Finally I created a Views Bulk Operations view to allow me to re-save all my existing nodes in one go, populating the new text field.

I now have one field I can use in an unexposed filter to create my initial view, and a different but similar field that I can use to provide an exposed filter.

This works, so I'm leaving it here as an answer, but it seems quite convoluted and messy, so I'm not accepting it as the ideal answer in the hope that someone may volunteer a better solution to the problem of needing to filter twice without running into weird filter order problems.

---
Tags: views
---


# Question
Title: Is it possible to use a replacement kernel without hacking core?
I'd like to use a replacement `DrupalKernel`.

It looks like the default is hardcoded into index.php, despite the existence of `DrupalKernelInterface`:

```
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');

```

I suspect the answer has to be no, but I thought I'd ask anyway: is it possible to use a custom kernel class without hacking index.php?

# Answer
> 2 votes
Some of the classes that implement `DrupalKernelInterface` are:

Those classes give you an idea of what they can be used for: If you have a very unusual request flow, which should be much more rare than in Drupal 7, you can write a special kernel.

---
Tags: 8
---


# Question
Title: Dim background elements when displaying submenu
I am developing a site with Drupal 7 and the requirement that I need to implement is that when a sub-menu is being displayed from the main navigation bar, the rest of the site (all the elements behind the sub-menu) is dimmed (just like when displaying a modal dialog box with JQuery).

I was wonder how I would go about accomplishing the same effect using Drupal's default menu system?

Thanks.

# Answer
There's a bunch of options. jQuery is probably the easiest but I could envision a way of doing it with CSS only using some combination of clever sibling and pseudo-class selectors. You could also do it using an overlay element and some z-index work. Or just use JS/jQuery to dim the other element's opacity either using `animate` or adding a class that has an opacity transition. The best choice depends on your requirements and how your HTML is structured.

But the question is a little vague and not particularly Drupal related. If you want do the last case above, just do `on('hover', function() ) {}` and set the opacity / class of the elements to dim.
> 0 votes

---
Tags: 7, routes, javascript
---


# Question
Title: How can I use the OpenLayers module to draw a route between nodes?
I have some nodes; I need to build a route using the location assigned to them, and I want to draw it on a map. How can I do that?

# Answer
OSM Route looks like it will do exactly what you need.
> 1 votes

# Answer
What you can do easily is to add KML or Geojson layer with one predefined route. This can be requested from YOURS API. Anything more required more or less development.

Sample KML request: `http://www.yournavigation.org/api/1.0/gosmore.php?format=kml&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik`
> 0 votes

---
Tags: 7, javascript
---


title: Access menu links from a module

text:
# Question
Title: Access menu links from a module
I'm trying to display a menu in my module. I've used `\Drupal::entityManager()->getStorage('menu')->load('oz-topbar-menu');` which allows me to get the title of the menu, the description, etc.

I obviously need the links of that menu, and I can't understand how to retrieve. From what I've read in the documentation I should probably use MenuLinkTreeInterface but I don't understand how to instantiate it.

I've tried `\Drupal::menuTree()->load('oz-topbar-menu', $menu_parameters);`. With basic menu parameters it returns a humongous amount of information; I'm guessing it must be the entire menu tree of Drupal.

I tried playing with the parameters of `MenuTreeParameters` (`setTopLevelOnly`, `setRoot('oz-topbar-menu')`) but it returns an empty array.

I've tried sending this as a `MenuTreeParameters` object with `\Drupal::menuTree()->getCurrentRouteMenuTreeParameters('oz-topbar-menu')`, but I still get a massive link tree.

# Answer
You are probably just missing the `build()` call.

```
$menu_name = 'my-custom-menu';
$menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
$tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
$renderable = \Drupal::menuTree()->build($tree);
print \Drupal::service('renderer')->render($renderable);

```

Core is the best example for these kinds of things. I pulled the above from `SystemMenuBlock::build()`.
> 4 votes

---
Tags: routes, 8, entities
---


title: Create themable field group

text:
# Question
Title: Create themable field group
I have a custom entity with several fields. Now I would like to group the fields and give each group it's own twig template so that I would be able to compose a page (my custom entity) containing several sections (field groups).

How would you do that? Do I group the fields in the entity preprocess function and give each group it's own `'#theme'`, do I have to change my `hook_theme` or should the grouping already happen in the controller? Or maybe create a computed field to store the other fields?

Thank you in advance!

# Answer
The field group module is designed to solve this exact problem The Drupal 8 version is reasonably up-to-date.

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
>
> https://www.drupal.org/project/field\_group
> 1 votes

---
Tags: entities, 8, theming
---


# Question
Title: dynamically populate a select field based on the selection in another field works only the first time
I am trying to dynamically populate a select field (chamiponship) based on the selection in another field (country). It works fine when I load the page but just the first time, the second time I select another country it does not work. Did anyone have this issue and how did you solve? Here is my code

```
<?php

function testform_menu(){

    $items['data'] = array(
        'title' => 'data access',
        'description' => 'get acess to the data',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('testform_form'),
        'access callback' => TRUE,
    );
    return $items;
}

function testform_form($form, &$form_state) {

        $form['country']=array(
            '#type'=>'select',
            '#title'=>t('Select your country'),
            '#options'=>array('FR' =>'France', 'UK' =>'England','DE' =>'Germany'),
            '#ajax' => array('event'=>'change','callback' =>'LoadDiv','wrapper' => 'DivSelect',),
        );

        $optionsDiv = array('Ligue 1','Ligue 2');
        if (isset($form_state['values']['country'])) {
            $optionsDiv = loadDivision($form_state['values']['country']);
        }

        $form['champion']=array(
            '#type'=>'select',
            '#title'=>t('Select your championship'),
            '#options'=>$optionsDiv,
            '#prefix' => '<div id="DivSelect">',
            '#suffix' => '</div>',
        );

        $form['submit'] = array(
            '#type' => 'submit',
            // #value is the text to display inside the button
            '#value' => t('Submit'),
        );

        return $form;
}

function LoadDiv($form, &$form_state) {
  return $form['champion'];
}

function loadDivision($country_id) {
  $data_count=array('FR' => array('Ligue1', 'Ligue2'), 'UK' => array('Premier','Championship'), 'DE' => array('Bundesliga1','Bundesliga2'));
  $championship = $data_count[$country_id];
  return $championship;
}

```

# Answer
> 0 votes
It is hard to say without seeing your JavaScript, but what you describe fits perfectly with the following scenario:

When your page loads initially loads, the LoadDiv JavaScript event is bound to #DivSelect, but when that #DivSelect element is overwritten by the Drupal AJAX api, the event is no longer bound.

The solution is to use Drupal.behaviors - there is a good, short explanation at http://www.amazeelabs.com/en/blog/drupal-behaviors-quick-how.

Wrap your LoadDiv javascript in the drupal behaviors code, and it will be added for every request, including AJAX requests:

```
Drupal.behaviors.myModuleDoSomethingCool = {
  attach: function (context, settings) {
    $('#DivSelect').change(function() {
      // Loaddiv etc etc
    });
  }
};

```

I agree with comments suggesting that this is a good use case for hierarchical select - but the above is the likely explanation for why your AJAX works the first time and not the second time.

---
Tags: entities
---


title: My new theme doesn't show the slogan

text:
# Question
Title: My new theme doesn't show the slogan
My site has a nice slogan that was shown with the previous theme.

Now, after installing the new theme "Nexus" (Live demo here), the slogan appears no longer. What should be done to make it appear again? thx.

# Answer
Let's call it a bug in Nexus theme.

If you sub-themed Nexus, copy the page.tpl.php from Nexus templates folder into your sub-theme's template folder, then make the following change to the copied file, just after the h1 tag for the title:

```
// look for this
<h1 id="site-title">
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>"><?php print $site_name; ?></a>
</h1>
// then add this below it
<?php if ($site_slogan): ?>
  <div id="site-slogan">
    <?php print $site_slogan; ?>
  </div>
<?php endif; ?>

```
> 1 votes

---
Tags: theming
---


# Question
Title: How to format Computed Field as WKT (geofield CCK) with display code
I'm pretty green here. This is my first question!

I am using computed field to calculate a WKT (Well known text) geofield using the geocoder API. This calculation is being done correctly, giving a result such as "POINT (28.12866 46.17625)".

When I want to display this computed field the only have the following options:

* Unsanitized
* Plaintext
* Raw value, no display code
* Filtered Markup
* -Hidden-

I currently have the following display code, which I think it the problem:

```
$display_output = $entity_field_item['value'];

```

I don't know how to make the normal geofield formatters available to display this field, so for example I can render it as a map.

# Answer
> 1 votes
Geofield calculates various values with the geofield\_compute\_values() functions (see README), so calculating a WKT will not replace it properly. Geocoder supports computed field, so I guess you can use that to populate a geofield.

---
Tags: entities, location
---


title: Alter label with token

text:
# Question
Title: Alter label with token
I am trying to build a questionnaire that simply replaces (alters) the label of a list field. I am doing so by replacing a token from views (embed) and implementing `hook_form_alter()` in a separate module.

How can I save that value and write it to the database? I am using an Entity form and a list-field.

This is the snippet I am struggling with, found on Store token replacement values in the database rather than tokens themselves.

```
function question_to_label_node_presave($node) {
  if ($node->type == 'page') {
    $replaced_text =  token_replace($node->field_question['und'][0]['value']);
    $node->field_question['und'][0]['value'] = $replaced_text;
  }
}

```

I am currently trying to run this in a custom module, but I cannot find the right content type for the Entity form. I am using the *Devel* module to find the right array value.

# Answer
> 0 votes
I´ve solved it by **using a token**, and placed that token (from a view) in a hidden field in that form - thus saving that value.

The same token generated from views - I used to **alter the label** for that question with "hook\_alter\_form".

A kind of non programmatically way of solving the problem.

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


# Question
Title: Machine readable coordinates to Geofield
I got a long txt file full of cordinates. Like this for every line;

```
 {"RT**n":"*****","RT**o":"*******","WGS**_lat":"******","WGS**_lon":"******" }

```

There are numbers, I just hide them since this is just a example. Anyway. I got a lot of these and it would take me forever to manually insert them. Is there any way to import these into D7 Leaflet Geofield?

Thanks

# Answer
This question is similar to the follosing, I recommend using the Feeds module: How do I import latitude/longitude into geofield?
> 0 votes

---
Tags: location
---


title: Javascript: Drupal.media is undefined

text:
# Question
Title: Javascript: Drupal.media is undefined
When I try to upload an image through anything other than the admin/content/media interface, I get an "Drupal.media is undefined" error.

Uploading an image through the interface does work. Using the Firefox developer console I can search all files (!drupal.media). It finds something on admin/content/media but nothing on other pages.

I do have the Media module installed, and I am aware of the following modules being affected: md\_slider and stability (a theme).

Why does this happen, and how can I fix it?

**Console log on Chrome**

```
'Attr.nodeValue' is deprecated. Please use 'value' instead.
Resource interpreted as Image but transferred with MIME type text/html: "http://xxx/admin/structure/md-slider/4/undefined".
Uncaught TypeError: Cannot read property 'popups' of undefined

```

**Console log on FireFox**

```
SyntaxError: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead
Error: http://xxx/sites/default/files/js/js_oCVMDTeSNt-_QxknevWyf6yO5OzmME3AhRz3ggZgNtg.js is being assigned a //# sourceMappingURL, but already has one
Use of getPreventDefault() is deprecated.  Use defaultPrevented instead.
Use of getAttributeNode() is deprecated. Use getAttribute() instead.
Use of attributes' nodeValue attribute is deprecated. Use value instead.
Use of attributes' specified attribute is deprecated. It always returns true.
Use of getPreventDefault() is deprecated.  Use defaultPrevented instead.
TypeError: Drupal.media is undefined

```

**List of installed modules**

> Chaos tool suite Chaos tools (ctools) Module Enabled 7.x-1.5
>
> Core Block (block) Module Enabled 7.34
>
> Core Color (color) Module Enabled 7.34
>
> Core Contextual links (contextual) Module Enabled 7.34
>
> Core Dashboard (dashboard) Module Enabled 7.34
>
> Core Database logging (dblog) Module Enabled 7.34
>
> Core Field (field) Module Enabled 7.34
>
> Core Field SQL storage (field\_sql\_storage) Module Enabled 7.34
>
> Core Field UI (field\_ui) Module Enabled 7.34
>
> Core File (file) Module Enabled 7.34
>
> Core Filter (filter) Module Enabled 7.34
>
> Core Help (help) Module Enabled 7.34
>
> Core Image (image) Module Enabled 7.34
>
> Core List (list) Module Enabled 7.34
>
> Core Menu (menu) Module Enabled 7.34
>
> Core Node (node) Module Enabled 7.34
>
> Core Number (number) Module Enabled 7.34
>
> Core Options (options) Module Enabled 7.34
>
> Core Overlay (overlay) Module Enabled 7.34
>
> Core Path (path) Module Enabled 7.34
>
> Core RDF (rdf) Module Enabled 7.34
>
> Core Search (search) Module Enabled 7.34
>
> Core Shortcut (shortcut) Module Enabled 7.34
>
> Core Statistics (statistics) Module Enabled 7.34
>
> Core System (system) Module Enabled 7.34
>
> Core Taxonomy (taxonomy) Module Enabled 7.34
>
> Core Text (text) Module Enabled 7.34
>
> Core Toolbar (toolbar) Module Enabled 7.34
>
> Core Update manager (update) Module Enabled 7.34
>
> Core User (user) Module Enabled 7.34
>
> Fields Link (link) Module Enabled 7.x-1.3
>
> Mail SMTP Authentication Support (smtp) Module Enabled 7.x-1.0
>
> Media File entity (file\_entity) Module Enabled 7.x-1.4
>
> Media IMCE (imce) Module Enabled 7.x-1.9
>
> Media Media (media) Module Enabled 7.x-1.4
>
> Media Media Internet Sources (media\_internet) Module Enabled 7.x-1.4
>
> MegaDrupal MD Slider (md\_slider) Module Enabled 7.x-2.15
>
> NikaDevs NikaDevs Main Features (nikadevs\_cms) Module Enabled 7.x-1.0
>
> NikaDevs NikaDevs Visual Shortcodes (nd\_visualshortcodes) Module Enabled 7.x-1.0
>
> NikaDevs Stability Shortcodes (stability\_shortcodes) Module Enabled 7.x - 1.2
>
> NikaDevs Stability theme module (stability\_cms) Module Enabled 7.x - 1.2
>
> Other Token (token) Module Enabled 7.x-1.5
>
> Shortcode Shortcode (shortcode) Module Enabled 7.x-2.1
>
> User interface CKEditor (ckeditor) Module Enabled 7.x-1.16
>
> User interface jQuery Update (jquery\_update) Module Enabled 7.x-2.4
>
> Views Views (views) Module Enabled 7.x-3.8
>
> Views Views Load More (views\_load\_more) Module Enabled 7.x-1.5
>
> Views Views UI (views\_ui) Module Enabled 7.x-3.8
>
> Core Seven (seven) Theme Enabled 7.34
>
> Other Stability (stability) Theme Enabled 7.x-1.4.2

# Answer
I contacted the dev of the stability theme. He gave me a link to update the md\_slider module to v7.16.

This fixed the issue
> 0 votes

# Answer
I am afraid this error comes from the `jQuery version`.

Since you have the jQuery\_update module check if the admin has the same version with the frontend. If not change the jQuery version of the admin to be the same as the frontend's (this can be through the modules UI page). Then, check if the same error occurs on the admin page. If so you have to test the frontend with other jQuery versions.

Notice that in case you cannot use the proper jQuery version for the frontend (since there are confilcts with other modules) then the only solution is to disable these modules or override them.

Before that, maybe you could use the `latest dev versions` for media, jquery\_update modules and check if the problem remains.
> 1 votes

---
Tags: javascript, media
---


# Question
Title: Programatically altering a field formatter in Views
I'd like to create a new (date) field formatter in Views, but also keep the existing formatters intact. As of now, I've managed to use `hook_field_views_data_alter()` to entirely replace the exiting handler with mine. However I would prefer to have my custom formatter available in the dropdown below. Is it possible to append an option to this dropdown for my custom formatter?

# Answer
> 3 votes
If you wish to display a field in a different way, there are a different ways to go about it.

1. Create a field template in your theme and change there. Just copying the field.tpl.php file would work changing the way the field is rendered on a node page. Note that `field.tpl.php` is a generic template which would be called on each field. You might want to try the specific template names like : `field--article.tpl.php` would get applied to all fields on article content type; `field--body.tpl.php` would get applied to body field on any content type; and `field--body--article.tpl.php` would only get applied to body field on the article content type.
2. Overriding the theme\_field() function. E.g. Implementing the following functions in your theme's template.php file would do the same as with template copying `THEMENAME_field__body__article()`, `THEMENAME_field__article()`, `THEMENAME_field__body()`, `THEMENAME_field()`.
3. If the field is rendered in a view you could override it with the view template. To find out the specific template which you would need to override, click on "Theme: information" under the "Advanced" settings in the view to find the field template that applies to your field.
4. By creating your own custom field formatter by using this blog post. This will display the formatter in the dropdown as you intend.
5. There is also a module which helps your create custom formatters, which are ctools exportable. Which means you could easily featurize them. More about the module:
> The Custom Formatters module allows users to easily create custom CCK/Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables/Features or Drupal API Formatters.

---
Tags: 7, datetime, views
---


title: How to properly add inline js?

text:
# Question
Title: How to properly add inline js?
```
function prospectpicker_unfollow_init() {
drupal_add_js($prospectpicker_unfollow_path . '/js/stickyMojo.js');
drupal_add_js('jQuery(document).ready(function () {
    jQuery("#unfollow-sidebar").stickyMojo({footerID: "#unfollow-footer", contentID:  "#unfollow-content"});
    });', 'inline');
}

```

I have included a js file named as "stickyMojo.js", and I want to use that js file's function named as stickyMojo, in order to add the sticky sidebar to my form elements.

# Answer
Just a suggestion.

As `hook_init` is only called on non-cached page, and you require this JS to be called on every page; why don't you go ahead and add it to your theme's `.info` file?

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

```
> 2 votes

# Answer
Where are you defining the `$prospectpicker_unfollow_path`?

To construct your path to a certain file of your module, you can use the `drupal_get_path` function of Drupal. In your case it would be:

```
function prospectpicker_unfollow_init() {
    drupal_add_js(drupal_get_path('module', 'prospectpicker_unfollow') . '/js/stickyMojo.js');
    drupal_add_js('jQuery(document).ready(function () {
        jQuery("#unfollow-sidebar").stickyMojo({footerID: "#unfollow-footer", contentID:  "#unfollow-content"});
    });', 'inline');
}

```
> 2 votes

# Answer
Just an addition to @Mike Vranckx's answer: We can use the heredoc PHP syntax :

• is easier to read
• and to write ( quoting especially )

As well as to precise the scope ( eg : display the script in the footer )

```
function prospectpicker_unfollow_init() {
  $inlineJS = <<<EOT
    jQuery(document).ready(function () {
      jQuery("#unfollow-sidebar").stickyMojo({
        footerID: "#unfollow-footer",
        contentID: "#unfollow-content"
      });
    });
EOT;
  drupal_add_js(drupal_get_path('module', 'prospectpicker_unfollow') . '/js/stickyMojo.js');
  drupal_add_js($inlineJS, 'inline');
  // We can tell as well where to display it ( eg : in the footer )
  // drupal_add_js( $inlineJS, [ 'type' => 'inline', 'scope' => 'footer', 'weight' => 5 ]);
}

```
> 2 votes

---
Tags: forms, javascript
---


# Question
Title: Views with filter on "main" and "additional" taxonomy terms
My articles are organised in a taxonomy, where each article has multiple taxonomy terms. I now want to build views for my front page, where each view represents a part of the taxonomy.

However articles can have tags from multiple parts of the taxonomy, but here, each article should only appear in one view. Is there a simple way to somehow in the admin interface mark one taxonomy term as "main term", such that in the front page views, the article only shows up for the view which shows this "main term"?

What I have tried so far is to have two taxonomy fields for my article, one for "main term" and one for "additional terms". However when building the view with the filter "has taxonomy terms (with depth)", there seems to be no way of specifying that I only want it to look in the "main term" field. Is this approach viable and how would I build the view?

# Answer
You should use the *Representative Node* pattern. That is that your View on the taxonomy refers to another View that collects a Node based on a particular filter (a checkbox in your example but just as easily a flag like "Sticky" or "Promoted").

There are two representative node patterns in Drupal 7. The first, which is builtin to Views, is a little less flexible (you can only sort on one parameter and you can only get one result). The second is the contrib module Views Field View which has fewer limitations but is a little harder to set up (you have to pass the contextual filter yourself).

## Views 3

* Firstly create a *View* on **Content** (filtering on Articles) with a *contextual filter* on the field containing terms from your Taxonomy. Check that it works by passing in a term ID that you know has content. You should get a number of results.
* Next create a View on your **Taxonomy** and have it list out the terms.
* Add a *Relationship* (Advanced \> Relationship) using *Taxonomy term: Representative node*
* Sort on your specifier (your checkbox field or sticky/promoted)
* Select your first View on Articles and apply.
* Add a field Title and use the *Representative node relationship*. Continue adding fields using the relationship.

## Views Field View

* Firstly create a *View* on **Content** (filtering on Articles) with a *contextual filter* on the field containing terms from your Taxonomy. Check that it works by passing in a term ID that you know has content. You should get a number of results.
* Then *limit* the number of results. Possibly 1 in your case. Turn off paging.
* Lastly *filter* on how you want to select your Representative node. The checkbox, or stick/promoted.
* Next create a View on your **Taxonomy** and have it list out the terms.
* Add a hidden *tid* (term ID) field
* Optionally add Title and other fields.
* Then add a *field* of type *Global:View*
* Select your View previously created. Pass in the term ID.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: Have I understood correctly? - Drupal Slider\carousel modules
Why in Drupal, so much is needed just to insert a picture into a slider?...

I understand that in the typical Drupal slider modules, we can't just upload a picture into the slider - We MUST choose from and existing photo in the site and it MUST also be an existing photo from an existing View... This is (allegedly) a problem because it forces one to upload the picture to somewhere in the site even if there is no such necessity and also forces him to use Views even if he has no need to.

Why all of this way just to use a picture and are there really no shorter ways to do image sliding in Drupal?

Please correct me if I was wrong in anything here.

# Answer
There are a lot of options within Drupal. This is it's great strength, but comes with a steep learning curve for starters.

So there are a lot of modules to build a slider. Most sliders require a content type where you upload the image and views to make the list of images. This is not to make it hard, but to give you options on what to do with it.

If you want an 'instant' slider, check out https://www.drupal.org/project/content\_glider. No views required.
> 1 votes

---
Tags: javascript
---


# Question
Title: Seperate /user/register fields and admin/people/create
i extended the add user field by adding a role field as part of the fields that will be displayed when you click create user in mydomain.com/user/register. With the addition of some rules, this helps me to assign automatic roles to registering users.

I however noticed that when you add user from the admin menu in People\>Add user, this roles fields are added to the already existing fields. This is undesirable because the Add user page already have a section where you can pick the role. This therefore makes the form to have 2 different section where you can pick roles.

I want to hide my custom role field in mydomain.com/admin/people/create but show it in mydomain.com/user/register. Please how do I achieve this

# Answer
> 0 votes
Probably hook\_form\_FORM\_ID\_alter on `user_register_form` then some logic like

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

  // Is logged in user admin.
  if (user_access('administer users')) {

    // Hide myfield.
    $form['myfield']['#access'] = FALSE;
  }
}

```

---
Tags: users
---


title: removing page title in drupal page

text:
# Question
Title: removing page title in drupal page
I have a Drupal 7 site, where I created a new page which became my front page.

Drupal requires that the page have a title and I've found no way of removing the title from showing on the page. At the moment, I have the title as "Welcome". I'd like to remove it completely from the page or make it invisible. I'm looking for the easiest method to accomplish this.

# Answer
The quickest way would be by css. You can do something like this (might need to change this depending on your site html structure):

```
.front h1#page-title {
  display: none;
}

```
> 5 votes

# Answer
> 1 - you can create file page--front.tpl.php in theme dir and you can hide the title .

```
<?php print render($title_prefix); ?>
  <?php if ($title): ?>
   <!--   <h1 class="title" id="page-title">
     <?php //print $title; ?>
    </h1></h2>-->
 <?php endif; ?>
  <?php print render($title_suffix); ?>

```

> 2 - you can use css Rule to hide this title
>
> 3- you can use hook\_page\_alter or hook\_preprocess\_page add this code

```
if (drupal_is_front_page()) { drupal_set_title('');}

```
> 5 votes

# Answer
My suggestion would be to consider to use Display Suite to accomplish this. The display suite package has a module named Display Suite Extras which provides additional granular features such as disabling all blocks from the site theme, assigning a title manually or having the choice to remove the title.

The following steps would be carried out to accomplish the same:

1. First enable 'View mode per node' from Extras field in **Administer \>\> Structure \>\> Display Suite \>\> Extras** tab and check both `View mode per node` and `Page title options`.
2. Next step would be enable our custom View mode to be available to use in our content type nodes' display. Navigate to **Administer \>\> Structure \>\> Content Types \>\> your\_content\_type**, Create a specific View mode without the title being displayed (the option would be `Custom page title` where Page Title could be set as Hide) and save the settings. Alternatively one could clone the Full page display mode for the new view mode (if the only change between a normal node and a node in the front page is the title) and make change to the title alone.
3. Navigate to the Edit page (node/our-node-id/edit) of our node which should be used as the Site front page. An additional tab named `Display Settings` would be available likely below the Publishing options where our new View mode can be selected and save the node.

This would ensure that the front page node would not have its title displayed. Though the process might sound a bit too lengthy or even complicated for a novice user to Display Suite this provides a certain advantage of choosing to enable or disable the functionality at will from the admin UI granting flexibility which would be evident on a long run.

Another code free method of doing this would be using Exclude Node Title module to do so as mentioned by user Rama raju dantuluri in the comment.

Alternatively you could create a front page template named `page--front.tpl.php` in your theme sans the `$title` to attain the result.
> 2 votes

# Answer
The most intuitive method I have found to remove the node title from the front page or any other content type is by utilizing the Title module https://www.drupal.org/project/title. This module has been developed to convert node titles to make use of the Field API in order to make nodes fully translatable. Editing of the node titles is made available via the Manage Display tab.
> 0 votes

---
Tags: 7
---


# Question
Title: Loading a View Through Ajax - Slideshow not showing
I have a view in node-view mode that has another view (a view slideshow) embedded into that view. I am using jquery and setTimeout to slideDown the hidden div that contains the view a few seconds after the page loads. The problem that I am running into is when the div slides down to show the view, the slideshow is not showing.

Here's my jquery

```
Drupal.behaviors.landing = function (context) {
if($('#portslide-wrap').children().children().next().hasClass('portfolio-direct')){

    setTimeout( function getSlide(){
        $('#portslide-wrap:not(.landing-processed)', context).addClass('landing-processed').each(function(){

            $('#portslide-wrap').slideDown();
            $.scrollTo('165','0');
            Drupal.attachBehaviors(context);

        });
    }   ,700)
  };

}

```

# Answer
Are you using a Drupal module like Views Slideshow to create your slideshow?

Usually slideshows will need to dynamically calculate the height/width of the content in the slides in order to render correctly. If the slideshow is hidden when the slideshow's javascript is loaded, then there will effectively be no content for the slideshow's javascript to render, thus the slideshow will never render correctly.

Does the slideshow render with no problems if you remove your CSS and/or JS that hides (and then slides down) the slideshow?

I haven't dealt with this sort of issue directly, but hopefully I can point you in the right direction. I would guess that somewhere you are using JS or CSS to hide the `#portslide-wrap` div (i.e. display: none;) until it is ready to slide down? I would suggest trying to hide that div behind some other element using z-index rather than display:none(so that the slideshow can render while being obscured) and then hide it using JS after the slideshow has processed (probably a class like "slideshow-process" is added to a wrapping div, which you can use to hide the slideshow via CSS).
> 0 votes

# Answer
Old question, but if someone finds this via Google then this should help. The above JavaScript is close. Try:

```

(function($) {
  Drupal.behaviors.myFuncName = {
    attach: function(context, settings) {
      console.log('Do stuff');
    }
  };
})(jQuery);

```

There is no need to call `Drupal.attachBehaviors` unless you are returning new elements for the DOM. In that case your context variable would be the new elements. It's also worth noting that you are missing the "settings" object in the arguments of the function you are trying to attach.
> 0 votes

---
Tags: ajax
---


# Question
Title: Customise Recent Content block to show only 1 content type
I need to customise the 'Recent Content' block to show only 1 content type (i.e pages or articles).

This doesn't seem to be possible with the block settings so I presume that I need to clone and/or edit this block to restrict the content it shows?

# Answer
> 2 votes
A custom View (as a block) would solve your problem.

You can make it replicate the functionality of the 'Recent Content' block but minus the the Content Type that you wish not to include.

# Answer
> 1 votes
Views is the answer, it is the most used module on Drupal sites, but it has a learning curve (well worth studying!). Try the video series at Nodeone.se called Taming the Beast. You will emerge as a guru of Viewdom.

# Answer
> 0 votes
If you want to use Views for creating recents content block, simply create a view, add sorts by newest items filter and select content-types you want to use. You can also add more filters and aditional options.

+You can also click configure from recents block, choose 'content-type' and select content-type you want to limit.

---
Tags: 7, theming, blocks
---


# Question
Title: Can you duplicate a Drupal 7 site and database when a new user registers?
I'm building a site that will be used as a template site for new users. Once someone signs up, they should receive a copy of the original master template site, including their own SQL database.

Ideally, the new sub-site would need to receive updates from the master site somehow.

Is there a way to copy and entire site when someone registers? Can this be accomplished with Multi-sites?

# Answer
Yes, using hook\_user\_insert() to start the process off. From a custom module that implements hook\_user\_insert() you can run any code you want. However to pull it off you're going to have to write quite a bit of custom code.

Your hook\_user\_insert() function would need to do quite a lot of steps:

1. Fetch the database connection information defined in settings.php
2. Run *mysqldump* to make a .SQL dump of the database
3. Run a *tar* command to make a .tar.gz file of the Drupal codebase (PHP files) and files directory.
4. Zip or tar or something the sql file, the .tar.gz file, and probably some kind of instructions
5. Present the file for download. This is made trickier because you don't want to have the file inside your codebase.. or each time you clone the database you'll pick up all the .zip files from previous users in the next user's .zip file. You either need to serve the file directly, exclude the zip files from future codebase archives, or serve the zip files out of a directory that won't get zipped into the zip file.
6. (optional) Clear the user out of the master site so that it doesn't exist for future signups.

You ask about Multi-Sites, that's only relevant if you plan to immediately start hosting the cloned site yourself. If your plan is to have the user download their files and .SQL database, you don't need to worry about that. (The user will have to worry about loading the SQL dump and setting up a database username and password though, which you'll need to babysit them through or it will never end up working out).

If your plan is to clone the site on your server, then you could do it with a multi site. Your steps would then be:

1. Fetch the database connection information defined in settings.php
2. Run *mysqldump* to make a .SQL dump of the database
3. Create a new MySQL database to hold the new cloned site 4. There are security implications here.. if your webserver is allowed to create mysql databases, is it really secure from hackers?
4. Create a new sites/new.example.com folder for the new site (if it were named new.example.com)
5. Create a new settings.php file for the new site's database in sites/new.example.com
6. Load the SQL dump from step 2 into the new database (using the command line *mysql* command)
7. Redirect user to the new site. You will need to use Wildcard DNS (ie. \*.example.com woudl match site1.example.com, site2.example.com, etc. and you wouldn't need to add DNS entries for each new site).

While this plan is not impossible, it will be quite hard to get working well. Your biggest challenge will be helping the users get through the complicated task of creating a new database, setting up username and password for it, loading the SQL dump, configuring their webserver etc etc etc.
> 0 votes

---
Tags: 7, users, multi-sites
---


# Question
Title: How do i create complicated content type?
My apologies for bad english.

I want to create educational website with user generated content. Sort of like wikipedia. The problem is content is a little bit complicated. It must have 4 tabs, which represent 4 stages of learning. Each individual tab must have guide (a basic content page with a text), a f.a.q. page, and a forum for users to open topics related to subject of learning and current stage. I draw a markup for better undearstanding:

I tried to make it myself by creating a content type with a Field Group module and ended up with this:

Current problems are: a) guide on each tab is just a text but needs to be a title, which leads to page with a guide; b) have comments instead of forum under the tabs and no idea how to make it.

I would absolutely appreciate any help.

# Answer
> 1 votes
Install Field Collection

> Provides a field-collection field, to which any number of fields can be attached.
>
> A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.

and Field Collection Tab formatter

> Field collection tabs provides a field formatter that allows you to output a multi value field collection field as a tabset, with one tab per field collection item.
>
> You can optionally choose a field from the field collection item to be used as the tab title.

modules.

Your common elements, guide, faq, forum goes into the field collection. Also put the stage title as a field in the field collection. Then use the stage title field as the title for the tabs.

# Answer
> 0 votes
Some tips:

* to create link to Guide page you can use Link module
* consider use of taxonomy terms for stages
* don't apologize for your English ;) It's very good IMO.

More info here: Filter category taxonomy with tabs

---
Tags: nodes
---


# Question
Title: Notice: Undefined index: tid in taxonomy_field_formatter_prepare_view() (line 1669 of
I'm getting this error on my website. I have tried cleaning up the content type of all fields but it still shows up.

Any ideas what could be causing it, and how to debug?

Thanks a lot,

Chiko

# Answer
Your content have an taxonomy\_term reference field which have invaild data, maybe it break.

You can install devel module and use error display with debug\_backtrace and you will see where it comming.
> -1 votes

# Answer
1 Open Content Type, 2 manage field tab, clieck save. 3 manage display tab, click teaser , default, and save
> -1 votes

---
Tags: taxonomy-terms
---


title: hook_menu() custom URL with argument

text:
# Question
Title: hook_menu() custom URL with argument
I am working with a 300K records dataset and I am having some performance issues. I try creating a node for each of the records on the dataset, but even the simple path translation query is taking forever (over 50ms to execute) to get the node ID from the page and the rest of the queries on the page make it insanely slow to load a single page. The server has all the capacity it might need and it even has memcached working, PHP-FPM, NGINX, etc.

I decided to have each page coming from that dataset as simple as possible to avoid having to load all those objects and so on. The question comes when I want to use the url:

```
http://www.example.com/item-ABBC

```

ABBC is the argument that will hit the database to perform a search, but I can figure out how to accomplish this with the hook\_menu:

```
function mymodule_menu() {
    $items['item-%'] = array(
      'page callback' => 'mymodule_abbc_view',
      'type' => MENU_CALLBACK,
    );
    return $items;
}

```

I am trying to avoid hitting the path table as much as possible that is why I wanted to use the MENU\_CALLBACK instead of a regular menu item.

Is this possible at all?

# Answer
> 2 votes
The way Drupal works out of the box, you need to separate your arguments with /. So your URL should be 'item/%'.

---
Tags: 7, routes
---


title: Pass arguments to a node

text:
# Question
Title: Pass arguments to a node
How do you pass an argument from a menu to an existing node? I've read many articles on hook\_menu but they seem to all talk about creating a page which references the arguments.

for example:

```
function myModule_menu(){
  $items['node/123/%'] = array(
    'page arguments' => array(1),
    'access callback' => TRUE,
  );
  return $items;

```

In my Navigation menu, I'd want to use a menu item with: node/123/option1

How would I get the argument 'option1' available to me in for example, the node.tpl.php file to manipulate the rendering of node/123 ?

At the end of the day, I'm trying to do is execute some jquery code based on a menu's argument, but the initial hurdle, how do I get access to these optional arguments on the url?

# Answer
The easiest way is to use `$argument = arg(2)` but more formal and much better way will be to create new menu item based on `node/%node`:

```
function yourModule_menu() {
  $items['node/%node/%'] = array(
    'page arguments' = array(1, 2), // Here you can specify which parts of url are page callback arguments (starting with 0)
    'page callback' = 'yourModule_node_with_option',
    'access arguments' => array('content access'), // Try to avoid access callback = TRUE
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function yourModule_node_with_option($node, $option) {
  // build your new page here.

  // $option is your extra parameter.
  $output = $node->nid . ' ' . check_plain($option);

  // This will show you node id and value of parameter
  return $output;
}

```
> 3 votes

---
Tags: routes
---


# Question
Title: Views PDF CSS file not being applied on generated PDF
I've created a pdf display with views\_pdf module in views, and under the PDF SETTINGS i've included a CSS File (eg. sites/all/themes/custom/mytheme/css/mytheme.css).

When viewing the page display of the view, the css is being applied, but when viewing the generated pdf, all of the css is missing. I have tried putting inline css as well but it's not working.

Can someone tell me what is the workaround for this?

# Answer
> 0 votes
What worked for me is to rewrite the field. For the title field it would be something like:

```
<div class="pdf-title">[title]</div>

```

And then use this custom class in my CSS file.

---
Tags: theming, views
---


title: URL alias for taxonomy in drupal 7

text:
# Question
Title: URL alias for taxonomy in drupal 7
On a Drupal 7 site with pathauto installed I'm using a view to show all taxonomy terms of a given node. The terms are linked to the term's page. The problem is, that the path of those terms does not use the url alias' that are set for the terms. Is there a way (without programmatically rewrite the view) to use alias in a view?

I know about the globalredirect module, but a redirect is not a clean solution here, in my opinion. And I do not understand why the pathes aren't replaced by there aliases in a view, can someone explain please?

# Answer
> 0 votes
```
<div id="nos_produits" class="grids_of_3 grids_of_3_accueil">

<?php

$field = $view->result;
?>

<?php

    foreach($field as $obj){

     $url = drupal_lookup_path('alias', 'taxonomy/term/'. $obj->tid);

?>
<div id="nos_produits" class="grids_of_3 grids_of_3_accueil">
<div class="grid1_of_3 div_cat_accueil">

    <a href="<?php echo $url;?>">
        <div>
            <p><span><?php echo $obj->taxonomy_term_data_name;?></span></p>
        </div>
        <img src="http://faliam.com/demo/sites/default/files/styles/catalogueimage/public/catalogue/<?php echo $obj->_field_data['tid']['entity']->field_illustration['und'][0]['filename'];  ?>" alt="" height="300" width="368">

    </a>

    </div>
    </div>

<?php

}

?>
</div>

```

---
Tags: views, taxonomy-terms, path-aliases
---


title: Blocks stopped showing on views page

text:
# Question
Title: Blocks stopped showing on views page
I was hoping you could help me with this problem on my website.

I have a views page "News" for a long time now. (q?=news) I also have 2 blocks that I want to show on that page. On the configurations I set: All pages except those listed - and I listed all the pages i don't want the block to show (So I **didn't** write the News page).

Thing is, **this was working fine** and suddendly the blocks stopped showing on that specific page, and I have no idea why.

Any thoughts?

Thank you in advance!

P.S. I can't just try the "Only the listed pages" option because there are too many pages involved.

# Answer
It's difficult to answer because I don't have enough information on what is happening, but here are some suggestions:

1. Give your views page a url alias of /news if you haven't already and in the block configuration make sure "news" is not listed there. Then you don't have to use "?q="
2. Make sure your spelling is correct so it's not q?=news and is ?q=news in your block configuration.
3. Views pages are not great to work with, personally I don't like them for a number of reasons. Instead, I use the insert\_block module and I insert a views\_block into my node, I get less problems like that and more flexibility.
4. The context module is also a good module for placing blocks in regions based on any type of page, but it's more difficult to manage.

EDIT: More things to check:

5. Make sure no styling is hiding those blocks. Check the markup loaded on the page and see if the markup for those blocks is loading on the page or not.
6. Make sure that the region you assigned those blocks to is actually loading on the views page.
> 0 votes

---
Tags: blocks
---


# Question
Title: Why does this rule not appear in the UI and how can I clone it?
I need to clone and modify the following rule:

```
commerce_checkout_order_email

```

However, it does not appear in the UI.

I have checked the following paths with no success:

```
admin/config/workflow/rules
admin/commerce/config/checkout/rules

```

I'm obviously missing something but I can't figure it out.

This rule is defined in this file along with 4 other rules, all of which do appear in the UI

```
sites/all/modules/commerce/modules/checkout/commerce_checkout.rules_defaults.inc

```

The thing is this rule DOES get executed properly.

Any ideas will be greatly appreciated.

By the way, I have doubled checked on TWO different drupal installations, one of which is a default `commerce_kickstart` distribution and the rule doesn't appear either. It won't show up in the UI nor in the database.

# Answer
After lots of research, and thanks to some helpful hints posted by other users here, I have been able to trace out the problem to the following:

* The rule was indeed working properly throughout my testing process
* The rule MUST have been deleted when disabling a 3rd party module. Possibly one of the following: `i18n`, `i18n_string`, `rules_i18n` (I disabled them and I did get a warning saying some rules had been translated and would be affected)
* After disabling these modules, the rule wasn't working anymore (I thought it was since I hadn't tested it yet after disabling those modules
* Importing it again get it back up and running

Thank you all for you help and cooperation!
> 0 votes

# Answer
* I don't think it's possible to delete this Rule. Even if you delete it from the database directly, it is recreated the first time Commerce gets called (because it's in the defaults .inc file).
* Are you sure it's not just disabled?
* Your module directory structure is non-standard; Commerce should be in `sites/all/modules/contrib`.

Here's a copy of the Rule in case you need to import it again:

```
{ "commerce_checkout_order_email" : {
"LABEL" : "Send an order notification e-mail",
"PLUGIN" : "reaction rule",
"WEIGHT" : "4",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [ "rules", "commerce_checkout" ],
"ON" : { "commerce_checkout_complete" : [  ] },
"DO" : [
  { "mail" : {
      "to" : [ "commerce-order:mail" ],
      "subject" : "Order [commerce-order:order-number] at [site:name]",
      "message" : "Thanks for your order [commerce-order:order-number] at [site:name].\u000A\u000AIf this is your first order with us, you will receive a separate e-mail with login instructions. You can view your order history with us at any time by logging into our website at:\u000A\u000A[site:login-url]\u000A\u000AYou can find the status of your current order at:\u000A\u000A[commerce-order:customer-url]\u000A\u000APlease contact us if you have any questions about your order.",
      "from" : ""
        }
      }
    ]
  }
}

```
> 1 votes

# Answer
Some time ago i had similar problem. The problem was (i think it was a bug of rules) that when saving a rule sometimes its owner was changed to something else and after that i could not see it in the ui

So check in the data base the table rules\_config, search the rule a check its owner, it should be rules
> 1 votes

---
Tags: 7, commerce, rules
---


title: Create a node programmatically?

text:
# Question
Title: Create a node programmatically?
I found this code to create a node programmatically. It creates the node but the "title" field is not populated.

```
    $body_text = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.';

  $node = new stdClass();
  $node->type = 'flats';
  node_object_prepare($node);

  $node->title    = 'Node Created on ' . date('c');
  $node->language = 'en';

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

  $path = 'content/my-lipsum-' . date('YmdHis');
  $node->path = array('alias' => $path);

  node_save($node);

```

The machine name of my Title is "title\_field", but using this neither works:

```
  $node->title_field    = 'Node Created on ' . date('c');

```

# Answer
> 2 votes
Are you using https://www.drupal.org/project/title ? If that's the case you must treat it like a field:

```
$node->title_field[$node->language][0]['value'] = 'Node Created on ' . date('c');

```

---
Tags: nodes
---


# Question
Title: Adding a 'post to everyone' option in Drupal Commons
At present, Drupal Commons posts must be added to one or many groups or to trusted contacts. I would like to add a "public" post that everyone can see in their feed. This is simply a meta group that all members belong to given that my community is a smaller, private intranet.

So, I would like the post to have 3 options. 1) Post to a group(s), 2) post to trusted contacts, 3) post to the community.

Has anyone implemented this ?

# Answer
Ok, I think I have enough information to help. Just because something is listed as a Group Post (i.e. something that can be posted into a group) doesn't mean it needs to be. In other words, by nature of not selecting any groups you are effectively leaving the piece of content out of the group context.

Then, I might consider simply modifying the view which powers the user feed (this is a view that ships with Commons) and including non-group posts with a specific flag/tag. So to recap:

* Create a tag (using taxonomy) or a flag (using this module) that effectively denotes a piece of content being non-group specific. e.g. public
* Instruct your users by way of a bit of help text on the node type that they should use that tag and not post into a group.
* Modify the view powering a user's feed (I think this is called Activity Stream IIRC) to include your newly tagged or flagged content.
* Fancy bonus: Use a bit of JavaScript to disable the group field if either of the above flag/tag conditions are true. (Pseudo-Code: `if node has tag public then disable list box`)

That should get you there. Hope this helps.
> 0 votes

---
Tags: 7
---


title: Embedding a view from a page with php

text:
# Question
Title: Embedding a view from a page with php
I need to put three view blocks next to each other on a page. Therefore, I thought i could put some php code in a new page and manually put them next to each other with DIVs.

The problem is that I can't seem to output the views block.

I have tried multiple things:

```
//load the view by name
$view = views_get_view('woensdag');
//output the view
//var_dump($view);
--> this returns the view, so it is being loaded

$view_name = 'woensdag';

views_embed_view($view_name, 'default');
--> outputs nothing

views_get_view_result($view_name, 'block');
--> outputs nothing

echo views_embed_view('woensdag', $display_id = 'block')
--> outputs nothing

```

The delta name of the view is woensdag-block\_1, I have tried that as well.

Any ideas? I am using Drupal 7.

# Answer
```
views_embed_view($view_name, 'default');
// does not work because you need to print/echo the result. eg.
print views_embed_view($view_name, 'default');

views_get_view_result($view_name, 'block');
//does not work because the function returns an array (and you aren't even trying to print the array anyway)

echo views_embed_view('woensdag', $display_id = 'block')
// Trying to set a variable in a function call? It probably would have worked like this:
echo views_embed_view('woensdag', 'block')

```
> 0 votes

---
Tags: views, theming
---


# Question
Title: How to remove JS from a page during preprocess D7
I'm trying to remove few JS files from one page, which will be called in an Iframe (so no TEMPLATE\_js\_alter possible because of the if condition).

This code below unset the JS but they are still loaded on the page. It's like I can't save the new list of JS.

Any ideas ?

```
 function theme_preprocess_page(&$variables) {
        $scripts = drupal_add_js();
        dsm($scripts);

        if(arg(0) == "account" && arg(1) == "reset"){
            foreach ($scripts as $key => $value) {
                $uri = strrpos($key, 'sites/all');
                if($uri !== FALSE){
                    unset($scripts[$key]);
                }
            }
            $variables['scripts'] = $scripts;
        }
    }

```

# Answer
> 1 votes
You can try hook\_js\_alter and remove it from there:

```
module_hook_js_alter(&$data) {
  dpm($data);
  unset($data['script']);
  dpm($data);
}

```

# Answer
> 1 votes
Assuming that you really need to use that code in a preprocess function, you should do it in `hook_preprocess_html()` with code similar to the following one.

```
function theme_preprocess_html(&$variables) {
  $scripts = drupal_add_js();

  if (arg(0) == "account" && arg(1) == "reset") {
    foreach ($scripts as $key => $value) {
      if (strrpos($key, 'sites/all') !== FALSE) {
        unset($scripts[$key]);
      }
    }

    drupal_static_reset('drupal_add_js');
    drupal_add_js($scripts);
    $variables['scripts'] = drupal_get_js();
  }
}

```

`$variables['scripts']` should contain the value returned from `drupal_get_js()`. See `template_preprocess_html()`.

```
  $variables['head'] = drupal_get_html_head();
  $variables['css'] = drupal_add_css();
  $variables['styles'] = drupal_get_css();
  $variables['scripts'] = drupal_get_js();

```

I agree with @CLive about first trying to implement `hook_js_alter()`, which I expect to work since Drupal doesn't make difference between a page requested with `<iframe src="http://example.com/your/drupal/page" />` and pages requested trough a link, or directly from the user.

---
Tags: 7, theming, javascript
---


# Question
Title: How can I change URL of 'Add new comment' link on teaser?
Currently, I have a list of teasers and they have a comment count and an 'Add new comment' link.

That link goes to a dedicated comment page with a URL of the form "/comment/reply/19#comment-form".

However, I want it to go to the actual node which has the comment form at the bottom (eg. "/node/19#comment-form").

Maybe this can be done is the template.php or some other way. Any ideas would be greatly appreciated.

# Answer
> 1 votes
Go to the admin page for your content type

> /admin/structure/types/manage/page

and check `Show reply form on the same page as comments` under `Comment settings`.

If you look at comment\_node\_view() in the comment module, you can see where the comment link is added to teasers.

```
    if (user_access('post comments')) {
      $links['comment-add'] = array(
        'title' => t('Add new comment'),
        'href' => "comment/reply/$node->nid",
        'attributes' => array('title' => t('Add a new comment to this page.')),
        'fragment' => 'comment-form',
      );
    }

```

To alter the link you can use hook\_node\_view\_alter() in your module.

```
function MODULE_node_view_alter(&$build) {
  $node = $build['#node'];
  if (isset($build['links']['comment']['#links']['comment-add'])) {
    // Alter the 'Add new comment' link.
    $build['links']['comment']['#links']['comment-add']['href'] = "node/$node->nid";
    // Fragment is the '#comment-form' part of the url.
    $build['links']['comment']['#links']['comment-add']['fragment'] = 'comment-form';
  }
}

```

---
Tags: comments, navigation, nodes
---


title: Add fields to entity in module update

text:
# Question
Title: Add fields to entity in module update
I'm using Drupal 7 and I have a module which has working implementation of the Entity API module.

In my\_module.install file there is a hook\_schema() in which I defined table columns:

```
$schema['my_subscription'] = array(
'description' => t('The base table for subscriptions'),
    'fields' => array(
      'sid' => array(
        'description' => t('Primary key identifier for an subscription log.'),
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'email' => array(
        'description' => t('Email of a users subscription.'),
        'type' => 'varchar',
        'length' => '250',
        'not null' => TRUE,
      ),
      'name' => array(
        'description' => t('Full name of a user subscribing.'),
        'type' => 'varchar',
        'length' => '250',
        'not null' => FALSE,
      ),
    ),
    'primary key' => array('sid'),
);

return $schema;

```

In my\_module.module there is a hook\_entity\_info():

```
 /**
 * Implements hook_entity_info().
 */
function my_module_entity_info() {
  return array(
    'my_subscription' => array(
      'label' => t('Subscriptions'),
      'base table' => 'my_subscription',
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIController',
      'fieldable' => FALSE,
      'entity keys' => array(
        'id' => 'sid',
      ),
      'bundles' => array(),
      'module' => 'my_subscription',
    ),
  );
}

```

Records are created from the module like this:

```
    $values = array(
      'email' => $email,
      'name' => $name,
    );

    $subscription = entity_create('my_subscription', $values);

```

It's all working good, and there are couple of hundred subscriptions at the moment.

Now I need to expand the table with one more column, I'll call it 'test' for simplicity. I added a hook\_update\_N() to the my\_module.install, added

```
 db_add_field('my_subscription', 'test', array(
    'type' => 'varchar',
    'length' => 64,
    'not null' => FALSE,
  ));

```

and ran update.php which added the column as expected.

Now, when I try to pass new column value in the $values array like this

```
    $values = array(
      'email' => $email,
      'name' => $name,
      'test' => 'lorem ipsum'
    );

    $subscription = entity_create('my_subscription', $values);

```

record is made, but the newly added 'test' column has the value of NULL no matter what.

I suppose I need to tell Entity API that there is new field that needs to be populated as well, but I don't know how.

# Answer
> 3 votes
Using the API to add a column is the right thing to do, but it can't/won't update the code in your `hook_schema()` definition for you.

Drupal relies on that definition to map values to columns, so if you haven't explicitly declared the 'test' column, entity API doesn't know it exists, and so discards the value.

To solve, you should declare the new column in `hook_schema()`:

```
$schema['my_subscription'] = array(
  'description' => t('The base table for subscriptions'),
  'fields' => array(
    'sid' => array(
      'description' => t('Primary key identifier for an subscription log.'),
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'email' => array(
      'description' => t('Email of a users subscription.'),
      'type' => 'varchar',
      'length' => '250',
      'not null' => TRUE,
    ),
    'name' => array(
      'description' => t('Full name of a user subscribing.'),
      'type' => 'varchar',
      'length' => '250',
      'not null' => FALSE,
    ),
    'test' => array(
      'description' => t('Test field.'),
      'type' => 'varchar',
      'length' => 255,
    ),
  ),
  'primary key' => array('sid'),
);

```

After you clear caches things should start working.

---
Tags: entities
---


title: Drush can't find php

text:
# Question
Title: Drush can't find php
I am on a shared server and someone else has installed Drush previously. But as of now Drush does not work and throws the following error.

```
[root@vps1]# drush
/root/.composer/vendor/bin/drush: line 47: which: command not found
ERROR: can't find php.

```

The last thing I can remember was updating PHP (mod\_php) to 5.4.36 several days ago. It worked on 5.4.34, but PHP was recompiled during the update. Is this related? What do I need to do to tell drush about this 'new' php?

# Answer
> which: command not found

I don't really use Drush, but that looks like it's dying when it uses the "which" command to locate PHP... Drush is falsely reporting that PHP can't be found, but it's because the command it uses to look for it ("which") is not available.
> 3 votes

---
Tags: drush
---