# Question
Title: Why am I getting a JSON dump when saving a node?
I've read about this issue elsewhere and the primary culprit has been Views and the jQuery Update module...particularly having jQuery set to anything but v1.5. I'm getting the JSON dump when saving a node:

```
[{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"my_theme","theme_token":"yyYQcgn3UELRKecX6yTsTIV8lKutRmg3bBIpqbjACzE"}},"merge":true}]

```

I need jQuery 1.7 for an image rotator that I'm using and I found a patch for jQuery Update that allows you to set the version of jQuery for admin and and front-end so I have 1.5/1.7 set respectively and yet I'm still seeing this issue. I have confirmed that jQuery v1.5.2 is being loaded. I do see that jquery.form.min.js v2.69 is being loaded from the jQuery Update module along with jquery.cookie.js...could these be causing the problem?

This is the URL after clicking save and seeing the JSON dump:

```
http://mydomain.com/views/ajax?title=test&sitename=&type=All&uid_1=&status=All&vid=All&language=en&__utma=1.98635126.1382890057.1383491752.1384184897.6&__utmz=1.1382890057.1.1.utmcsr%3D(direct)|utmccn%3D(direct)|utmcmd%3D(none)&Drupal_toolbar_collapsed=0&Drupal_tableDrag_showWeight=0&has_js=1&SESS0e1269226b42fa1c68bd46a4609d8d90=YIk12tixVnxuF9Om77vikXdp7Il8oxAYukuDswiCJoI&__utmc=1&SESSe5a8c6595a55e490f10153304dbfc1ee=El6m94kqyvIsFjx_IDJkC6-nujMMHCed4oVBpPNnvXA

```

The error only seems to occur when I edit a node after searching for it on the **Find content** page. I'm using the Administration Views module as well.

All modules have been updated as well as core (7.23). I have the jQuery admin overlay disabled in an attempt to solve the problem. Is there anything else I can check/do to alleviate this issue?

---

Now that the issue is repeatable, I disabled jQuery Update and still received the same JSON dump, so that's not the issue :s

# Answer
> 4 votes
Thanks to MPD, this is how I solved it:

```
/* sites/all/modules/views/modules/node/views_handler_field_node_link_edit.inc */
if(strpos($this->options['alter']['query'], 'admin/content') !== FALSE) {
  $this->options['alter']['query'] = array('destination' => 'admin/content');
}

```

Basically if the destination contains admin/content, force it ONLY be admin/content, no additional parameters.

# Answer
> 6 votes
We were having this same issue on our company website. We have Administration Views installed, and use jQuery 1.8 as default version and 1.5 for admin pages.

As SomethingOn mentioned above, we were consistently seeing the JSON dump after filtering on the Find Content view, editing a node then saving. The URL paths all had '`views/ajax`' in the query string of the node edit URL; e.g.,

```
/node/XXXX/edit?destination=admin/content%3Fq%3Dviews/ajax%26title%3D%26type%3DAll%26author%3D%26status%3D0%26vid%3DAll

```

What I ended up doing was turning AJAX off (under Advanced \> Other \> Use AJAX) for the Find Content view (Administration:Nodes). This removed 'views/ajax' from the node edit paths and resolved the issue for us.

# Answer
> 4 votes
You may be having an issue with the Admin Views module that allows advanced filtering of nodes using Ajax on Drupal's Content screen.

Every time I've encountered the issue, I've filtered the list of nodes, and — after saving the changes — **get shown the JSON data dumped to the screen instead of being taken to the node view**.

It doesn't happen all the time, but often enough to be absolutely infuriating.

What worked for me was to disable Ajax for the **Administration: Nodes** view ("*Find and manage content*") at `/admin/structure/views/view/admin_views_node/edit`.

Here's what you need to do:

1. Login to Drupal
2. Go to **Structure \> Views**
3. Find the **Administration: Nodes** view
4. Under **Operations**, choose **Edit**
5. Click on the **Advanced** column section heading
6. Under **Other**, change **Use Ajax** from "Yes" to "No"
7. When prompted, **Save** the changes

Now, when filtering the list of nodes on the content screen, performing a query will reload the page instead of instantly showing the results via Ajax — it's a tiny tradeoff, but absolutely worth it to fix the problem.

With Ajax disabled, the Admin Views module modifies the query string it builds, which is where the problem originates.

Here's a simplified example using URL decoded parameters for readability:

> Using Ajax (Default):
> `/node/123/edit?destination=admin/content?q=views/ajax&title=Foo...`
>
> Without Ajax:
> `/node/123/edit?destination=admin/content?title=Foo...`

You'll notice the `q=views/ajax` parameter is absent from the non-Ajax node edit path, which seems to *fix* the issue.

You can easily test this hypothesis by removing the suspect parameter from the Ajax-enabled node edit destination path.

Tested with Drupal 7.3.4 using Administration Views 7.x-1.3 and jQuery Update 7.x-2.4 (set to jQuery 1.10).

# Answer
> 0 votes
The reason for the problem has already been found in previous answers and also all the workarounds proposed work.

I'd like to add that if you want your view to still work with ajax and also not loose the filters added in the destinations, there is a core patch available that I've tested on both on an nginx environment and on Azure that uses IIS.

I recommend applying this: https://www.drupal.org/node/1036962

---
Tags: 7, users
---


# Question
Title: Programatically create node + panel configuration?
Is there a way to programmatically create a panel node with a certain layout?

# Answer
> 0 votes
For some people, Panel Nodes is good enough. Depends on your circumstances.

The below will create a panel node with 2 column bricks layout and will use the In Place Editor (IPE):

```
$node = new stdClass();
$node->title = t('Home');
$node->type = 'panel';
node_object_prepare($node);
$node->language = LANGUAGE_NONE;
$node->status = 1;
$node->promote = 0;
$node->comment = 0;

$node->panels_node = array(
    'layout' => 'twocol_bricks',
    'css_id' => NULL,
    'pipeline' => 'ipe', // change this to "standard" if you don't want to use the In Place Editor (ipe)
);

// node_submit() populates the node with author UID and creation date
$node = node_submit($node);
node_save($node);

```

# Answer
> 0 votes
As suggested in the comments, it is better to use Panelizer rather than Panel Nodes.

Here is the code example how to a new display and attach it into panelized node:

```
  $node = is_numeric($node) ? node_load($node) : $node;
  $display = !empty($node->panelizer) ? $node->panelizer['page_manager']->display : FALSE;
  if ($display && !is_numeric($display->did)) {
    $new_display = panels_save_display($display);
    $node->panelizer['page_manager']->display = &$new_display;
    $node->panelizer['page_manager']->display_is_modified = TRUE;
    node_save($node);
    // $new_did = $node->panelizer['page_manager']->display->did;
    ctools_include('object-cache');
    ctools_object_cache_clear('panels_node_display_cache', $node->nid);
  }

```

where display should be created only once and re-used when possible.

Here is example how to attach such display into the existing node:

```
$node = node_load($nid);
$display = $node->panelizer['page_manager']->display;
$did = is_numeric($display->did) ? $display->did : NULL;
$display = panels_load_display($did);
$panes = $display->content; // Get this display's panes.

// Attach our new panel.
$uuid = ctools_uuid_generate();
$new_pane = panels_new_pane('node', 'my_node', TRUE);
$new_pane->uuid = $uuid;
$new_pane->pid = "new-" . $uuid;
$new_pane->panel = $region;
$new_pane->shown = 1;
$new_pane->configuration['nid'] = $nid;
$new_pane->configuration['build_mode'] = 'full';
$new_pane->configuration['link_node_title'] = FALSE;
$new_pane->configuration['links'] = FALSE;
$new_pane->configuration = array_merge($new_pane->configuration, $opts);
$display->panels[$region][] = $new_pane->pid;
$display->content[$new_pane->pid] = $new_pane;
$node->panelizer['page_manager']->display = $display;
$node->panelizer['page_manager']->display_is_modified = TRUE;
$result = node_save($node);
// Clear ctools caches.
ctools_include('object-cache');
ctools_object_cache_clear('panels_node_display_cache', $pnid);

```

---
Tags: 7, panels
---


# Question
Title: View in block doesn't sort by date whereas page does
I've got a 'archive' view in a block on my openblog drupal blog. In the view, the page view sorts ok, but in the block sorting by date doesn't work - it is always sorted by ASC.

# Answer
I figured out I needed to change the sort option inside the contextual filter.
> 1 votes

---
Tags: views
---


# Question
Title: How to get comment votes using raw sql query?
In a D7 site, comments are voted using rate module.

I'm wondering how to get the rating of all comments of 'story' content **using raw sql query**?

# Answer
> 1 votes
Here you are SQL to get the total vote count for widget type number for each comment od node type "story"

```
SELECT c.cid,count(v.vote_id) FROM votingapi_vote v JOIN comment c ON v.entity_id=c.cid JOIN node n ON n.nid=c.nid WHERE n.type='story' GROUP BY v.entity_id;

```

If you want to get the total numer of votes for all "story" nodes then:

```
SELECT c.cid,count(v.vote_id) FROM votingapi_vote v JOIN comment c ON v.entity_id=c.cid JOIN node n ON n.nid=c.nid WHERE n.type='story'

```

Or conditional for voting type like you did:

```
SELECT c.cid, count(v.value) FROM votingapi_vote v JOIN comment c ON v.entity_id=c.cid JOIN node n ON n.nid=c.nid WHERE n.type='story' and v.value_type='points' GROUP BY v.entity_id;

```

---
Tags: 7, database, rating
---


# Question
Title: Want a select option of a field saved in another form
i have a web form having following fields for sales department: client name(text field), quarter(select option), countries(select option), Annual fees(number), Monthly fees(number), setup(fees)......

now i want to create a form in which i can have a list of all the client saved by above form for management to allot resources for the client

please suggest any module required or coding which required.

need help urgently on this

# Answer
The module is Webform Views Select.

This question is related to this question.

Webform select option list from another submission data
> 0 votes

---
Tags: webforms
---


# Question
Title: How to redirect url in index.php?title=plip to a specific url like /my-page?
I develop a new drupal website to replace another website. So, in order to not loose my Google SEO from the old website, I create URL rewriting rules.

Everything is ok except for old urls beginning with index.php, like `index.php?title=plip`

I would like to redirect like this :

```
RedirectPermanent /index?title=plip http://new.drupal/my-page

```

It is normal because of this, in Drupal .htaccess file :

```
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{HTTP_USER_AGENT} !MSIE
RewriteRule ^ index.php [L]

```

But how can I do to get my redirection from urls like `index.php?title=plip` ?

I tried with the flag S to create an If-Else-like rule but it doesn't work.

Is there any chance to make it possible ?

# Answer
You should be able to make this work using the Rules module, as detailed below.

Looking at your path (= `/index.php?title=plip`) I would try to make the value (= `plip`) of the URL argument (= `title`) available as a new variable to the Rules module. To do so, you can use the Rules URL Argument module. Here is a quote about it (from its project page):

> ... provides two rules conditions based on URL arguments:
>
> * check if a URL argument is present.
> * compare the value of an URL argument.
>
> It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "*Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10*". Here is the relevant part of it:

> * add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
> * add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "`amount_from_url`".
>
> You will now be able to use the amount value as a variable "`amount-from-url`" for other actions in this rule.
> 0 votes

---
Tags: uri
---


title: Adding custom variable to $user object

text:
# Question
Title: Adding custom variable to $user object
I am using the following to add a custom field to a user with a custom variable.

```
global $user;

$account = user_load($user->uid);

$language = ($user->language) ? $user->language : 'und';

$edit = array(
  'field_favourite_football_team' => array(
    $language => array(
      0 => array(
        'value' => 'Manchester City',
      ),
    ),
  ),
);

user_save($account, $edit);

```

**Problem**: I can see the outputted value on module A but on module B, when I dump or print out that global $user, I can't see that field. Is there anyway to save that on a for global use?

# Answer
To add a field to the user entity, you need to visit the menu entry *Administration \> Configuration \> People \> Account Settings \> Manage Fields*. You can then define the field properties (including specifying whether it appears on the registration form or not) and customize how it is displayed on user pages.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Why does legend not appear when the first bar value is zero?
I have created a chart using Forena reports. I have added the legend by using the property frx:legend\_entries="legend" from the frx file. But when value of the first bar chart is zero or null, legend is not visible.

I am attaching the pictures below.

# Answer
I would check the results you'd get by using either of these special settings in the SVG Graph library:

If none of these options help, you might have discovered "some issue" (bug?) in the SVG Graph library.

A possible work around might also be that you can think of a way to replace the "zero or null" with "NULL".
> 0 votes

---
Tags: charts, forena
---


# Question
Title: Which variable to set for programmatically making a field required?
I am trying to do something like :

```
/**
 * Implements hook_update_N().
 */
function module_name_update_7002() {
 // Change field to required
}

```

To alter a field to make it required in production (where i can't access the backoffice).

Which variable do I have to set for doing so?

# Answer
> 1 votes
You may use following code to update your field

```
// Fetch an instance info array.
$instance_info = field_info_instance($entity_type, $field_name, $bundle_name);
// Change a single property in the instance definition.
$instance_info['required'] = TRUE;
// Write the changed definition back.
field_update_instance($instance_info);

```

# Answer
> 2 votes
Get the `form_id` of that form and write an alter function for it in your custom module.

```
function hook_form_form_id_alter() {
 $form['that_field_name'] = array(
   '#required' => TRUE,
    // add other features you want to add
 );
}

```

Follow the below link for more details: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_form\_FORM\_ID\_alter/7

---
Tags: entities, updating
---


# Question
Title: How filter node inside view block by even nid (or odd nid)
I have a view 2 blocks where I show some images and I'm trying to show the images with an even nid in the 1st block and the images with odd nid in the 2nd block

Do you guys have any idea if it's possible? and how?

# Answer
> 2 votes
@IsmaH answer is on the right track (use Regex for filtering `nid`). The problem in his answer is that this filter uses mySQL Regular Expressions \- this is why his proposed regex is not working.

This worked for me: `^.*[13579]$`

or this for even numbers: `^.*[02468]$`

**Notice:** no slashes at the beginning and end of the expression.

# Answer
> 1 votes
You should create two blocks.

Let's call them EvenBlock et OddBlock. On each one of them, visit the view editing page (back office).

On "FILTER CRITERIA" Clic on add and type "NID" in the search bar then select "Content: Nid". Then chose " Regular expression" and write a REGEX to match odd nid (I think "^\d\*\[13579\]$") for the OddBlock and even nid ("^\d\*\[02468\]$") for the EvenBlock.

Then save ^^

---
Tags: views
---


# Question
Title: How to get the URL of the entity reference node?
I'm building a site of course video，one course includes many video clips. I have created 2 content types, one is for the **Course** ,and the other is for the **Video**.

In the *course* content type, I set a field of entity reference to make a relation between course and video.

And then I create a view to display the video list on the video node page, it works. I wonder how can I add the link of the relative course node page on this video node page, how can I get the URL of the entity referenced course node page?

Any help would be great! Thanks in advance.

# Answer
> 1 votes
This is a very late answer, but hopefully it will help others looking to get the raw URLs for related content (especially if you're building a custom theme file for the view).

In the view:

1. Under "Relationships", add a `Entity Reference: Referenced Entity` relationship for the related field.
2. Under "Fields", add a `Content: Path` field
3. Set that field to use the relationship.
4. In the field settings, deselect label; under style settings, set the wrapper HTML to none.
5. Under "Rewrite Results", select "Rewrite the output of this field"
6. Use the replacement patterns to add just the `[path]` token. If you already have a separate Path field selected in the view, it may show up as `[path_1]` or a similar name.
7. Save & test the view.

# Answer
> 0 votes
> **Views Relationships** : Relationships are used to allow Views to bring in data that is associated with the data already available in the view.

**References**

---
Tags: entities, uri, views
---


# Question
Title: Alternative for the core statistics module that also includes pages created using Views?
I want to make a block, which shows the title of 10 most visited contents of my site and then display those as an ordered list.

My **pages are created using the Views module**. I tried to get it done using the core `Statistics` module. But it lists only Articles, Basic pages, or Content types which we have created. But it doesn't list pages which are created by Views.

Is there any contributed module for this?

# Answer
Have a look at the Visitors module. Here are some reports you get from it:

> * View pages that have recently been visited.
> * View pages that have been hit frequently.
> * View pages count per month, day of month, day of week, hour.
> * ...

Especially these reports should be what you're looking for (it includes hits for paths corresponding to a view):

* Top pages (table with columns Title, Path and nr of Hits). Here is an example of this report:
* Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor). Here is an example of this report:

If you follow any of the "details" links in the example above, you'll get something that looks as in this example:

Checkout the above (source) links to get an idea of which data are available.

The demo site contains some sample reports (charts) available to anonymous users also. Any visits to a Views related path will be reported in the **Recent hits** module. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors\_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module,
I hope this does not violate the site's policy on self-promotion.
> 1 votes

---
Tags: 7, views, nodes
---


# Question
Title: Ignore parts of the url or dynamically rewrite/alias the url
I am having a problem and have been wrecking my brain over it...

I feel I might ohh how did I not think of that moment once I find the solution...

Basically, what I need to do is:

For any url containing a string like "abcmytrack" show the page/view/drupal url that is before it in url and ignore the rest. So if I go to node/1/abcmytrack/some/other/stuff/abc then just show node/1, if I go to nodeone/alias/page/abcmytrack/some/other then again just show nodeone/alias, but keep abcmytrack/some/other in the url.

What am I trying to do: there is some referral tracking that I am trying to implement in the form of.

/some/drupal/url/\[trackid\]/some/other/track/ids/even /any/drupal/url/\[trackid\]/any/even/number/of/arguments /\[trackid\]/some/other/set/of/arguments

basically for any url with \[trackid\] which is a string. It should just ignore anything starting with \[trackid\] and load the path before it as if \[trackid\] was not there.

The result is that they basically get converted to a cookie, but the site is behind varnish and akamai caching so on production the code does not run and cookie is not written. Best option at the moment is to use JS to write a cookie, but problem is that adding /\[trackid\]/some/other/set/of/arguments to some of the site urls like aliased node paths, homepage, etc. breaks the pages.

It might be possible to do it as url rewrites in .htaccess but this is a last resort. I would like to see if there are other options I am not considering.

I have attempted to do use hook\_url\_inbound\_alter but it seems to do redirects and I loose the string from the url or otherwise it url encodes the string.

I have been wrecking my brain on this and cannot make this work. Granted I have some interesting requirements but it is one of those things that should be straightforward but it is not.

# Answer
> 0 votes
Subpathauto might do what you need even if it wasn't written for that exact use case. https://www.drupal.org/project/subpathauto

Subpathauto was written to handle the case where those extra arguments at the end of the string are meaningful and the first portion of the string is an alias. For that to function it must use hook\_url\_inbound\_alter (you were on the right track!) to look up the first section of the string.

Even if this module isn't an exact fit the code within it is a good starting point.

---
Tags: path-aliases
---


# Question
Title: Adding token in the views header and footer
I have created webform and displaying the webform submission data using views. In above the submission data, I mean in the header, I want to display the data from the webform body field. I tried using adding the "Global: Unfiltered text" and placing the token of the body field. But when I view the page, it is not showing the body content instead of showing the token itself.

Please tell me how to use token of the webform body field in the header without using "Global: PHP"?

# Answer
The "Use replacement tokens from the first row" checkbox is essential. It works with either the "Global: Text Area" option or "Global: Unfiltered text." Here is a screenshot of both working:
> 1 votes

---
Tags: webforms
---


title: Update header in hook_views_pre_render

text:
# Question
Title: Update header in hook_views_pre_render
I have seen how to update a views header via hook\_views\_pre\_render or hook\_views\_post\_execute here, but I am asking myself why one should go about this to update the value:

```
$view->display['page']->handler->handlers['header']['area_1']->options['content'] = $my_values;

```

While testing the same it seems to me that this is also working:

```
$view->header['area_1']->options['content']` = $my_values;

```

Is there any reason why I should/could not use this shorter code?

# Answer
The longer line would be helpful if you wanted to target only one display. For instance if there were a page display and block display and were both overriding the "master" and you only wanted to override the page display then the first line would be the way to go.

If the master display is what you want to override the second option is clearer.

FWIW, it might be better to simply have multiple displays that alternate whatever you're switching between in this hook. While quick, implementations of hooks like these are hard for a team to maintain over time.
> 0 votes

---
Tags: hooks, views
---


# Question
Title: How to create a menu block which is created by the active trail
I'm trying to create a sidebar block which contains secondary and tertiary menu links for a page which is in the main menu. I would also like to ensure that all children pages also have this same menu block.

I have been looking into the Menu Block module, but I don't think it will work for my situation. It looks like that module shows a subset of a particular menu, but it doesn't change per page. I don't want to create multiple menu blocks, just use one and have it change dynamically.

Is there a solution in the community for this?

# Answer
> 0 votes
Menu Block does cover your use case.

Go to `/admin/config/user-interface/menu-block`

You will see

> If a block is configured to use "the menu selected by the page", the block will be generated from the first "available" menu that contains a link to the page.

That screen is for administering which menus are available when the menu block is supposed to simply rely on the active trail to determine which menu to show.

---
Tags: blocks
---


title: Devel Module bogus output

text:
# Question
Title: Devel Module bogus output
I need help with the devel module. I'm outputting my objects/variables with `dpm($variables);` into my template.php and I get the same output on every page. It's pulling one of my views and showing it as the markup for every page. I'm running Drupal 7 with my own subtheme of the Omega project. Any ideas what's going on?

# Answer
What preprocess function or theme function override are you putting `dpm()` inside of? If you are inside of hook\_preprocess\_views\_view() then I would expect that you'd get the same results in on every page that the given view is on.
> 0 votes

---
Tags: theming, debugging
---


# Question
Title: Can I use multiple if statement in with with same validation?
Multiple if statement with similar validation will crash(WSOD) my website and I'm not sure if this an expected behavior, meaning what I'm doing is wrong. Or this is a bug, which I should fill into Drupal.org as bug.

Here is my code.

```
  {%  if page.footer_second and page.footer_third %}
       {% set col_class = 'six' %}

   {# If we have 3 columns#}
   {%  if page.footer_first and page.footer_second and page.footer_third %}
       {% set col_class = 'four' %}

   {# If we have 2 columns#}
   {%  elseif page.footer_first or page.footer_first or footer_third %}
        {% set col_class = 'eight' %}
   {% else %}
        {% set col_class = 'ten' %}
   {% endif %}

   <div class="{{ col_class }} columns">
     {{ page.footer_first }}
   </div>

    <div class="{{ col_class }} columns">
     {{ page.footer_second }}
     </div>
     <div class="{{ col_class }} columns">
         {{ page.footer_third }}
      </div>
    {% endif %}

```

If I remove one of my if statement my website will not crash (WSOD).

What I'm doing wrong ?

# Answer
Try separating the `set col_class` conditions from the display condition. Something like this...

```
{# first, set the col_class #}
{% if page.footer_second and page.footer_second and page.footer_third %}
    {% set col_class = 'four' %}
{% elseif page.footer_first and page.footer_third %}
    {% set col_class = 'six' %}
{% elseif page.footer_first or page.footer_second or page.footer_third %}
    {% set col_class = 'eight' %}
{% else %}
    {% set col_class = 'ten' %}
{% endif %}

{# then, display the columns #}
{% if col_class %}
   <div class="{{ col_class }} columns">
     {{ page.footer_first }}
   </div>
   <div class="{{ col_class }} columns">
     {{ page.footer_second }}
   </div>
   <div class="{{ col_class }} columns">
     {{ page.footer_third }}
   </div>
{% endif %}

```

You could (should?) probably set that `col_class` var in a preprocess hook to get all those ifs out of the template
> 1 votes

# Answer
What's jumping out at me is this line:

```
elseif page.footer_first or page.footer_first or footer_third

```

It's checking `page.footer_first` twice, and `footer_third`, which based on the code you've shown is not a valid variable, it should be `page.footer_third`. I'm guessing this should be more like:

```
elseif page.footer_first or page.footer_second or page.footer_third

```
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Change Omega4 Layout Based on Content Type via template.php
I want to set Omega4 Layout defaults based on Content Type. I am trying to use the following code, but the hook\_omega\_layout\_alter doesn't seem to use the $node variable. What am I missing?

I have already referenced Omega override simple-layout.tpl.php for content types but, once I try and and a switch statement based of $node-\>type it stops working.

What can I do to set the default Omega4 Layout based on Content Type using the hook\_omega\_layout\_alter function?

```
function THEME_omega_layout_alter(&$vars, &$layout) {
  $node = $vars['node'];
  switch ($node->type) {
    case "article":
        $layout = 'article';
        break;
    case "blog":
        $layout = 'blog';
        break;
    case "market":
        $layout = 'market';
        break;
    case "merchant":
        $layout = 'merchant';
        break;
    case "product":
        $layout = 'product';
        break;
    case "update":
        $layout = 'update';
        break;
  }

}

```

# Answer
> 1 votes
As per referenced question I would go with something like the following:

```
function THEMENAME_omega_layout_alter(&$layout) {
  if (arg(0) == 'node' && is_numeric(arg(1))
      && $node = node_load(arg(1))) {
        switch ($node->type) {
          case 'article':
            $layout = 'article';
            break;
          case 'blog':
            $layout = 'blog';
            break;
          default:
            $layout = 'default';
        }
   }
}

```

# Answer
> 1 votes
So this works for me...

```
function THEME_omega_layout_alter(&$layout) {

  $default = 'basic';

  $layout = $default;

  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    $node = node_load($nid);
    if (isset($node) && $node->type == 'page') {
      $layout = 'basic';
    }
    if (isset($node) && ($node->type == 'project_page' || $node->type == 'project_front')) {
      $layout = 'full-page';
    }
  }
}

```

Hope that helps someone. I personally think it is overkill to have to create new layouts in omega 4 to create minor changes... but hey, it is a quick and simple process!

---
Tags: nodes, theming
---


# Question
Title: how generate chart from Views Aggretation Plus
I created a table from webform submission data (group and compress) using Views Aggregator Plus

I would like to generate a pie chart from this table (industry as the label and turnover as the values).

Any hints to generate the pie chart would be appreciated.

# Answer
> 1 votes
Now I can do that,

(a) Exclude the Company field
(b) In the VAP setting, disable the summary sum in the footer
(b) Then use highcharttable module to create the pie chart.

# Answer
> 0 votes
You can achieve that using Charts module

> Transform Data into Information. Charts are a very good way to visualize a lot of data in a way that can be quickly digested.

It has a Views integration that Display the Views results as charts.

There are similar modules check Check Views Charts , Charts and Graphs

---
Tags: views, charts
---


# Question
Title: How do I make entity reference breadcrumbs?
I need to make entity reference breadcrumbs, with the first level being a node title, and the second level the title of a referred node.

As you can see in the image below, the nodes are different content types.

>

>

>

How do I make entity reference breadcrumbs?

# Answer
> 2 votes
**0)** download and enable the Entity Reference module

**1)** Go to eLesson content type Manage Fields.

**2)** Add a new field, call it "File Under" select Entity Reference as your type and use auto complete as your widget.

**3)** Select Node as your Target Type

* Target Bundles: checkmark Course only

## **4)** Go to your Forex Advantage node and edit it.

* For **File Under** type Beg, and select BEGINNERS COURSE.
* Save changes.

**5)** If you have any breadcrumbs module, disable it and uninstall it.

**6)** Since there is no configuration link, the only way to access the config is by going to it directly, so to go `www.yourwebsite.com/admin/structure/crumbs`

**7)** Under Disabled by default, drag up the entityreference.\* to Enabled.

* Save Changes

8) Go to your Forex Advantage node and now you should see

BEGGINERS COURSE \>\> Forex Advantage

---
Tags: breadcrumbs
---


# Question
Title: my urls are not replacing spaces with hyphens
I have url aliasing and clean urls. They are making the content have good urls, but for some reason it's not always rendering with hyphens. It leaves the spaces and breaks pages.

# Answer
> 0 votes
It's because you haven't updated the paths yet. So you need to go to the BULK UPDATE tab

Select CONTENT Paths and click on update.

---
Tags: path-aliases
---


# Question
Title: Media Youtube/Vimeo is being saved (or rendered) incorrectly as application/octet-stream
In Drupal 7, I am using panels/panelizer, media & media\_youtube.

I have correctly set up my view mode for the Video file type, and have selected that view mode using 'Rendered entity' in my pane settings.

The video is rendering as a link to sites/default/files/\[file youtube title\].

The above problem is arising with a file field on a node, that is being rendered with panelizer. When I add a video using a fieldable panel pane, it renders correctly (using the same view mode).

Any help you could provide would be much appreciated.

```
<div class="field-video">
    <span class="file">
      <img class="file-icon" alt="" title="application/octet-stream" src="/modules/file/icons/application-octet-stream.png">
      <a href="http://sl-header.site.io/sites/default/files/F%2016%20Fighter%20Pilots%20over.F%2016%20Fighter%20Pilots%20over" type="application/octet-stream; length=0">F 16 Fighter Pilots.F 16 Fighter Pilots over</a>
    </span>
</div>

```

# Answer
> 1 votes
I was having the same problem. The YouTube video was added correctly using the Media browser, the thumbnail was generated and it was even saved in the database correctly prior to saving the node.

After the node was saved, the entry in the database changed to application/octet-stream with a filename of the description twice, as well as a URI of public://

Something was altering the file details when the node was being saved. There weren't many options I could think of, and a quick review of the field settings revealed filefield\_paths was enabled for the field, which was altering the filename.

I disabled fielfield\_paths for the field and saved the node again, which resulted in the video displaying properly.

If you have filefield\_paths installed, try disabling it for the YouTube field only.

**Update:** This is resolved in the latest version of filefield\_paths. See: https://www.drupal.org/node/2576547

---
Tags: 7, media
---


title: How do I manually migrate a site?

text:
# Question
Title: How do I manually migrate a site?
So far I copied all files to a new directory.

Put the site into Maintenance Mode

Then I downloaded the database and imported it into a new database I created.

Truncated the following tables in the database

* cachetags
* cache\_\*

Updated settings.php with new database name, database user and password.

Currently the problem I am having is that I where I moved it to has a different path. Before I had my Drupal site set up at **/xyz/my\_drupal\_site** and now I have it set to **/abc/my\_drupal\_site.** I believe at this point I just need to update the database with the new path and I am not sure what needs to be updated (a global replace did not seem like good idea) or if there is an admin page that I can go to to take care of it.

I found instructions for Drupal 7 and they mentioned **/admin/settings/file-system** but it does not appear to exist in Drupal 8.

Also I want to make sure I am not missing anything else.

# Answer
> 0 votes
You likely don't need to change anything at all. Just move the folder and clear caches. Maybe you need to change the path in settings.php but only if you hardcoded it there before.

The instructions you found are for Drupal 6 and changing the path is no longer necessary unless you manually changed it to something else than the default location before.

---
Tags: 8, migrations
---


# Question
Title: Mask User url with dynamic temprorary user
Is there a module to mask user url with a temporary url which only last for a day and next time it generates another url for the same user?

I want to hide the users UID/username so that no two users can talk to each other but can view their profiles with a temporary url.

I checked with pathauto module but it generates a dynamic permanent url not a temporary ones.

Edit:- I used uuid\_link module for this and ran cron to generate uuid for users.

# Answer
It's very unlikely; this sounds like a very specific use-case that wouldn't need a dedicated project. You're going to have to implement your own custom module to pull this off.

You could go an aliasing route in a manner similar pathauto but that is likely to leave source paths open (e.g. **user/XXX**) to accessibility. A better approach is to create a simple module that:

1. Uses a hook\_cron() implementation to generate random hash to UID mappings periodically and storing them in custom table.
2. Implementing a `hook_menu()` to generate a dynamic path like `user/%random_hash` that maps the random hash paths in #1 to a user profile page (generated in the the same manner like `user/%user`)
> 1 votes

---
Tags: users, uri
---


# Question
Title: How to add external javascript on popup?
I have a splashify popup with links on the front page I want to set a cookie when the link is clicked but the external javascript I have written to set cookie is not working on popup.

How to add external javascript on popup?

# Answer
Please read Managing JavaScript in Drupal 7 there are various methods to add your own js. I assume you are using Drupal 7, this is important because in Drupal 8 adding js is different.

Also your js code needs to be like this

```
(function ($) {
  $( document ).ready(function() {
            // custom code goes here
  });
}(jQuery));

```
> 0 votes

---
Tags: javascript
---


# Question
Title: Cant find database table with node stickiness
I watched into Drupal 7 database, but i cannot find a table where nodes have stored their "sticky" value. Any ideas?

# Answer
> 0 votes
You can find field in node table as mention @clive

# Answer
> 0 votes
You need to look harder!

The `node` table has a `sticky` column, the data is stored there.

---
Tags: entities, database
---


# Question
Title: Why do my custom javascript modules not work anymore after updating bootstrap?
I have some custom javascript modules in my Drupal site that worked perfect. Yesterday I performed an update for bootstrap and unfortunately the custom javascript modules doesn't work. I get bellow errors to chrome developer tool console:

> Uncaught TypeError: $ is not a function

If you want to see the problem, you can here: http://www.neashmera.gr/

# Answer
> 5 votes
locate the javascript file where you have your error throwing code:

```
$(document).ready(function(){var weatherAPI='http://api.openweathermap.org/data/2.5/weather';var data={q:"Athens",units:"metric",appid:"b0847a3de80121926a9f428c35f611f8"};function showWeather(weatherReport){var iconURL='http://openweathermap.org/img/w/'+ weatherReport.weather[0].icon+'.png';var imgE=document.createElement('img');$("#open-weather").attr('src',iconURL);$('#temperature').html('Αθήνα '+ weatherReport.main.temp+'°');}
$.getJSON(weatherAPI,data,showWeather);});;function dateAndTime(){var date=new Date();var day;var dayOfMonth=date.getDate();var month;var h=date.getHours();var m=date.getMinutes();var s=date.getSeconds();switch(date.getDay()){case 0:day="Κυριακή";break;case 1:day="Δευτέρα";break;case 2:day="Τρίτη";break;case 3:day="Τετάρτη";break;case 4:day="Πέμπτη";break;case 5:day="Παρασεκυή";break;case 6:day="Σάββατο";break;}
switch(date.getMonth()){case 0:month="Ιανουαρίου";break;case 1:month="Φεβρουαρίου";break;case 2:month="Μαρτίου";break;case 3:month="Απριλίου";break;case 4:month="Μαϊου";break;case 5:month="Ιουνίου";break;case 6:month="Ιουλίου";break;case 7:month="Αυγούστου";break;case 8:month="Σεπτεμβρίου";break;case 9:month="Οκτωβρίου";break;case 10:month="Νοεμβρίου";break;case 11:month="Δεκεμβρίου";break;}
if(h<10){h="0"+ h;}
if(m<10){m="0"+ m;}
if(s<10){s="0"+ s;}
var time=h+":"+ m+":"+ s;$('#time-now').html(time);setTimeout('dateAndTime();','1000');var myDate=day+', '+ dayOfMonth+" "+ month;$('#date-now').html(myDate);return true;};

```

then wrap it with

```
(function($) {
..
})(jQuery);

```

or replace the *$* sign with *jQuery*

---
Tags: javascript, updating, theming
---


# Question
Title: How to validate a form against a custom user profile field?
I unsuccessfully tried https://www.drupal.org/project/rules\_forms for forms validation so I am writing my own little validation module.

Basically, on node creation I want a **validation against a custom user profile field** (machine name: field\_points). When the user enters on node creation more points then he has on his profile, an error message should appear.

Static validation against a number works just fine, but how can I access custom fields of the user object? Using devel, for some reason they don't show up in dpm($user).

```
function custom2_form_contenttype_node_form_alter(&$form, &$form_state, &$form_id) {
drupal_set_message("Form ID is : " . $form_id);
dpm($form);
//$form['field_points']['und']['0']['value']['#default_value'] = 164;
$form['#validate'][] = 'custom2_form_contenttype_node_form_validate';
}

function custom2_form_contenttype_node_form_validate($form, $form_state) {
global $user;
dpm($user);
$profilePoints = $user->field_points;
$enteredPoints = $form_state['values']['field_points']['und']['0']['value'];
dpm($form['#validate']);
dpm($form_state);
if ($enteredPoints > $profilePoints) {
   form_set_error('field_points', '"You can only spend" .     $profilePoints . " //points."');
   }

```

}

EDIT: uploaded devel user screenshot

# Answer
> 0 votes
Try this in your validate function

```
global $user;
$user_fields = user_load($user->uid);

$profilePoints = $user_fields->field_points['und'][0]['value'];

```

I hope this will work

# Answer
> 0 votes
Try with this code it is helpful for you

```
<?php

function mymodule_form_alter(&$form, &$form_state, &$form_id) {
      if ($form_id == 'form_id') {
    $form['#validate'][] = 'my_validation';
                                      }
                                                                }

function my_validation($node, $form, $form_state){

    if (!isset($form_state['values']['field_text']['und'][0]['field_text']['und'][0]['value']))
    {
        form_set_error('Text', 'Select text');
        }

}

```

---
Tags: 7, users, forms
---


title: How to create a custom event in rules?

text:
# Question
Title: How to create a custom event in rules?
I need to create an custom event for an action to be triggered in the Rules module.

Custom event is after completing the checkout process the page will be redirected to confirmation page. I need to trigger an action if the page is redirected to the confirmation page.

I need to check if the user has on the confirmation page like /payment-confirmation then i need to trigger an action.

# Answer
Let's assume that the Rules action that you want to trigger is to just set a Drupal message like "**Rules action related to payment confirmation**". But this action should only be triggered when "Viewing the content" located at your confirmation page, which has a path like "`/payment-confirmation`".

To get this to work, use the rule below (in Rules export format, just import it in your site and check the results of it):

```
{ "rules_extra_action_about_payment_confirmation" : {
    "LABEL" : "Extra action about payment confirmation",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "/payment-confirmation" } }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Rules action related to payment confirmation" } } ]
  }
}

```

The rule above should be close to what you're looking for, except from these further refinements:

* Replace the rules ***Action*** by your own rules "action" (which you didn't specify).
* If you want your Rules Action to be performed **before** your confirmation page is actually shown, then replace the Rules ***Event*** (= `"ON" : { "node_view" : [] },`) with `"ON" : { "init" : [] },` (= "Drupal is initializing").
> 1 votes

---
Tags: rules, actions
---


# Question
Title: Feature automatically reverts on cache clear
I have an issue with Features which contains a view. If I update the feature and then clear the Drupal cache, the view will revert to the configuration in the updated feature.

My understanding was that a feature would not be reverted unless it is specifically made to (e.g. manually revert the feature). Is this a wrong assumption?

Here is more information of what I have tried. On server A, I modify a view which is contained in a feature. I then update the feature so that it contains the modification to the view. I then commit the updated feature to git.

Now, I log into the other server, and pull in the changes from git (e.g. bring in the updated feature). If I go to the feature's admin page I can now see that it is overridden (so far so good).

I then clear the drupal cache (e.g. via performance page or drush cc all). If I now check the feature status, it is set to default and the view has also been modified.

Why would the feature and the view change on cache clear if I haven't specifically reverted the feature?

**UPDATE**: It seems the issue only occurs if the status of the feature on Server B was 'default' prior to deploying the updated feature. See following scenarios:

**SCENARIO 1**: Feature on Server B is in 'default' state. Updated feature from Server A is deployed to Server B. The features admin page shows on Server B now shows the feature to be "Overridden" (expected given we have deployed updated feature).

If I now clear cache, the feature's status has now changed to 'default' and examination of the relevant view shows that the changes in the updated feature have been applied.

**SCENARIO 2**:

Feature on Server B is already in 'Overridden' state, due to a local change I made to the view. The updated feature from Server A is deployed to Server B. The features admin page shows feature on Server B to be "Overridden" (expected given we made local changes to relevant view).

If I now clear cache, the feature is still shown as "Overridden" and the relevant view has not been altered.

As you can see in SCENARIO 1 the updated feature is automatically reverted on cache clear, but in SCENARIO 2 it is not.

# Answer
This is not supposed to happen, a cache clear should not have any effect on overridden features.

I'm just guessing here, but have you tried to uncheck the option 'Rebuild features on cache clear' on the features settings page (admin/structure/features/settings)?

Rebuild and revert are two different things where rebuild should leave the overridden features as they are, but who knows? It's worth the try.
> 1 votes

---
Tags: views, features
---


# Question
Title: How do I limit the node count of a content type to one per user?
I have a custom content type. I would like to limit that each user can only create one node of this content type. How can I achieve this?

# Answer
You can use the Node Limit module for that:

> The Node Limit module allows administrators to restrict the number of nodes of a specific type that roles or users may create. For example, if a site has an "Advertiser" role that can create "advertisement" nodes, then the node limit administrator can restrict all users in that role to a specific number of nodes. He may also restrict users on a per-user basis.
> 2 votes

---
Tags: nodes
---


# Question
Title: Is performance affected on local server?
I have my drupal on a server that doesnt have access to internet.

Does this hurt the preformance?

I am getting this error on the status report :

> "HTTP request status Fails"

If it does, how can I overcome this?

Thanks

# Answer
> 0 votes
You should be able to set up Drupal on your local machine without an Internet connection, where you can do most of your development work. See this post on Drupal.org for info about setting this up properly. You shouldn't be getting any HTTP errors, I'd check to make sure you don't have any some external images, files or other resources (like feeds) embedded which would require the browser to fetch from www.

---
Tags: performance
---


# Question
Title: How can I add multiple field collections based on a reference on a new node
I am trying to figure out how can I add multiple field collections to a node when a user starts filling out a node.

Here is how my nodes are basically set up:

```
Color Card Content Type:
 - id
 - name
 - colors_term_reference(multi select)

Style Content Type:
 - id
 - color_card_node_reference (select)
 - color_images_collection (unlimited field collection)
   - color_term (single select)
   - image

```

When a user starts filling out the node form, I want the field collections to get created and all the colors that were chosen in the color card get preselected.

So ideally if color has the following colors: red, blue, and green, when a user starts filling out my style node and chooses that color card the field collection would have red, blue, and green preselected and they would only need to upload the images.

```
Color Card:
- id: 1
- name: Cool Colors
- colors_term_reference:
  10 (red)
  17 (blue)
  38 (green)

Style:
- id: 1
- color_card_node_reference: 1
- color_image_collection:
  0:
    color_term: 10,
    image:
  1:
    color_term: 17,
    image:
  2:
    color_term: 38:
    image:

```

# Answer
I ended up using the same approach as How to create (& pre-populate) multiple “field collection” fields on an ajax call.

Use hook\_form\_FORM\_ID\_alter() to the node you need the functionality at.

```
// Add ajax callback when a node reference is entered or changed.
$form['field_node_reference'][LANGUAGE_NONE][0]['target_id']['#ajax'] = array(
  'callback' => 'your_module_ajax_rebuild_form',
  'wrapper' => 'field-collection-values',
);

```

Create ajax callback.

```
/**
 * Ajax callback, rebuilds and returns the field_collection_colorizer
 * element.
 */
function your_module_ajax_rebuild_form() {
  // Get Field collections and children.
  $field_collection_colorizer = &$form_state['field']['field_collection'][LANGUAGE_NONE];
  $field_childs = &$form_state['field']['field_collection'][LANGUAGE_NONE]['entity'];

  // Found that I had to set item and items count in order for this to work.
  $field_collection_colorizer['item_count'] = $options_count;
  $field_collection_colorizer['items_count'] = $options_count;

  // Create any new field collection instances if needed.
  for ($i = 0; $i < $field_collection_colorizer['item_count']; $i++) {
    if (!isset($field_collection_colorizer['entity'][$i])) {
      $field_collection_colorizer['entity'][$i] = entity_create('field_collection_item', array('field_name' => 'field_collection_colorizer'));
    }
  }

  // Reset the input to make sure cached version of the form insn't returned.
  $form_state['input'] = array();

  // Rebuild the form.
  $form = drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);

  // Return the field you want to replace.
  return $form['field_collection_colorizer'];
}

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Check, anywhere during a session, if a logged in user has previously logged in
There are a number of properties on the global $user object https://api.drupal.org/api/drupal/developer%21globals.php/global/user/7

But I can't figure out how to see if a logged in user has ever previously logged in, or if this is his/her first session. When logged in, the $user-\>access, $user-\>login, $user-\>timestamp values all seem to point of the current session.

I can set a cookie and check for that cookie myself. But I suspect I'm just missing something Drupal already has ?

# Answer
A cookie would work. Another way is to add a field to the user entity that you can check that field first to see if it's empty, and then modify it with a Rule, triggered by the log in action
> 1 votes

---
Tags: 7, users, sessions
---


# Question
Title: Can visit the page but can't see the tab it should have
Not sure how to word it and I am sure plenty of other people have run into this problem, so I apologize in advance.

I have the following code:

```
 function content_type_message_menu() {
  $items = array();

  $items['admin/config/content/authoring/messages'] = array(
    'title' => 'Messages',
    'description' => 'Configure what messages are displayed for the differing content types and who has permission to see them.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('content_type_message'),
    'access arguments' => array('administer content type messages'),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/config/content/authoring/messages/settings'] = array(
    'title' => 'Settings',
    'description' => 'Configure who has permission to see them.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('content_type_message_roles_form'),
    'access arguments' => array('administer content type messages'),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

```

The second page I can access when I go to `'admin/config/content/authoring/messages/settings'` but I do not see a tab on the first page (`'admin/config/content/authoring/messages'`) to go to this second page. Anyone know what I might be doing wrong?

# Answer
Drupal doesn't show tabs when there is just a tab defined or visible for the currently logged-in user (which includes the case users don't have the permission to see other defined tabs).
If you look at what Drupal does, for each node there is node/%node/view and node/%node/edit; when users don't have the permission to edit a node, they don't see any tab, in the node page.

See the following screenshot, taken from drupal.org at https://www.drupal.org/node/5, using an account with the permission to edit the node.

>

You see the *View*, *Edit*, *Outline*, and *Revisions* tabs.

Compare it with the screenshot taken using an anonymous user account, for the same page.

>

You don't see any tab, but the screenshot is for the *View* tab. In fact, if you try accessing https://www.drupal.org/node/5/view as anonymous user, you would see the same as in the last screenshot.
> 1 votes

# Answer
So it seems I was getting this issue AGAIN when starting up a brand new project. So I tried something unconventional. I just created a third page...

```
$pages['admin/config/content/messages/roles1'] = array(
    'title' => 'Roles that can see Messages',
    'description' => 'Set roles that can see the messages',
    'page callback' => 'what',
    'access arguments' => array('Administer content types '),
    'type' => MENU_IS_LOCAL_TASK,
  );

```

... THEN it like for some reason hit drupal upside the head and picked up the third page and the 2nd page and made the appropriate tabs on the first page.

So the answer it seems is, if you have been clearing cache and you know what you are doing is 100% correct (which was my case) then just make another page, clear that cache and watch it pickup the page you intended for.
> 0 votes

---
Tags: routes
---


title: Overriding node output

text:
# Question
Title: Overriding node output
I'm currently creating a website on Drupal 8, even if it's still in RC3.

I've been swimming in the sauerkraut since few days now and I still cannot figure it out how to override node output as I could do in Drupal 7. Because Drupal 8 is not as used as Drupal 7, it's tough to find answers on Google.

So, I'd like to do the following in my twig file(s):

```
<div class="images">
  <ul>
    <?php if ($field_images) { ?>
    <?php
      $img_url = $field_images[0]['uri'];
      $img_alt = $field_images[0]['alt'];
      $img_title = $field_images[0]['title'];
    ?>
    <li>
      <a data-lightbox="galleryWrapper" href="<?php print image_style_url('lightbox', $img_url); ?>">
        <img src="<?php print image_style_url('album_thumb', $img_url); ?>" alt="<?php echo $img_alt; ?>" title="<?php print $title; ?>" class="media" />
      </a>
    </li>
    <?php } ?>
  </ul>
</div>

```

I've seen that I could, as in Drupal 7, override a *template* file with a specific filename, such as: *"field--node--field-images--gallery.html.twig"*.

The thing is that I don't know where to create my variables that will be available for my *twig* files (*MYTHEME.theme*?).

I've already tried this in "*field--node--field-images--gallery.html.twig*":

```
{% if multiple %}
  <div{{ attributes.addClass(classes, 'field__items') }}>
    {% for item in items %}
      <div{{ item.attributes.addClass('field__item') }}>
        {#  Before was {{ item.content }} instead of the 5 following lines  #}
        {% if item.content.url %}
          <a href="{{ item.content.url }}" class="lightbox" data-lightbox="gallery">{{ item.content.image }}</a>
        {% else %}
          {{ item.content.image }}
        {% endif %}
      </div>
    {% endfor %}
  </div>
{% else %}
  {% for item in items %}
    <div{{ attributes.addClass(classes, 'field__item') }}>
      {#  Before was {{ item.content }} instead of the 5 following lines  #}
      {% if item.content.url %}
        <a href="{{ item.content.url }}" class="lightbox" data-lightbox="gallery">{{ item.content.image }}</a>
      {% else %}
        {{ item.content.image }}
      {% endif %}
    </div>
  {% endfor %}
{% endif %}

```

I've tried to access to "url" with {{ item.content.url }}, because {{ content }} seems to call "image-formatter.html.twig", which contains the following:

```
{% if url %}
  <a href="{{ url }}">{{ image }}</a>
{% else %}
  {{ image }}
{% endif %}

```

As you can imagine, it doesn't work.

And, that's another issue, but I've already tried to *dump* variables but I got this famous WSOD (White Screen Of Death). So, that's very difficult to know what this $variables contains.

# Answer
The fields you are looking for are under '#item', for example:

```
 {{ item.content['#item'].title }}

```

To set variables for twig put a theme\_preprocess\_field() function in MYTHEME.theme.

To examine variables use kint (this is in the devel module):

```
{{ kint() }}
{{ kint(items) }}

```
> 2 votes

# Answer
(Crosspost with 4k4, slightly different approach and some background info, so still posting)

Yes, preprocess still exists and yes, you can put it in your yourtheme.theme file just like in D7. See template\_preprocess\_field() in theme.inc for the default logic.

Also see `FormatterBase::view()` for all the data that is passed to the field template. You can see entity and items in there. Those are basically the raw data.

Accessing them directly in twig is a bit complicated due to the #, You'd need something like {{ elements\['#items'\].0 }}, you could use preprocess to make that available (note that top-level items is created in the preprocess and something else.

For the url, you should actually be able to access it through content with a similar syntax as above, `{{ item.content['#url'] }}`.
> 2 votes

---
Tags: 8, theming
---


# Question
Title: Need to print all the function calls Drupal makes
I need to examine all the function calls Drupal makes during it loads a page (even if there are no errors). I guess debugging software can do this but I would also like to know a way to do this without xdebug etc.

I found this link: https://drupal.stackexchange.com/questions/545/how-to-debug-drupal but I'm not sure where to put for example this code:

```
<?php
$bt = debug_backtrace();
foreach ($bt as $key => $value) {
  if ($key == 0) {
    continue;
  }
  unset($bt[$key]['args']);
  unset($bt[$key]['object']);
}
drupal_set_message(str_replace('    ', '    ', nl2br(htmlentities(print_r($bt, TRUE)))));
?>

```

# Answer
> 4 votes
I would recommend using Xdebug as opposed to any other methods.

Xdebug can easily be installed and then all you have to do is enable profiling and navigate around your site.

Not only does it list all function calls but it counts how many times each is called during a request and also times the function call, so you know **exactly** where to look to resolve bottlenecks.

The results can be viewed using Webgrind (browser-based) or KCacheGrind (KDE/linux), amongst others.

This is more efficient because you are not tampering with the code and littering it with debug statements.

# Answer
> 1 votes
The number of function calls during a single page view can be quite a lot. I don't know the number, but my guess is that it's several thousand. If you want to log all of this data, you shouldn't post it to the screen, but instead write it in a file, like the `dd` function that the `devel` module has.

If you want to log all function calls, you should start by the end, that last function that is called in a drupal page. One of the last functions where you could start is `drupal_page_footer`. You can add the `debug_backtrace` in that function.

Then you would have to go through all the functions and add `debug_backtrace` for all the functions that those functions call. Then you would have to go through all the new functions listed in the `debug_backtrace` you just added and repeat the above step until you or your computer chokes.

It's possible to do this, but to get anything useful you will need a profile tool, which can do all of this in seconds instead of hours. This is where computers excels: **recursion**.

# Answer
> 0 votes
If you need to print all the function calls (e.g. just their names separated by comma), try:

```
print implode(', ', array_column(debug_backtrace(), 'function'));

```

Note: `array_column()` is part of PHP \>=5.5.0

---
Tags: debugging
---


# Question
Title: Hide price and add to cart form for purchased product
I'm using Drupal 7 and Drupal Commerce.

I need to hide the price and the add to cart form when a product was bought by the current user.

I found the solution for the add to cart form, but not for the price.

I imagine that it is necessary to use the function hook\_entity\_view\_alter, but my code doesn't work. Here he is :

```
function mymodule_entity_view_alter(&$build, $type) {
  $purchased_product = mymodule_get_users_purchased_products();

  $line_item = commerce_unit_price[LANGUAGE_NONE]['0']['amount'];
  $product = commerce_product_load($line_item->commerce_product[LANGUAGE_NONE][0]['product_id']);

      if (in_array($product->product_id, $purchased_product)) {
        $build['product:commerce_price']['#access']=FALSE;
      }
    }

```

Function for load the purchased product :

```
mymodule_get_users_purchased_products() {
      $purchased_products = &drupal_static(__FUNCTION__);

      if (!isset($purchased_products)) {
        global $user;
        $query = db_select('commerce_order', 'corder');
        $query->join('commerce_line_item', 'li', 'corder.order_id = li.order_id');
        $query->join('field_data_commerce_product', 'prod', 'li.line_item_id = prod.entity_id');
        $query->condition('corder.uid', $user->uid, '=')
              ->condition('corder.status', 'completed', '=')
              ->fields('prod', array('commerce_product_product_id'));
        $result = $query->execute();

        $purchased_products = array_unique($result->fetchCol());
      }

      return $purchased_products;
    }

```

Do you know where from comes the problem?

Thanks for your help

# Answer
Here's a function that you can use to accomplish your goals. I tested it with Commerce Kickstart 2.

```
function MYMODULE_entity_view_alter(&$build, $type) {
  if ($build['#view_mode'] != 'full' && $build['#entity_type'] != 'node' || empty($build['field_product'])) {
    return;
  }

  // Load your purchased products.
  $purchased_products = array('HAT2-BLK-OS');

  foreach ($build['#node']->field_product[LANGUAGE_NONE] as $product_data) {
    $products[] = $product_data['product_id'];
  }

  $all_products = commerce_product_load_multiple($products);
  if (count($all_products) == 1) {
    $product = reset($all_products);
    if (in_array($product->sku, $purchased_products)) {
      $build['product:sku']['#access'] = FALSE;
      $build['field_product']['#access'] = FALSE;
    }
  }
}

```

Let's step through it. The first thing that happens is that you need to get your SKUs that you'll base your hiding off of. Just replace this line with a line that loads the products that the current user has purchased.

```
  $purchased_products = array('HAT2-BLK-OS');

```

Then, you load the products:

```
  foreach ($build['#node']->field_product[LANGUAGE_NONE] as $product_data) {
    $products[] = $product_data['product_id'];
  }

```

If you just have a single product per page, you could grab a single `product_id`.

Then you need to load your products.

```
  $all_products = commerce_product_load_multiple($products);

```

I'm assuming a single SKU per product here, so it does `reset($all_products)` to grab the first one. Then, just do a check to see if that product's SKU is in the array of SKUs that were already purchased:

```
    if (in_array($product->sku, $purchased_products)) {
      $build['product:sku']['#access'] = FALSE;
      $build['field_product']['#access'] = FALSE;
    }

```

If it, then hide the sku (in `product:sku`) and the add to cart form (in `field_product`). The result will then be this:

As opposed to this:
> 1 votes

---
Tags: 7, theming, commerce
---


# Question
Title: creating "live search" from database text field in Profile Content field Drupal 6
I'm new to Drupal development. I have inherited a Drupal 6 site. I would like to add to the content-profile fields a "live search" text field that will give the user options from a database based on the letters typed. I already have the following:

1. Database
2. Profile field with onkeyup function in the .js file.
3. Function that gets the correct values from the database
4. any number of tutorials that explain how to use ajax for connecting the onkeyup function and the database query.

What I don't understand is how to put the search results into the "allowed values" of the text field? All the examples define an additional \< div \> to put the results in. Here it's part of the text field. What code should be in the allowed values so that it will show the correct values? Where to put the retrieved values?

Any help would be appreciated!

# Answer
> 0 votes
You're asking how to make an Ajax search request from a textfield.

I'm not going to answer your exact question but you need some javascript to fill in the results from your sql query into the search field. Here is an example which fills in an HTML `<options>` list from a Drupal sql search:

```
jQuery(function($) {

  $('#edit-field-survey-program-und option:gt(0)').remove();
  $('#edit-field-survey-program-und').attr('disabled', 'disabled');

  // When a country is selected. Find the Academic Programs within that
  // country from an SQL lookup. Then fill in the options values and
  // make that options list enabled for the site visitor.
  $("#edit-field-survey-country-und").click(function() {
    var selected_country = $("#edit-field-survey-country-und").val();
    if (selected_country != '_none') {
      // Do our SQL lookup from a service enpoint with a search parameter.
      $.ajax({
        type:'GET',
        url: '/eap-ajax/eap-country-programs/' + selected_country,
        data: '',
          success:function(data){
          // Replace values of target form element with found results.
          // Enable for enduser.
          $('#edit-field-survey-program-und option:gt(0)').remove();
          $.each(data, function(key, value) {
            $('#edit-field-survey-program-und').append(
              '<option value="' + key + '">' + value + '</option>'
            );
          });
          $('#edit-field-survey-program-und').removeAttr('disabled');
        }
      });
    }
  });
});

```

The above example is the same 3 pieces for any AJAX thing.

1. Make a click event listener function
2. Do your SQL business logic
3. Inject your results somewhere back into the page

For a full writeup feel free to see my more complete writeup: http://blog.arvixe.com/drupal-ajax-autocomplete-dependant-form-elements-using-jquery/

I suggest googling how to fill in results to an `<input>` text field using jQuery.

---
Tags: users, 6, database, ajax
---


# Question
Title: Where is the email New release(s) available coming from
With Drupal 7, we are getting some emails that say **"New release(s) available for name of site"** , but they are going to someone who doesn't work here any more, and they are bouncing back to me.

Where are these emails coming from, they seem to be from drupal but I can't find where this is configured.

Thanks!!

# Answer
It's configured on the "Available updates" settings page at /admin/reports/updates/settings:
> 2 votes

# Answer
Remove email address present at **admin/reports/updates/settings**.
> 1 votes

---
Tags: notifications
---


# Question
Title: Add custom image styles to media browser display options
I'm using the Media module in a project.

I've defined several custom image styles and would like to add them to the list of display options in the media browser. However, I can't find a way to do so.

Reading through issues similar to mine, I found this thread which suggested using hook\_styles\_default\_presets() to render the options. But even with clearing caches, I'm unable to get my custom image styles to display as formatting options.

# Answer
> 2 votes
This tutorial ended up answering my question: http://figure-w.co.uk/drupal-how-do-you-make-a-new-image-style-appear-in-the-media-browser/

* Install the Entity View Mode module
* Add new view modes
* Configure display settings for view modes

---
Tags: media
---


# Question
Title: Print module and missing breadcrumbs of Crumbs modules
I use crumbs module to maintain custom breadcrumbs. Also, I use print module to maintain printer's friendly pages.

The breadcrumbs works perfectly in the ordinary pages. However, using print module leads to missing section in breadcrumbs.

For example:

mysite.com/sports/the-winner-cups return breadcrumbs: Home -\> sports -\> the-winner-cups

but mysite.com/print/sports/the-winner-cups

returns Home -\> the-winner-cups

The following is a screen shot of active rules weigts of Crumbs module:

# Answer
> 1 votes
It seems the router path for print/.. pages is always "print". See the print\_menu() hook implementation in print.module.

You could write new Crumbs plugins for these paths (one for parent-finding, another for title-finding), with a logic somehow like this:

* The parent path for "print/a/b/c" is "print/" + the parent path of "a/b/c".
* The breadcrumb link title of "print/a/b/c" is the same as for "a/b/c".

The plugin could live in a custom module, or in the print module, or in the Crumbs module (patch welcome).

(This still needs some tinkering and experimentation. I'm afraid if I put it all into this answer, then I can as well just write the plugin myself and add it to the module - sorry..)

---
Tags: 7, breadcrumbs
---


# Question
Title: In hook_user_login is there a way to know if this is the first time the user has logged in?
I'm overriding hook\_user\_login to redirect users to a specific page when they log in. The problem is I'm using the verification email setting on registration which requires the user to set their password on first login, but I redirect them so some users aren't able to login the 2nd time to the site.

Is there something I can check in hook\_user\_login that will tell me if this is the first time the user has logged into the site?

# Answer
> 7 votes
I made a test on my test site, using the following code.

```
function code_testing_user_login(&$edit, $account) {
  watchdog('code_testing', 'User name: %name, user access: %access, user login: %login', array('%name' => $account->name, '%access' => $account->access, '%login' => $account->login), WATCHDOG_DEBUG);
}

```

I then created a test user, and logged in with that account. The code I wrote output the following message:

> User name: test, user access: 0, user login: 1340038458

`$account->login` cannot be used because the user already logged in, when `hook_user_login()` is invoked. The only way to see if the user already logged in is to check `$account->access`.

```
function mymodule_user_login(&$edit, $account) {
  if ($account->access == 0) {
    // The user has never logged in before.
  }
}

```

# Answer
> 7 votes
Check for $account's access property. It is a timestemp the user logged in previously.

It should be other than a valid time stamp in case to be a first time login.

```
function MODULE_user_login(&$edit, $account){
debug($account->access);
}

```

# Answer
> 1 votes
This does not answer your question, but if I understand your scenario, this would help: don't do the redirect if the user logs in on the pass\_reset page

```
function MYMODULE_user_login(&$edit, $account) {
    if (empty($_GET['destination'])) {
        if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {

                drupal_goto('somewhere');
        }
    }
}

```

---
Tags: 7, users
---


title: Accessing product price in template.php

text:
# Question
Title: Accessing product price in template.php
So I am using hook\_form\_alter to alter the add-to-cart button for my Ubercart pages. See here:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ( !empty($form['nid']) ) {
    $node = $form['nid']['#value'];
  }
  else {
    $node = 0;
  }

  if (($form_id == 'uc_product_add_to_cart_form_'.$node) and ($form['node']['#value']->type =='product')){

    hide($form['actions']['submit']);

    $form['button'] = array(
      '#prefix' => '<button type="submit" id="edit-submit-'. $node .'" name="op" class="node-add-to-cart btn btn-cart">',
      '#suffix' => '</button>',
      '#markup' => 'Buy for: ',
      '#weight' => 1,
    );
  }
}

```

This works great. Except, in my form\['button'\] array, want to change the button markup to something like: 'Buy for: $10'.

How can I access the node's list and selling price so that I can use it in the markup of the button?

# Answer
> 1 votes
The node object is made available through the `$form` array in `$form['node']['#value']`. You can find list & sell price through the `$form['node']['#value']->list_price` & `$form['node']['#value']->sell_price` properties.

---
Tags: 7, theming, ubercart
---


# Question
Title: How to create Select list on Entity forms with changeable list of key values?
I would like to create a field for my Entityform same as 'Select list' with ability to change its values after the data is submitted.

Currently when I am trying to change the default values of 'Select list' it gives me the error:

> Allowed values list: some values are being removed while currently in use.

or:

> There is data for this field in the database. The field settings can no longer be changed.

I believe this behaviour should be different than for Content type, as when using Entityform I don't care for already submitted data (as it's something that suppose to be submitted only once)?

### Question

How do I create a Select list widgets on Entity forms where I am able to change its key values once the data has been submitted?

How do I fix or workaround that Drupal limitation, or I should use a different solution/module instead or write my own?

---

### Example scenario

So for example I want to create a Select list widget (e.g. contact\_by field) appearing on Entity form which has the following values:

```
by_phone|By Phone
by_email|By Email
ops_typo|By Post (fixme: correct typo)
by_fax|By Fax (fixme: remove me)

```

So the critical scenario would be a strong need of changing these values such as typo (correcting `ops_typo`) or changes in business requirement how these form works (e.g. I want to remove `by_fax` appearing on the submission forms for new forms), however it is currently not possible by using a standard Select list widget, because it has already some existing data associated with that value

---

### Reproducible steps

1. Launch Drupal sandbox.
2. As admin, add a new entityform type (*Admin/Structure/Entityform Types/Add*) for auth users: Test
3. Add new required field Contact By of List (text) type as Select list widget pasting above values.
4. Create two entity forms (*Admin/Structure/Entityform Types/Submit Link* or at */eform/submit/test*), one with *By Post*, another with *By Fax* values.
5. Now go to *Manage fields* of that *Entityform*, in 'edit field' or 'field settings' try removing/changing the last two values (the **key part**, not label).

---

### Data storage

As per comment concern, the change of value won't corrupt any existing data (despite of the warning), because the value in stored is database in the text format anyway, for example:

```
INSERT INTO `field_data_field_title` VALUES ('entityform','test_title',0,207,207,'und',0,'Foo');
INSERT INTO `field_revision_field_title` VALUES ('entityform','test_title',0,207,207,'und',0,'Foo');

```

which has the references to the right `entityform`:

```
INSERT INTO `entityform` VALUES (208, 'test_title', '', 1447192797, 1447192797, X'733A303A22223B', 1, 0, NULL);

```

So when viewing the entity form (e.g. `/entityform/208`) is just showing plain text. I don't need to edit that data, as it's just one-off form submission.

# Answer
> 6 votes
As for workaround, it is possible to use *Taxonomy Term Reference* field type as *Select list*, which would provide me a dynamic list of options (list of terms) which can be changed in the future.

However this is not ideal solution for multiple forms from UX perspective, as I have to create a separate taxonomy vocabulary for each widget (or creating a very long one).

---
Tags: 7, entities
---


# Question
Title: Migrating Multisite Setup to Localhost Running Nginx 404 for /files
I'm migrating a Drupal 7 based site to localhost. The site is currently setup in a multi-site configuration in the following way:

```
    webroot
    -drupal
    --sites
    ---example.com
    ----files
    ----settings.php
    ----sites.php
    ----modules
    ----themes
    ----libraries
    ----private

```

On my local dev server I imported the Db and set up the site in the following configuration:

```
 webroot
 -sites
 --example.com
 ---files
 ---settings.php
 ---sites.php
 ---modules
 ---themes
 ---libraries
 ---private

```

While I'm able to see the pages and login to the site, everything in my /files folder is returning a 404. All of the aggregated js files and images are broken and when I try to access any site admin links, I get an error.

I've check the permissions for the /files folder and files and everything seems fine. I've tried various suggestions like checking the .htaccess file, and adding $base\_url in settings, and even turning off clean urls, but nothing seems to work. I even tried to set permissions on the folder and files to 777, but no luck.

Any suggestions or recommendations would be greatly appreciated.

# Answer
> 0 votes
I sorted this out. I'm using VVV Varying Vagrant Vagrants for my local development environment, https://github.com/Varying-Vagrant-Vagrants/VVV

Needed to customize the nginx configuration files for my site to accommodate a Drupal installation. The issue with the /files folder contents being 404 was largely due to this. After I configured nginx correctly for Drupal it worked like a charm.

You can find a sample config file here for Drupal: https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/

---
Tags: migrations, multi-sites
---


# Question
Title: How to set up content writers to produce articles in their own languages
After spending hours on the Entity Translation and Fields modules I still can't configure a Drupal site, how do I achieve this:

* When a content writer logs in and create a node and drops down to their language, it automatically puts their country prefix in front of it: th/this-is-my-article. Currently it allows the drop down, but when created seems to be in English

Tried this through path auto, doesn't let me add the 'th' bit on

* Translate all nodes automatically - surely I don't have to physically click each node after I've created it to add another language? This cannot be correct?

Any help welcome.

# Answer
I manage multilanguage sites with lingotek module, but it can be with other modules,to prevent a user to upload a node in a wrong language, with rules module add a rule, event: Drupal is initializing, condition: compare user language with current language, action: page redirect, change language or whatever to prevent it to be in wrong language. once uploaded you can translat it. with lingotek configure your contentype to be auto-translated when uploaded.
> 0 votes

---
Tags: i18n-l10n
---


# Question
Title: Webform 4 - More than one conditional hides or shows component - Confusing Is & Isn't Shown?
I'm getting the following error: **More than one conditional hides or shows component** -- Once a user selects one option, it should hide other fields not pertaining to the selection. attached screenshot.

not sure what I'm doing wrong.

# Answer
ok it works with this setting it seems. it seems that once u set it to "isn't shown" it will auto hide it by default. which is why its throwing an error as it cant do 2 conditions at once.
> 2 votes

---
Tags: 7, webforms, entities
---


# Question
Title: Is it possible to run a View from code in a cron hook?
I'm writing a queued cron process, and need to retrieve some information while doing this. Rather than fiddling around with DB queries, it seemed to me much easier to create a View and then execute it in the code. Which I did (and by the way, the View itself works fine and returns the expected result). Trouble is, although it seems to run fine, it returns no result.

I've tried two different ways of doing this, but both are the same: the result is empty.

First was very simple:

```
if (!isset($node->og_group_ref)) {
  $regions = views_get_view_result('og_regions');
  }

```

That left $regions empty, so I tried this, with no better result:

```
if (!isset($node->og_group_ref)) {
  $view = views_get_view('og_regions');
  $view->execute();
  $regions = $view->result;
  }

```

# Answer
Problem sorted. It was all down to permissions, and loading user 1 as described in the blog linked to by my previous comment allowed the View to work as expected.
> 0 votes

---
Tags: views, cron
---


# Question
Title: how to use data of a text list field to draw a canvas image?
I'm working on a website, where some information has to be drawn like a graph on a canvas. I have the javascript to draw the picture, but for input I need the values of a field (List/Text) initialized by check boxes.

What I need is a way to get the values from the field of the node and draw a canvas image with the javascript code I have but I cannot figure out how..

Any ideas?

# Answer
> 0 votes
the answer is jQuery. The comment above written by burnsjeremy

'I guess you need to get the value in the browser on the client side so you would need to use jQuery (you can pass the value from the backend '

thanks, burnsjeremy

---
Tags: entities
---


# Question
Title: show content type fields from user on another content type
I need to be able to show fields from one content type on another.

Example:

Article: basic title/body fields Author Bio: User information (website, twitter and FB info, email, etc... fields)

Trying to create a block that will look at the NID, pull the node author and show the bio at the bottom of the node.

I tried using UID and NID as the contextual filter and author as the relationship. I also filtered to show only published and content type "author bio"

But when I try and use the auto preview, I get my labels with no data.

So I went into the individual fields, but there is no drop down to force a relationship to the node author like in entity references.

I am missing something, but I can't seem to find it. Any help would be appreciated.

Thank you.

# Answer
I wonder if it may be better to just add all personal info fields to the User entity itself instead of creating a whole new Content Type (go to Configuration \> People \> Account settings and add fields such as website, twitter, etc to the user entity). Then simply create a view of articles and create a relationship to the user entity by choosing `Content: Author`. Then simply add user fields to your list of fields in the view. Am I missing something in your question? (it's not very clear). Let me know and I can edit this answer.

**Edit after your comment:** Since you are interested in providing these info fields to specific users, I would then explore the profile2 module, which allows you to add additional fields for certain users. You can create different profile types with different fields, and allow certain roles to have access to specific profiles. In your View you can create a relationship to `Content: Author` first, and then one to the profile, then add those profile2 fields to your list of fields in the view.

Otherwise, if you still want to do this with a Author bio content type, I would suggest that you add an Entity Reference field to the User, and then you can use that as a bridge to your Article. Let me know if you want more details on this.
> 1 votes

---
Tags: 7, nodes, views
---


# Question
Title: Content Type with Add comment, Post New Article, Share Links
I have created a drupal page, I want to add comment,share link to the post I have tried using view to create it it does not work out.

# Answer
> 1 votes
To add **Add comment** link in view, follow below steps.

1. Add another field to your view i.e. **Content: Nid**
2. In field configuration, remove the title.
3. Select "rewrite the output of this field" and enter "Add comment" in the text area.
4. Now select "output this field as a link" and enter `comment/reply/[nid]#comment-form` in the Link Path field.

To add **Share link**,

1. Install ShareThis module.
2. Now add share field into your view.

---
Tags: comments
---


# Question
Title: Get/print current Ubercart currency via template.php
I am using Ubercart on D7.

Does anybody know how I can get the current Ubercart currency (e.g. $, €, etc) in template.php?

I am overriding the add to cart button via hook\_form\_alter, and need to print the site's current currency (in case of multi-currency) in the button markup.

thanks

# Answer
```
/**
 * Implements hook_node_load().
 */
function NAME_OF_MY_MODULE_node_load($nodes, $types) {
    $language = $GLOBALS['language']->language;

    if($language == 'en') {
        $variables['uc_currency_code'] = 'EUR';
        $variables['uc_currency_sign'] = '€';
        $variables['uc_currency_thou'] = ' ';
        $variables['uc_currency_dec'] = ',';
        $variables['uc_currency_prec'] = '2';
        $variables['uc_sign_after_amount'] = 1;

        variable_realm_switch('currency', 'eur', $variables);

        // increase price by 1000
        foreach($nodes as $key => $value) {
            if(isset($value->price)) {
                $nodes[$key]->price += 1000;
                $nodes[$key]->sell_price += 1000;
            }
        }
    }
}

```

Requires Variable module. I hope it helps
> 1 votes

---
Tags: 7, theming, ubercart
---


# Question
Title: Hide label for input on focus and when has value
I have some simple jQuery working to hide labels for text inputs on focus, keyup and blur if (value !== ''). I am using replacement tokens in my forms to fill in a default value based on the currently logged in user. I need to hide the labels if the default value gets prepopulated. I can't get the right function to hide the labels if a default value populates the form. (I've installed jQuery update to get the .on() function.) Here's the script in my js file:

```
(function ($, Drupal, window, document, undefined) {
Drupal.behaviors.my_custom_behavior = {
  attach: function(context, settings) {
/*------ Hide labels when user interacts with forms ------*/
    $(".form-item input", context).on({
      focus: function() {
        $(this).prev('label').fadeOut('fast');
      },
      keyup: function() {
        $(this).prev('label').fadeOut('fast');
      },
      blur: function() {
        if($(this).val() !== "") {
          $(this).prev('label').hide('fast');
        } else {
          $(this).prev('label').fadeIn('fast');
        }
      }
    });
/*------ Hide label if has default value on page load --------*/
    $(document).ready(function(){
      if($('.form-item input').val() !== "") {
          $(this).prev('label').hide();
      }
    });
  }
};
})(jQuery, Drupal, this, this.document);

```

Drupal outputs

```
<div class="form-item form-type-textfield form-item-field-email-address-und-0-email">
  <label for="edit-field-email-address-und-0-email--2">Email Address <span class="form-required" title="This field is required.">*</span></label>
 <input type="text" id="edit-field-email-address-und-0-email--2" name="field_email_address[und][0][email]" value="foo@foofighter.foo" size="60" maxlength="128" class="form-text required">
</div>

```

# Answer
> 0 votes
Check out this

```
   if ($(value).val() != ""){
  var fieldId = $(value).attr("id");
  $("label[for='"+fieldId+"']").hide();
}

```

---
Tags: javascript
---


title: Image styles return Access Denied

text:
# Question
Title: Image styles return Access Denied
I'm using the Insert module to allow users to insert images with a specific image style into a page. After upgrading to Drupal 7.20, the images are not stored in the `files/styles` folders, and the image url returns a 403 (access denied) error. I checked the folder permissions, and they are all set to 777.

# Answer
It is always recommended to read the release notes of the new release before updating, to make sure that the update doesn't break some of the current features.

The release notes of Drupal 7.20 mentions:

> The security fixes in this release change all image derivative URLs generated by Drupal to append a token as a query string. (As an example, links that previously pointed to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png will now point to a URL like http://example.com/sites/default/files/styles/thumbnail/public/field/image/example.png?itok=zD\_VaCaD.)

You can add the following line to your `settings.php` to get the images in the site working:

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```

but it would be as good as updating the core and not using the updates ;-)

Some useful links from the page:

## **UPDATE:**

From the release notes of Drupal 7.21, the update includes fixes for incompatibilities introduced in the Drupal 7.20 security release only. So, it is recommended to update to the latest version i.e. 7.21 to use the security fixes in version 7.20.
> 32 votes

# Answer
For what it's worth I also found that somehow my image style directories were no longer set the correct permissions after an upgrade and clear cache.

They root styles/\[your style\] and styles/\[your style\]/public should be 755 in order for things to load properly.

Changing them all caused the images to appear properly agaain!
> 3 votes

# Answer
Fix your File system: /admin/config/media/file-system

**Here are my settings:**

*Set up the public system path*: sites/default/files

*Private file system path is* empty.

*Temporary directory:* /tmp

*Default download method* (selected) Public local files served by the webserver.
> 1 votes

# Answer
Performing this edit did NOT fix the problem and produced errors:

> line 775 of modules/image/image.admin.inc needs a patch...
>
> ```
> 775> - $preview_file = image_style_path($style['name'], $original_path);
> 775> + $preview_file = image_style_url($style['name'], $original_path);
>
> ```

(since my reputation is low I can't comment yet under that separate answer)

I've implemented this way back and it fixed a lot of things when that issue first arose:

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```

I've also implemented changing all `+FollowSymLinks` to `+SymLinksIfOwnerMatch` but still am not able to get image styles previews to work properly.

Next and last option is to change the server-size user permissions, ack. I'll either fix it or break it all.
> 1 votes

# Answer
line 775 of modules/image/image.admin.inc needs a patch...

```
775> - $preview_file = image_style_path($style['name'], $original_path);
775> + $preview_file = image_style_url($style['name'], $original_path);

```
> 0 votes

---
Tags: 7, media
---


# Question
Title: How to remove "Submitted by .... on Fri, 06/19/2015 - 22:04" from published content in Drupal 7?
How to remove "Submitted by .... on Fri, 06/19/2015 - 22:04" from published content in Drupal 7? Where and what parameters and permissions to change? Thank you.

# Answer
You can remove it by doing below steps.

1. Go to content type edit page i.e. **/admin/structure/types/manage/page**
2. Now under **Display Settings**, uncheck the option **Display author and date information.**
> 3 votes

---
Tags: nodes
---


# Question
Title: How to install drush extension / addon globally?
I want to install drush-toolbox project globaly on my linux server box so all users can use it. How can I do it?

# Answer
Put it in `/usr/share/drush/commands` for global accessibility. On Windows, Drush will look in the folder named `Drush/share/drush/commands` inside the location specified by the `ALLUSERSPROFILE` environment variable.

After adding new commands, you will need to run `drush cc drush` to clear the Drush command cache, so that Drush will once again scan its command searchpath.
> 7 votes

# Answer
You can also specify your own directory for Drush modules/commands by drushrc.php:

```
$options['include'] = array('/path/to/commands','/path2/to/more/commands');

```

This file could be placed in several directories:

1. Drupal site folder (e.g. sites/{default|example.com}/drushrc.php).
2. Drupal sites/all/drush folder.
3. In any location, as specified by the --config (-c) option.
4. User's .drush folder (i.e. ~/.drush/drushrc.php).
5. System wide configuration folder (e.g. /etc/drush/drushrc.php).

More useful informations can be found in example.drushrc.php.
> 3 votes

# Answer
Newer versions of `drush` (6.2 here) are installed with `composer`, the new PHP dependency manager. So the installation of an additional command is now like this, in your case:

1. Go to the installation directory for `drush` commands:

```
cd [drupal-site-docroot]/vendor/drush/drush/commands

```

This assumes the default case where `composer` installed `drush` for each of your Drupal sites separately (it can also install it once per user, or system-wide – I prefer the latter).
2. Download, unpack and clean up:

```
wget https://github.com/zroger/drush-toolbox/archive/master.zip;
unzip master.zip;
mv drush-toolbox-master drush-toolbox;
rm master.zip;

```
3. Clear the commandfile cache to register the new command:

```
drush cc drush

```
> 2 votes

# Answer
If you only need it for your local user on Linux, then put plugin into

```
~/.drush/commands

```
> 2 votes

---
Tags: drush, installation
---


# Question
Title: Problem with getting number of nodes created by a user in a View
I know this question is already asked, here is a few links How to count the node a user has created in a View? or How can I count the number of nodes submitted by the current user?

This is a very simple task but I am facing a problem. I'm trying to get the number of nodes of a certain content type created by a user. This is the configuration of the view:

1. setting **Author uid** as contextual filter
2. setting the content type in filter criteria and selecting Node ID as field
3. setting aggregation to `yes` and set the `nid` to use the `Count Distinct` aggregation
4. Setting the `Pager` to *Display all items*

If I don't use the aggregation this is the result:

2158 2151 2152 2153 2154 2155 2156 2157 2142 2143 2144 2145 2146 2147 2148 2149 2150 2141 2140 2139 2138 2137 2136 2127 2126 2125 2124 2123 2128 2129 2130 2131 2132 2133 2134 2135 2122

But if I use it, the result is :

```
8
15
14

```

which 8+15+14 = 37 and number of the nodes is also `37` but I wonder why it displays the 37 this way?

# Answer
> 1 votes
You should make sure that you have no sort criteria set in your view that splits your aggregation.

---
Tags: 7, views, nodes
---


title: Using Drupal::url()

text:
# Question
Title: Using Drupal::url()
I am porting code from Drupal 7 to Drupal 8.

In Drupal 7, my code looks like the following:

```
return url($parts[0] . '/' . $parts[1] . '/profile/id/' . $context['profile']->uuid . '/cancel');

```

I know that I have to use `Drupal::url()`, but I have to use a route name or an external URI, but I don't know what to pass.

How should I update my code for Drupal 8?

# Answer
> 0 votes
Try following code:

```
$path = '/' . $parts[0] . '/' . $parts[1] . '/profile/id/' . $context['profile']->uuid . '/cancel';
$url_object = \Drupal::service('path.validator')->getUrlIfValid($path);
$url_object->setAbsolute();
$url = $url_object->toString();

```

---
Tags: 8, uri
---