# Question
Title: Choosing between template files and custom module
I wanted to add some custom functionality in my Drupal website, so I read some tutorials (first, second ) and decided to create custom template files for specific forms & exposed filters I wanted to change. And it worked perfectly!

But when I had to pass the changes to the original site I had to change the code a bit, so I tried with a custom module this time (not using template files) and it also worked like a charm!

I'm confused because both templating and custom modules can be used for providing the same functionality. But which is better - in terms of stability, performance, code reuse etc. ?

# Answer
> 1 votes
You should separate your templating into two logical groups:

**Theme-specific** Only markup and styling that is relevant to your site theme should go here. You should ask yourself the question - if I was to change my theme - would it affect any functionality of the site? For instance, say you needed to add a block of markup that inserted a third-party analytics tracking. If you put this in `html.tpl.php`, it would be removed if you switched theme, breaking site functionality.

**Functionality-specific** If you are augmenting your site with new functionality that requires markup or styling (quite rare) independent of theme, then it should be coupled with the module. The above example of inserting a snippet of JS for a third-party analytics provider is a good one, for instance. Again, ask yourself, what happens if you were to switch the theme. If any site functionality were to break because of a change in theme then it shouldn't be in the theme, but part of the module.

For the most part, your markup and styling will be related to your theme. But say you developed a forum module - you would need some base markup to deliver the functionality; base markup and styling which could then be enhanced by a specific theme, and not break the basics of the forum layout if you decided to implement or switch another theme.

# Answer
> 1 votes
That depends on what you would like to accomplish. When it is just pure templating (markup, styling, theming) you can do this with template files just fine.

But when you want to include custom logic (programming), it is better to create a custom module where you put the hook() implementations and/or preprocess functions etc...and then define a temaplate file there.

Does this offer some clarification for you?

---
Tags: 7, forms, theming, views
---


# Question
Title: Mollom captch disappear after using hook form alter for validation
I have altered **Request new password** form field label

```
function useredit_form_user_pass_alter(&$form, &$form_state, $form_id) {
  $form['name']['#title']='Username';
  $form['#validate'] = array('useredit_user_pass_validation');
}

function useredit_user_pass_validation($form, &$form_state) {

  $name = trim($form_state['values']['name']);
  if(preg_match("/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/",$name))
  {
     form_set_error('parent_field_email', t('Please enter valid username.'));
  }
  # try to load by name.
  $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
  $account = reset($users);

  if (isset($account->uid)) {
    form_set_value(array('#parents' => array('account')), $account, $form_state);
  }else{
    form_set_error('name', t('Sorry, %name is not recognized as a user name.', array('%name' => $name)));
  }
  }

```

form get's altered and validation works but captch image gets disappear. How to resolve this ?

# Answer
I have done below changed above code:

```
$form['#validate'] = array('useredit_user_pass_validation');

```

by

```
$form['#validate'][] = 'useredit_user_pass_validation';

```

And it's works !
> 0 votes

---
Tags: advertising
---


# Question
Title: How not to "fill up" a view when flagging
I have a list of different tasks (about 100 items). Each time a user logs in, he should get a display of 5 tasks randomly selected out of this list. When he finished the task, he can flag them as "done" and the task will disappear from the list. I managed to do this with flag module and views module. The problem is, that the task-list is much longer than the 5 tasks. So each time the user flags a task with "done" this task will disappear from the list, but a new task will show up at the same time. How can I stopp a view to be "filled up" in order that the user can empty his task list? (And may be gets new tasks only the next da or on next login).

# Answer
> 0 votes
I figured out how to manage the problem without the need to write new code. I am posting it here, so that it may help others as well, even if the topic is very specific.

How to manage, that a view doesn't fill up immediately after flagging:

1. Create a "helper flag" and set the flag link to the helper flag on the nodes of your view.
2. Create a rule, that the flagging of the helper flag, adds the action of unflagging your original flag.
3. Put the filter in your view in this way, that not only all nodes are displayed that are unflagged with your original flag, but also those with the helper flag (or-filter)
4. Create a rules display of this view.
5. Create a rule that reacts on the event "user has logged out".
6. Add a view loop from the created rules display and add the action (unflag the nodes". choose the "helper flag" to be unflagged.

That's all. As long as the user stays logged-in, the view is not filled up, when he flags the nodes. As soon as he logs out, the helper flag is unflagged and the view is filled up.

---
Tags: views, flags
---


# Question
Title: how to add a class div on drupal 7 webform element?
webform generated each form component in this structure

```
<div>
  <label></label>
  <input></input>
</div>

```

I like to add a div class on each input element

```
<div>
  <label></label>
  <div class="xxxx"><input></input></div>
</div>

```

I looked into the form alter to alter form element with `#field_prefix` and `#field_suffix`

```
$form['submitted']['chinese_name']['#field_prefix'] = '<div class="abc">';
$form['submitted']['chinese_name']['#field_suffix'] = '</div>';

```

but it didn't work.

# Answer
You are using the incorrect keyword, the correct way to add a prefix to the webform field is:

```
$form['submitted']['chinese_name']['#prefix'] = '<div class="abc">';
$form['submitted']['chinese_name']['#suffix'] = '</div>';

```
> 1 votes

# Answer
Prefix and suffix will add wrapper element to whole form element, to add class to certain fields you can next thing.

For textfield you can do next find, go to `includes/form.inc` and find function `theme_textfield` copy it to your `template.php` and rename to `yourtheme_textfield` its look like this:

```
function theme_textfield($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'text';
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  _form_set_class($element, array('form-text'));

  $extra = '';
  if ($element['#autocomplete_path'] && drupal_valid_path($element['#autocomplete_path'])) {
    drupal_add_library('system', 'drupal.autocomplete');
    $element['#attributes']['class'][] = 'form-autocomplete';

    $attributes = array();
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element['#attributes']['id'] . '-autocomplete';
    $attributes['value'] = url($element['#autocomplete_path'], array('absolute' => TRUE));
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';

  //This will add div element with class SOME_CLASS
  //================================
  $output = '<div class="SOME_CLASS">' . $output . '</div>';
  //=====================

  return $output . $extra;
}

```

As you can see you can do what you want. Here for example i added `<div class="SOME_CLASS"><input></input></div>`.

If you need this class for different form elements find `theme_form_element($variables)` in `form.inc` copy it to your template.php and rename to `yourtheme_form_element` and do whatever you want. This works for `drupal7`.
> 0 votes

---
Tags: forms, webforms
---


title: Q&A/ticket system help with permissions

text:
# Question
Title: Q&A/ticket system help with permissions
I am trying to build a Q&A / Ticket System with custom nodes. the current status is:

### Nodes:

* Company: on the company node you get a link with "I want to ask a question"
* Question: on the question node you get a link with "add comment"
* Comment: on the comment node you get a link with "add comment"

Multiple comments create a thread.

The relation is made with Node Reference URL Widget. The question node has a reference to company. The comment node has a reference to question.

### I have 2 user roles:

* Company
* Clients

Companies can only react on questions and comments related to themselves. e.g. pcpower can only react on questions for them and not on those asked to pcworld.

How can this permission be accomplished. For now a company can react on all questions.

Clients: can ask questions to anyone (is working) BUT must only reply on comments/reactions on subjects created by them.

At this moment clients can make comment to any question or comment in the system.

Any help regarding to this would be really helpful.

Kind regards, Jos

# Answer
> 0 votes
You could accomplish this with a custom node.tpl.php for the content types - whereby it checks if the author of the node is the currently logged in user, and if not, it doesn't display the comments links (or the comments all together).

# Answer
> 0 votes
thanks. Getting there (partial) i have restricted acces to the add comment link for the node author using.

```
 <?php
    global $user;
    //dsm($user);
    if ($user->uid == $node->uid || $user->uid == 1 ):
        print $links;
        endif;
        ?>
   <?php print $terms; ?>

```

Now I would like to create acces to the link for the company user.

* user(company) has field\_company as term
* question has field\_company as term

Can I create a code that will say: print link when logged in user term is equal to current node term?

I have only found a code that print the term name.

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


# Question
Title: How to load file, when I know it's filename, but not fid?
I create filenames using some ID and timestamps. I don't want to add additional table to "remember" associations, as filename keeps them pretty well:

```
$filename = get_symbol_by_id($id) . ' ' . get_modified_by_id($id) . '.xml';

```

Also, I don't care if they will be managed or not. And I don't care if they get deleted - I can recreate them on demand. They are small, so leaving older ones behind does not create any cost worth taking care of. What is the proper course of action?

**"Unmanaged" files seems to be generally discouraged in 7**, but using them is pretty straightforward with tools like:

With managed files, I'm afraid I would be forced to use

So what's the proper course of action, if I want to avoid both deprecated functionality and overly complicated code?

# Answer
> 5 votes
I'd definitely go with EntityFieldQuery, not a really complicated solution:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'file')
      ->propertyCondition('filename', '<filename>%', 'LIKE');
$result = $query->execute();
if (!empty($result['file'])) {
  $files = entity_load('file', array_keys($result['file']));
}

```

Use of conditions is not really recommended on any load multiple function anymore, the method above would be more standard and "future proof" as EntityQuery is the way to go in Drupal 8.

Installing file entity module would add much more value on what you can do regarding managed files.

---
Tags: 7, files
---


# Question
Title: Main menu is hidden from unauthenticated users
I am using a slightly modified Responsive Batrik theme. The odd thing is that the main manue and site logo are hidden from unauthenticated users. When they log in, they can see the menu and logo.

I'm wondering why this happen and how to solve it?

# Answer
Follow Below things:

1) Make sure that in admin/people/permissions "View published content", "view own Unpublished Content are "Unchecked" for the "anonymous user".

2) Still if you are getting those "Disclaimer and Policies" menu links. i) Create a new menu and add those links in to that menu. While adding links Give the Parent menu link to "Main Menu". and save the menu. ii) Then admin/structure/block, configure the menu block: Give the permission to access only to Authenticated User and save the block

or,

If you are assigning main menu (as block) to region, you can control it's visibility by "Visibility settings". If you are rendering it in .tpl.php file then you can do it like this: Example (bartik's page.tpl.php):

```
<?php print theme('links__system_main_menu', array(

  'links' => $main_menu,

  'attributes' => array(

    'id' => 'main-menu-links',

    'class' => array('links', 'clearfix'),

  ),

  'heading' => array(

    'text' => t('Main menu'),

    'level' => 'h2',

    'class' => array('element-invisible'),

  ),

)); ?>

```
> 0 votes

---
Tags: navigation
---


title: How to remove ?= from url?

text:
# Question
Title: How to remove ?= from url?
I am getting url example.com/?= and I want this example.com
I have tried .htaccess method but nothing happened.
I have also gone through may link like clean urls but nothing happened My clean URLs test fail.

Please help.

# Answer
> 0 votes
It will sound silly but it can help you.
Go to `/admin/config/search/clean-urls`
you will get `example.com/?=admin/config/search/clean-urls` in your address bar
remove `?=` from address bar so that your url become `example.com/admin/config/search/clean-urls`
press enter
Now you will get a check box
tick that box and save configration.
May this Helps you.

# Answer
> 0 votes
First thing first, try enabling "rewrite" module for apache,

```
sudo a2enmod rewrite

```

After that You need to replace the occurrence of **AllowOverride none** to **AllowOverride all** in your site-available file

```
sudo vim /etc/apache2/sites-available/default

```

And finally you need to enable `clean-url` form your drupal site.

> Home » Administration » Configuration » Search and metadata
>
> OR navigate to
>
> http://example.com/admin/config/search/clean-urls

# Answer
> 0 votes
Enable mod\_rewrite apache from httpd.conf

1. open httpd.conf
2. find mod\_rewrite
3. just remove # to enable
4. once it enable then you can run Clean URL
5. this will show check box tick on it and save it

---
Tags: .htaccess, uri
---


# Question
Title: Enabling Clean URLs on website-in-progress
I host my site and a few others through Hostgator. When I build a new Drupal site as a replacement for an existing site at a different host, I build it on the IP address (192.xxx.xxx.xxx/~username) or on the corrado (Hostgator) url (corrado.websitewelcome.com/username). In both cases, I cannot activate Drupal's "Clean URLs" feature. Once the site is built and we are ready to point the domain name to the new site (and we do so), Clean URLs works fine. It is an issue, though, while I am still building the site, because I have to use absolute URLs in the CSS and the various content blocks for the links and images to work correctly, and that creates extra work during the website activation process where I have to go back in and remove all of those absolute URLs. I have tried modifying my hosts file so that the site's existing URL will resolve to the Hostgator IP address for that new site-in-progress, but this isn't enough to "fool" the Clean URLs function.

I already reached out to Hostgator support, and they did not have a solution for me. Any ideas on how I can work around this issue and get Clean URLs to work in this environment?

# Answer
You can use relative css as long as you are pointing to files within your theme. That will work like this. `url('img/image.jpg');` So no need for full url's here.

More explanation here: http://css-tricks.com/quick-reminder-about-file-paths/

At template level you might want to use drupal\_get\_path to point to the various modules and or themes.
> 0 votes

# Answer
Check for status of Rewrite module, whether it is enabled or not. If it is not enable it and restart your Apache server (Hope you using Apache). still if it is not working then check the **Allow override** settings in the virtual host file or default site file for the specific project folder.

AllowOverride all

If the value is None the change it to all. Once again restart the web server and check you can activate clean url feature.
> 0 votes

# Answer
It can help you.
Go to /admin/config/search/clean-urls
you will get example.com/?=admin/config/search/clean-urls in your address bar
remove ?= from address bar so that your url become example.com/admin/config/search/clean-urls
press enter
Now you will get a check box
tick that box and save configration.

May this Helps you.
> 0 votes

---
Tags: 7, .htaccess, uri
---


# Question
Title: Images under sites/default/files not appearing
I have images inside `/sites/default/files/styles/medium/public/field/image`, and I can't seem to see them in my browser, I have /sites permission set to 777 and I read something about commenting all the `Options` line from my .htaccess. And here's my .htaccess :

```
# Turn off all options we don't need.
#Options None
#Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

```

Any way I can solve this ?

# Answer
> 0 votes
* First of all give recursive permissions to the folder (sites folder). Below screenshot shows how to give recursive permission on windows filezilla.

Select the checkbox "Recurse into subdirectories"

* Make sure to reset the permissions on the settings.php file

---
Tags: media, .htaccess
---


# Question
Title: Create a view pulling in content that matches user profile
Im am trying to create a view that pulls in content that matches to the user. This is done with two taxonomy fields that are added to the user profile and the content type. These are job role and speciality. I know how to set up the view to pull in content using just 1 of these fields but how can I get it so its an AND condition. I need to pull in content that has both the same job role and same speciality as the user. Is there anyway of achieving this through the views UI or do I need to alter the query?

Thanks

# Answer
> 0 votes
I ended up adding a **relationship** for Content: Taxonomy terms on node and using hook\_views\_query\_alter() and loading the users profile and adding two where clauses like so :

```
$query->add_where(0,"field_data_field_job_role.field_job_role_tid",$job,"=");

$query->add_where(0,"field_data_field_specialty.field_specialty_tid",$specialty,"=");

```

# Answer
> 0 votes
With Drupal 7 and Views 3 you can match on multiple taxonomy terms using contextual filters. I posted about this on drupal.org here. Maybe it can be adapted to your particular situation.

# Answer
> 0 votes
I think you can achieve that using Views module as usual. In the edition of the view:

1. Look for the `Filter Criteria` section
2. Locate the button in the right.
3. Click on the arrow and you should see the link `And/OR, Rearrange`.
4. Click it and add the conditionals you need.

Hope this is what you're trying to achieve.

---
Tags: views
---


# Question
Title: View showing ONLY taxonomy children terms and NO parents
I've managed to got my view working but my worry is that this method is not dynamic.

**What I want to achieve?** To have a list of articles tagged with terms that are one level deep (children) but not their parent terms.

E.g.: assuming a taxonomy looks like this:

```
A
  A1
  A2
B
  B1
  B2

```

I want to be able to go to the URL **mysite.com/A/A1** or **mysite.com/B/B2** and retrieve a list of articles with ONLY content tagged with A1 or B2 (in this example)

For that I added a filter and manually selected the parent terms I don't want to list:

Is there a better solution to achieve this?

Thanks!

# Answer
Super simple but impossible to guess solution :

With a normal filter set the "Parent term" filter not equal to "0".

This will filter parents
> 3 votes

# Answer
In your view:

Contextual filters

Content: Has taxonomy term ID (with depth)

```
 Depth: 1
 When the filter value is NOT available :
   Type : Taxonomy Term Id from url
   & Select Load default filter from term page

```

Content: Has taxonomy term ID depth modifier

Hope this will help you to get the result.
> 1 votes

# Answer
From Contextual filters select:

Content: Has taxonomy term ID and select checkbox Provide default value "taxonomy term id from url" and select checkbox " Load default filter from term page"

and In Relationship:

Relationships Content: Taxonomy terms on node and select checkbox REquire this relationship.

I hope this will work you.
> 0 votes

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


# Question
Title: How can I make Apache Solr Autocomplete work in search Views?
I'm trying to work with Apache Solr search in my view and make this autocomplete.

Apache solr is configured correctly and I've added a solr view. I can search on fields, that's no problem. But how can I make the autocomplete work?

# Answer
Have you tried to search in google? before asking. Have you tried to do anything? I noticed you're constantly asking questions to which the answer can be found by spending a little time searching. Try to do something by yourself before asking. thanks.

ApacheSolr Autocomplete module \- This module should solve your problem.
> 2 votes

---
Tags: views, search, ajax
---


title: How can I get a Rule to trigger a rule

text:
# Question
Title: How can I get a Rule to trigger a rule
I need to make a set of eight rules. Each rule will have about ten actions, nine of which will be the same for each rule (basically, these rules will duplicate a node and change one field). I would like to create a rule (sub-rule?) that contains the nine similar actions, and then make eight other rules which call the sub rule. Is there a way to make a rule trigger another rule? If possible, I would like to do this directly instead of performing an action (such as saving a node) which can trigger an event.

# Answer
Try creating a Rule Set Component and call it from a reaction Rule. (https://drupal.org/node/1300024)
> 2 votes

---
Tags: rules
---


# Question
Title: Show Link to Subscribe/Unsubscribe to Nodes in a View
I'm creating a view that shows all the nodes of a specific type. I'm looking to also show which of those nodes the current user is subscribed to and provide a link to subscribe or unsubscribe. Is there any way to achieve this using arguments, custom PHP field, etc?

I created an argument that filters the nodes the current user is subscribed to, but it hides all the nodes their not subscribed to, even if "Display All Values" is selected.

I'm using the Notifications module and Views 2.16 on D6.

# Answer
For a single View of non-subscribed nodes:

1. Using a contextual filter for NIDs, select provide default value by using PHP code.
2. Then in the PHP code use an EntityFieldQuery to get a listing of all nodes that are subscribable. Save this array of IDs to a variable.
3. Then use a 2nd EntityFieldQuery to get an array of all subscribed nodes for the active user.
4. Then subtract the 2 arrays, these are all nodes able to be subscribed to by the user.
5. use `return $subscribable_nodes;` to return the nodes as an array to the View.

Your view would contain a node title, and you could rewrite the node title as a link to the subscription url if you want.
> 0 votes

---
Tags: views, 6, notifications
---


# Question
Title: Drupal extra subdomains for some special nodes
I have the following in mind and I'm not sure how to realize it nicely.

1. Drupal 7 serves many nodes from several different taxonomies
2. If I visit a taxonomy page e.g. example.com/category-one/taxonomy-term-one I get a list of all the corresponding nodes
3. If I click on one of the list nodes, I get to the page example.com/content-type/node-name
4. There are some special nodes in this list, when I click on them, I get to the following special page node-name.example.com. This page is exactly the content like example.com/content-type/node-name but in this case, only the subdomain URL is accessible and example.com/content-type/node-name doesn't exist to avoid content duplication.

The first 3 items are easy standard tasks: The Pathauto module handles all the taxonomy url alias tasks etc.

The 4th item is my problem. My idea so far: The subdomain node-name.example.com just references a special folder under the drupal root, which contains some logic to determine the name of the node according to the subdomain. With the given subdomain I get the node id and just load all the stuff from drupals db with a service implemented for this usecase.

Questions:

1. Ist it possible to give a drupal node an absolute url alias like node-name.example.com just like node-category/node-name?
2. Are there any problems going to be concerning drupals $baseurl/site configuration?
3. As I'm editing everything just over the example.com/node/node-id/edit there should be no problems with the editing functionality, no?
4. What remains to be done?

Did anybody had to fulfill a similar apporach and could share some thoughts regarding my approach?

# Answer
Have you looked at the Domain Access module?

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites such as:
>
> * example.com
> * one.example.com
> * two.example.com
> * my.example.com
> * thisexample.com \<-- can use any domain string
> * example.com:3000 \<-- treats non-standard ports as unique
>
> By default, these sites share all tables in your Drupal installation. The Domain Prefix module (for Drupal 6) allows for selective, dynamic table prefixing for advanced users.

Basically you can assign a Node across any number of configured subdomains you've made drupal aware of.
> 0 votes

---
Tags: hooks, path-aliases, .htaccess, subsites
---


# Question
Title: Find users who have not uploaded certain contents in last 30 days
I need to find users who have not uploaded certain contents in last 30 days. I have tried this query it is not working. Can anyone help me?

> select uid, max(created) as max\_created from node where node.type in ('page','story') AND max\_created \< UNIX\_TIMESTAMP()-2592000

I am getting error in phpmyadmin:

> 1054 - Unknown column 'max\_created' in 'where clause'

# Answer
SQL is **evaluated backwards**, from right to left. So the `WHERE` clause is parsed and evaluate prior to the `SELECT` clause. Because of this the aliasing of `MAX(created)` to `max_created` not yet occurred.

You can try this,

> SELECT uid, MAX(created) FROM node WHERE node.type IN ('page','story') HAVING MAX(created) \< UNIX\_TIMESTAMP()-2592000
> 3 votes

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


# Question
Title: I sometimes get the following error message "Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 8 bytes)
On my Drupal 7 site once I have around 1500 records associated to a given content type then when viewing any of these nodes instead of seeing the content I sometimes get the following error message "Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 8 bytes) in /www/dev/drupal/includes/cache.inc on line 434". If I have less than 1500 records for a given content type (i.e. 1000 records) then viewing any of these contents always display without this error. How can I prevent this error from occurring for a given content type that has at least 1500 records associated to it.

# Answer
If you work in localhost, change memory\_limit in your {php\_installation\_dir}/php.ini to a higher one. Otherwise ask your web hosting service to increase the memory limit of the server. (You can check your PHP memory limit in your Drupal site too: /admin/reports/status)
> 0 votes

---
Tags: nodes
---


# Question
Title: Show original price and discounted price?
I'm using this module: Commerce Discount to create products discounts. In the products list view I'd like to show both prices: the original price and price with the discount. How can I do this?

I found this module: https://drupal.org/project/commerce\_price\_savings\_formatter but it doesn't seem to work with the Commerce Discount module.

# Answer
> 3 votes
It does work with the discount module. In fact the moudle was built with that one in mind. Install Commerce Price Savings Formatter and go to your product types's display settings and change it as per the screenshot.

---
Tags: commerce
---


# Question
Title: How to add UNION with pagination in drupal 7 query?
My query is like :

```
$query_club = db_select('club_members','cm');
$query_club->fields('cm',array('first_name','last_name'));
$query_club->group_by('cm.uid');

$query_network = db_select('network_members','nm');
$query_network->fields('nm',array('first_name','last_name'));
$query_network->group_by('nm.uid');

$query_club->union($query_network, 'UNION');
$result = $query_club->execute()->fetchAll();

```

And its giving me correct result.

I want to add here pagination,

```
$query_club = $query_club->extend('PagerDefault')->extend('TableSort');

```

But its not working. Can any one help me out

# Answer
> 2 votes
I got the solution. I added this whole query as in subquery like,

```
$query_club = db_select('club_members','cm');
$query_club->fields('cm',array('first_name','last_name'));
$query_club->group_by('cm.uid');

$query_network = db_select('network_members','nm');
$query_network->fields('nm',array('first_name','last_name'));
$query_network->group_by('nm.uid');

$query_club->union($query_network, 'UNION');

**$query_pagination = db_select($query_club,'club_network')->fields('club_network');
$query_pagination = $query_pagination->extend('PagerDefault')->extend('TableSort');
$query_pagination->limit(10)->orderByHeader($header);**

$result = $query_pagination->execute()->fetchAll();

```

And using custom form table `$form['pager'] = array('#markup' => theme('pager'));` pagination working fine now

# Answer
> 1 votes
I don't see where anything could be wrong, or why it's not working -- I suspect it might have to the do with the `union` but I'm only guessing.

Try these 2 things and see if 1 works for you:

1. Change your first db\_select to `$query_club = db_select('club_members','cm')->extend('PagerDefault')->extend('TableSort');`. This may help, i'm not 100% sure.
2. leaving your query as-is and using pager\_default\_initialize directly in your code. See the examples and comments on the API page.

---
Tags: database
---


# Question
Title: Drush ignoring `$options['config']` statement in drushrc file from the 'drush' folder at the root of the current git repository
I'm a long-time browser, first-time poster.

I have a Drupal 7 site set-up using Drupal-Boilerplate structure in a Git repository. I defined some settings in the `drush/drushrc.php` file. The documentation indicates:

> “Drush doesn't by default know to search this directory. To work around that we need to add this awesome snippet to our local drushrc.php file.”

I added the provided snippet to `docroot/sites/all/drush/drushrc.php`. But the `$options['config']` statement seems to be ignored. The settings defined in `drush/drushrc.php` are not taking effect.

I believe that the code is correctly defining the root of the Git repository. The `$options['alias-path']` statement seems to take effect as the “example” aliases appear when I run `drush site-alias`. The `$options['include']` statement also seems to take effect as the `devify` command defined in `drush/commands/build.drush.inc` is available.

The configuration options I have specified in `drush/drushrc.php` are not taking effect. When I run `drush status`, the “Drush configuration” lists `docroot/sites/all/drush/drushrc.php` and my user-specific `drushrc.php` from my home directory. I would expect to also see the `drush/drushrc.php` file listed.

I have tried executing `git rev-parse --show-toplevel`. That returns the correct path to the root of the Git repository. I tried explicitly adding the `drush/drushrc.php` file by adding the full path in an `$options['config']` statement in `docroot/sites/all/drush/drushrc.php`. None of that seems to have been effective.

I’m at my wits end with this. Please help me StackExchange!

I’m using

* Drush 6.3.0
* Drupal 7.28
* PHP 5.5.11
* Windows 8

# Answer
As Clive said, the snipped goes in $HOME/.drush/drushrc.php, not in the drushrc.php file in your site folder. The drushrc.php in your site folder does not get parsed until Drush bootstraps your site; by that time, it's too late to add items to the 'config' list, as it has already been processed.

Also, in place of:

`$repo_dir = drush_get_option('root') ? drush_get_option('root') : getcwd();`

... it would probably be better if the snippet used:

`$repo_dir = drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT') ? drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT') : getcwd();`

Finally, rather than setting the 'config' option, which is gitchy and a little high-strung, you could just include your drushrc.php directly.

Replace:

`$options['config'] = $repo . '/drush/drushrc.php';`

with:

`include $repo . '/drush/drushrc.php';`

Then you could go back to putting this snippet in your sites/all/drush/drushrc.php, if that's working better for you.
> 1 votes

---
Tags: drush
---


# Question
Title: How can I pass a fixed argument to a view within a panel?
I have a view that will be repeated on many pages, and to not replicate many times, has two arguments. These arguments do not come from URL, are fixed. This view is inserted into a panel. Is it possible? How? Thanks!

# Answer
> 1 votes
I'm making the assumption your on D7, with views 3, and have Views Content Panes running on your site (Views Content Panes comes with ctools).

So your gonna create your view as you normally would. When it's good and displaying as you want it to, add a display of a content pane (up near the top, under the display, hit the plus sign, select content pane). This will give you access to the "PANE SETTINGS," one of which is "Argument input." Click on this. If you have two contextual filters running on your view, there should be two drop down menus, one for each of your contextual filters.

Set both of these to "input on Pane Config." Now when your adding your views to your panels, your going to use the "View Panes," NOT the "views." Once you add your view pane, you should be presented with two text boxes for your contextual filters, you may set provide the arguments for those here.

---
Tags: panels, views
---


title: Profile2 profile

text:
# Question
Title: Profile2 profile
I am very new to Drupal but am good with coding (PHP, JS, whatever is required). I want to set up a simple registration page that allows users to register using minimal fields (name, email, password, etc). ONCE THEY ARE registered and verified/okayed, I would like to give them an OPTION to fill in a profile form, which will have many optional fields they might want to share about themselves.

The profile form will always be available to registered users to edit/change.

What is the best way to achieve this? It seems the PROFILE2 module only adds fields to the registration page.

# Answer
Oy, embarrasing. In the profile2 view, "edit" the individual profile, disable "Show during user account registration."

If those more experienced than me think this will help others, keep it... O/W delete this thread.
> 0 votes

---
Tags: views, users
---


title: simple layout fix for IE

text:
# Question
Title: simple layout fix for IE
I'm using Omega3 and having just a couple styling issues with IE. (The site looks good in every other browser) Is there a simple way to detect IE and call an IE specific style sheet to fix these couple layout issues?

I've tried setting/unsetting css/js aggregation and clearing caches. Also tried adding this code to my template.php file and creating a ie8.css file:

```
drupal_add_css(path_to_theme() . '/css/ie8.css', array('weight' => 999, 'browsers' => array('!IE' => FALSE, 'IE' => '(lt IE 9)&(!IEMobile)'), 'group' => CSS_THEME));

```

I'm looking for a simple way to detect IE and add a couple lines of css. Thanks!

# Answer
> 1 votes
1. Arguably the simplest (and least Drupal'y) way:

In html.tpl.php:

```
<head>
<!--[if lt IE 8]>
<link rel="stylesheet" href="<?php print base_path() . path_to_theme(); ?>/css/ie7.css" type="text/css" media="all" />
<![endif]-->
</head>

```

Clear your theme cache if adding the template to your theme for the first time.
2. Install the module, Conditional Stylesheets, which allows you to add conditional stylesheets to a theme's .info file.
3. Add 37 lines of code to template.php.

New to StackExchange, hope I did the right thing here. Thanks, @jdu.

---
Tags: theming
---


# Question
Title: Change print $node_url To a Link Fields Value
Hello i would like to change the destination of a url in a node.tpl (in a view) from this-

```
<a href="<?php print $node_url; ?>">

```

to something like this-

```
<a href="[field_viewslink]">

```

where the field viewslink is a link field in the node itself.

I know i could do it if the view used fields but it doesnt its using a content teaser.

Anyone got any advice?

Thanks

sites/all/themes/other\_sub/templates/nodes/node--view--portfolio-block.tpl.php

```
<li class="<?php print str_replace(',-', ' ', str_replace(' ', '-',strip_tags(render($content['field_portfolio_category'])))); ?>">
    <?php print render($content['field_portfolio_image']); ?>
    <div>
        <a href="<?php print render($content['field_viewslink']); ?>">
          <span class="center">
              <h4 class="heavy remove-bottom"><?php print $title; ?></h4>
              <p><?php print strtolower(render($content['field_portfolio_category'])); ?></p>
          </span>
        </a>
    </div>
</li>

```

# Answer
> 0 votes
finally got there with this

```
<a href="<?php print strip_tags(render($content['field_viewslink'])); ?>">

```

# Answer
> 1 votes
If it is a field with in the node then you should be able to use the `$node` object.

The object contains all the fields associated with the node.

if you are not sure of the name of the field then you could try to print the object using the `print_r` function.

You could also try try the `$content` object which contains the fields as well.

```
print render($content['field_viewslink']);

```

That should render the variable.

# Answer
> 1 votes
You can use template\_preprocess\_node function to modify value of node.tpl.php

e.g:

```
function MYTHEME_preprocess_node(&$variables) {
//$variables['node_url'] = url($uri['path'], $uri['options']);
$variables['node_url'] = url(YOUR-CUSTOM-URL);
}

```

---
Tags: views
---


# Question
Title: Easy Question: Filter a View By Tax Term Menu Style Not Exposed Filters
I dont know if im having a blonde moment or not. Im sure i learnt how to do this about 9 years ago way back on drupal 4 but ....well i seem stuck.

I have a page view. /match-previews. Its using the same vocab as im using across my website. I was wanting to create a menu link in the sidebar to each football league. I have it set up with an exposed filter but really i would prefer to have it as a menu system.

Ive tried cloning the page and adding a /match-previews/% page but thats where i seem to be stuck. Maybe just making up some normal pages and making a block view for each and taking the term from the page could be the way to go.

Can anyone put me out my misery as ive been at it too long for now tonight.

Thanks

my page is here if it helps http://ukfootballbet.com/match-previews/

# Answer
> 1 votes
You can use the /match-previews/% as a contextual filter (advanced tab). Here is a good tutorial on setting it up (http://www.metaltoad.com/blog/using-drupal-contextual-filters-views)

---
Tags: views
---


title: privatemsg link for anonymous users

text:
# Question
Title: privatemsg link for anonymous users
I crated a view to show a list of registered users such as as name, email, job etc. one of the fields I am also listing is a private link so other members of the site would be able to contact that user. Authenticated users can see the link and send a private message, but what I would like to to is to allow anonymous users to see the private message link but when they click on it they should be redirect to the login form. Is there a way to do that? I´ve been googling around and can´t find an answer.

I would really appreciate if you can help me to find a way to to this.

Thanks in advance

# Answer
> 1 votes
This might be what you are looking for (https://drupal.org/node/1988848)

---
Tags: views, users, privatemsg
---


# Question
Title: Module Structure question from perspective of PHP dev
I'm new to drupal, and am unsure how to aproach writing a module. My uni is moving to drupal, and I'm working on getting a courses module to display information about courses at the uni.

List of things I need to implement

* A list of courses in a specific subject that can be put in many places on the site, with differnt subjects
* Search page
    + I think I understand how to do this one, at least
* List of courses based on search parameters
* List sections in a specifc course and term

I've figured out how to make custom pages and pass data around in the url by follwoing the drupal menu example. From here, I could just custom write everything, and return straight html, and it seems like that would work, but not be the "correct" way to do it in drupal.

The data will be available in an API of sort, I don't know much about it yet. NOrmally I would just make a data class that had sample data in it, and deal with the data later, but it seems like this won't work in drupal.

Should I be aproaching this by trying to get the views module to do the views for my module? It seems like this would be the correct way to do it, but the query is stupidly complex SQL, and the output can't just be a list.

Also, where is a good tutorial on how I should be using content types? It seems like I should be using that effectively as a data class, that somehow gets passed to a view(possibly the views module, maybe just a view I write myself for a page), which renders it, but I haven't been able to figure it out.

Sorry that there is no concrete answer for this, I just really need pointers on how to aprocah drupal modules.

# Answer
**Content Types** and /or entities would be the way to go about this. Content types you can think of as objects that are fieldable. So for example your course would have fields that would represent an objects property. All content types are node and accessed similarly and can be distinguished by a node id (nid). Content types automatically integrate into views.

**Views** can be used to display your data on the courses and they can be filtered by using exposed filters, or filtered by using contextual filters (arguments from the URL). Content types are automatically usable in views along with their fields

**Entity references** are the backbone of relationships in drupal. In an object sense you can have a one to one, one to many relationships with other objects or content types. So your course may have sections and what not so in drupal you would create a content type of both Course and Section and then reference them using the entity references module. See entity reference module which must have the entity api module

**Taxonomy** is a way to tag stuff so if you want to tag a course a certain subject you could use a field that is a taxonomy reference.
> 1 votes

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


# Question
Title: On export Managed_files With Features No UUID Added
I have a custom field of type 'managed\_file' along another field of type - 'file'. This node is exported into feature. The field with 'file' type gets UUID attached while it does not for 'managed\_file' field. In the database table 'file\_managed', there are UUIDs for all the files included ones uploaded with 'manged\_file'. Why is it not including the UUID for managed\_file custom fields in the feature? Is there a separate module for this? Any suggestions how to best export/import files? Your help is much appreciated

uuid 7.x-1.0-alpha5+17-dev, uuid\_feature 7.x-1.0-alpha3+15-dev, strongarm - 7.x-2.0, Drupal 7.26

# Answer
I end up creating module for handling assets exporting via Features either as custom field or not. Here is write up http://margotskapacs.com/2014/04/handling-artifacts-for-custom-module-in-drupal/
> 0 votes

---
Tags: files, entities, features
---


# Question
Title: Undefined index: cck_time_field_presave()
I have imported about 2 thousand nodes that include start time.

I have imported and the formating and time looks the way it should.

Now if i try to publish the nodes i get following error -

> Notice: Undefined index: hour in cck\_time\_field\_presave() (line 97 of public\_html/sites/all/modules/cck\_time/cck\_time.module).

The time fields gets changed to null time.

But if I open the node and save it - the node is saved with the correct time as it was before.

Im at a loss.

And hoping for some guidance.

# Answer
> 0 votes
Go to CCK Time then open cck\_time.module

find this:

```
function cck_time_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items)

```

change this:

```
if (($items[0]['hour'] === '') || ($items[0]['minute'] === ''))

```

to this:

```
if ( empty($items[0]['hour']) || empty($items[0]['minute']) )

```

It helped solving my problem getting the same error **Undefined index: cck\_time\_field\_presave()**

---
Tags: datetime
---


title: Node filtering based on taxonomy terms

text:
# Question
Title: Node filtering based on taxonomy terms
I followed this post, I am able to filter nodes based on content type and other parameters

```
http://test/api/node?parameters[nid]=1&parameters[status]=1

```

but I am not able to filter based on taxonomy terms (tid), problem is with nested json, how do I pass the parameter on URL for nested json?

I don't want to use services\_views.

Below is my json data,

```
{
    "vid": "142",
    "uid": "2",
    "title": "Tomato",
    "log": "",
    "status": "1",
    "comment": "1",
    "promote": "1",
    "sticky": "0",
    "nid": "142",

..
..

 "field_category": {
        "und": [
            {
                "tid": "2"
            }
        ]
    },
}

```

# Answer
This is what I tried and it works perfectly,

```
http://test/api/node?parameters[nid]=1&parameters[field_category]=1

```
> 0 votes

---
Tags: services
---


title: Comments Notification

text:
# Question
Title: Comments Notification
Where is the comment notification when anonymous users send a comment? I don't find any notification in dashboard, or other pages to approve comments.

# Answer
> 3 votes
The list of unapproved comments is on admin/content/comment.

Unapproved comments are the comments left from users without the permission of skipping the comment approval, which is given in admin/people/permissions.

In the site where I took this screenshot, authenticated users are allowed to skip the comment approval, which means that any user with an account is able to write a comment without it gets approved before to be visible to every user.

# Answer
> 0 votes
If you want to receive an email notification when the anonymous user posts a comment, you can use the Anonymous Publishing module.

This module can be set up to send e-mail to administrators when anonymous content (inclusing comments) is created.

---
Tags: 7, comments
---


# Question
Title: How to use Views to make a Block that displays a field from the author's profile?
using Drupal 7.

I have added a field in the user account settings called "author summary" (field\_author\_summary)

When a user is editing their profile, they can enter a brief description of themselves into this field.

Now, the goal is to display this information as a block, directly under the content they are the author of.

I can't figure out the proper contextual filters and/or relationships.

Any ideas?

Thanks!\

# Answer
> 0 votes
I assumed that you have create a block view. (In case if you want to know how to create, check the revisions of this answer)

**Add Author Relationship**

**Add Fitter Criteria** : User: Current with *author* relationship

select **Is the logged in User** \- yes. Click on Apply.

It pulls a field from a node (the author of the current node) and display it in a block

---
Tags: views
---


title: Filter content in view by user field

text:
# Question
Title: Filter content in view by user field
I'm having problems filtering a view. This is my case:

When a **user registers** he has to select some **suppliers** of a **list** (This is a term reference as a field of my user).

A user can also create a product. Now I would like to show the products where the suppliers reconcile.

This is an example:

**USER 1** has **suppliers A & B**.
**USER 2** has **supplier A**.
**USER 3** has **supplier B**.

**USER A** can see the products of **USER 2** and **USER 3**.
**USER B** can see products of **USER 1**, but **NOT USER 3**.
**USER C** can see products of **USER 1**, but **NOT USER 2**.

But I'm having trouble making this filter in a view. Could someone help me on my way on how to make this?

# Answer
> 1 votes
If the Supplier field lives in the user profile you could make the Product fields dependent on the Supplier field using the **Conditional Fields** module, grant various roles field/taxonomy term access to Product fields using the **Field Permissions** or **Taxonomy Permissions** module, and then create a rule that fires based on Supplier field values that modify user role assignments accordingly

Then you would add *all* Supplier and Product fields to your view, hiding each Product field in the display, and then add a *Global: Custom text* field called "Products" and use replacement patterns to reference each of the hidden fields one after the other. (Make sure the hidden fields appear before the *Global: Custom text* field.) Anything that comes up empty simply won't appear.

If those fields live in a node, that may require a slightly different strategy, but the idea should be more or less the same.

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


# Question
Title: Administrator settings vanished for sheetnode content type nodes
I installed the sheetnode module. It was working ok and then the next time I clicked on "Edit" on the node, the following happened:

I don't know how the links for Publishing options, URL Path settings etc got disabled. I run as an administrator and I edited my permissions too (grant everything under sheetnode module to admin) but to no avail. Please help me get back to those links.

I run drupal 6.

# Answer
> 0 votes
I got the answer myself. I had my CKEditor module disabled while the "Sheetnode CKEditor" module was enabled. So there was some conflict which led to the disappearance of links.

---
Tags: navigation
---


# Question
Title: How to enable Rich text editor for content types
I have installed Ckeditor module and configured it to work with advanced editing options. But couldn't get rich text editor. I even tried all options in content authoring I din't get any solution.

And I want to enable rich text editor for certain fields and webforms. Here my case is the rich text editor should be enabled only some fields not all the fields.

For example, if i have two text fields(text areas) like summary and body. Only the body field should be enabled with rich text format the other should show basic editor. Can I have a clear answer.

# Answer
> 1 votes
Follow these steps:

1. Go and write in drush command prompt-

sudo drush en ckeditor -y
2. Use full HTML format while editing the node as shown in attached screenshot.

---
Tags: entities, webforms, wysiwyg
---


title: How to alter OpenLayers map settings?

text:
# Question
Title: How to alter OpenLayers map settings?
I'm writing a module that will alter map zoom level and map center based on argument from url. But I cant figure out how the `hook_openlayers_map_alter(&$map = array())` works, I'v tried to test this hook with:

```
function openlayers_mapalter_openlayers_map_alter(&$map = array()) {

    $map->center['initial']['zoom'] = '1';

}

```

but it has no effect on maps. What is the proper way to call this hook?

# Answer
have you tried using drupal\_message to make sure it's being called?

Or calling the hook\_openlayers\_map\_alter() function and using map as an array like so:

```
function hook_openlayers_map_alter(&$map = array()) {
    $map['center'] => array( 'lat' => '0',
                             'lon' => '0',
                             'zoom' => '2'
                           );

```

}
> 0 votes

# Answer
You have to clear cache to make the hook works.
> 0 votes

---
Tags: 7, hooks, javascript
---


# Question
Title: How do I use add the image field Product entity in to my view?
I'm using Drupal 7.28, Views 7.x-3.8 and Commerce 7.x-1.9.

I've created lots of products in the Products section and I've also created some product displays. For example, I have created a round oak table, square oak table and a rectangle oak table. I have then created a product display called Old Oak Table and I've referenced the three oak tables.

Now I need to create a view that lists all tables. My view needs to show one image from each product display.

I was unable to add the image field to my view - so I added a Product reference and I'm now able to add the Image field which is on the Product entity not the content type.

Now that I've added the image field, my view shows every product image so for example the round table, the square table and the rectangle table - I just need it to show one image from each product display, so for example just one image from the Old Oak Table product display.

Thank you very much for reading.

# Answer
> 1 votes
To show just a single image, you can add a filter to the view to restrict the product reference field to delta 0.

---
Tags: views, commerce, entities
---


# Question
Title: URL redirects within drupal 7 site breaking image display in blocks
I am developing a drupal 7 site where 4 pages have url redirects from a parent page within the site. I have a block in the footer that is shown on all pages but the 4 pages mentioned above do not display the image within that block. I'm thinking that it must have something to do with the redirects as it is only these 4 pages that don't display the image. All other pages with that block show the image up just fine.

# Answer
In your situation a recommendation is to use relative path and not activate if this is your only reason the php as input type. Your code will be

```
div class="img-holder-getintouch"><img src="/sites/default/files/footer-get-in-touch.png" alt="" width="250" height="291" /></div>

```

You will see that i added just a slash as of this tells the site to request the file from http://www.example.com/sites.... this way you can do a migration and the images will still work.
> 0 votes

# Answer
Well, this image will play nice only if you are in your homepage or something and then the relative path is as: `http://site.com/sites/default/files/footer-get-in-touch.png`

Off course this won't play for other paths as this is invalid

`http://site.com/<PATH>/sites/default/files/footer-get-in-touch.png`

Quick Solution:

Enable php filter module, to be able to write php inside the blocks contents and provide correct image path for all cases

```
<?php
    global $base_path;
?>
<div class="img-holder-getintouch">
    <img src="<?php echo $base_path; ?>sites/default/files/footer-get-in-touch.png" alt="" width="250" height="291" />
</div>

```
> 1 votes

---
Tags: blocks, media, uri
---


title: Override Load More button for Views

text:
# Question
Title: Override Load More button for Views
I am currently using Drupal Views and its "Load More" Pager. I wish to change the words on the button to say something else instead.

It looks like the UI does not provide me with an easy way to do that, so I am wondering if there is any easy programming way to achieve that.

# Answer
> 0 votes
There is an option to change the text. Follow the steps

In you 'view' you can find **PAGER** settings

Click on Settings to change the text

Enter the text whatever you want to see at Output

---
Tags: views, paging
---


# Question
Title: Messed Up Drupal Site, truncated all cache, menu_router, registry_file and now I can't access site
After disabling comment module, I could not access some modules, so I researched how to get that fixed and end up following this. I cleared all the cache\_table, menu\_router and registry\_file.

This is the exact command I ran:

```
TRUNCATE `cache`;
TRUNCATE `cache_block`;
TRUNCATE `cache_bootstrap`;
TRUNCATE `cache_entity_og_membership`;
TRUNCATE `cache_entity_og_membership_type`;
TRUNCATE `cache_field`;
TRUNCATE `cache_filter`;
TRUNCATE `cache_form`;
TRUNCATE `cache_image`;
TRUNCATE `cache_libraries`;
TRUNCATE `cache_menu`;
TRUNCATE `cache_metatag`;
TRUNCATE `cache_page`;
TRUNCATE `cache_path`;
TRUNCATE `cache_token`;
TRUNCATE `cache_update`;
TRUNCATE `cache_variable`;
TRUNCATE `cache_views`;
TRUNCATE `cache_views_data`;
TRUNCATE `menu_router`;
TRUNCATE `registry_file`;

```

Now I have an empty site, I can't browse or go to anywhere. Even the front page Gives page not found error saying "/" not found.

I tried to rebuild the menu and registry with these commands but it didn't work.

```
chdir('path/to/site/root');
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

registry_rebuild();
menu_rebuild();

```

I tried with drush using `drush cc all` but it says

> No Drupal site found, only 'drush' cache was cleared. but `drush status` shows it find the site

```
 Drupal version         :  7.23
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php5/cli/php.ini
 PHP OS                 :  Linux
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /path/to/site/root

```

What can I do? How to get the site back after this?

# Answer
Best thing is to restore it from a backup to make it work.

If you want to fix it, replicate the site from a back up (db and files). Then truncate tables one by one to see which one is causing the problem (It should be menu\_router).

Truncate first all cache table and check Truncate menu\_router and check Truncate registry\_file and check.

About the code you did, try to remove registry\_rebuild from your code. Create a file fix.php and paste this code

```
<?php
error_reporting(E_ALL);
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

menu_rebuild();

```

save it into your drupal root and visit mysite.com/fix.php .
> 3 votes

# Answer
I assume you've got no backup from *before* you messed up the site, so that the *obvious* solution - using your favourite SQL management tool (e.g. *phpMyAdmin* or the CLI SQL program) to restore from backup - is not an option?

* Create a backup *now* (using whatever database management tool you have).
* Create a clean install of the Drupal core.
* Look at your new nice and shiny database, print out the schema (a list of the tables it now contains).
* Roll back from the backup all the tables that exists in this schema, *except* the following (all of these may not even exist in your backup):

+ `{accesslog}` – access log generated by statistics module (disabled by default);
    + `{batch}` – connects a user to his/her batch (a crashed site has no active users);
    + `{cache*}` – the cache just optimises page loads, always safe to truncate;
    + `{flood}` – flood log generated by built-in flood control;
    + `{registry_file}` \- code registry, rebuilt when cache is cleared;
    + `{search*}` – loses search indices and statistics, indices is regenerated by cron;
    + `{sessions}` – loses user session (a crashed site has no active users);
    + `{syslog}` – system events log generated by syslog module (disabled by default);
    + `{watchdog}` – loses log messages.
* Note that list above is *always* safe to exclude from rollbacks. They only contain ephemeral data, and may contain bad data if a site has crashed. There is a comment after each, explaining what it is used for.
* Also roll back all tables starting with `field`.
* Install all the contributed and custom modules you absolutely need, but skip those you suspect make trouble.
* Roll back from the backup all the tables that belongs to these modules, module by module. You can see what table a belongs to because the table name always starts with the module's machine name. Check that your site is healthy after each round of rollbacks.

Usually, this gives you back a working site, with no contents lost.
> 1 votes

---
Tags: routes, caching, debugging
---


# Question
Title: WYSIWYG CKEditor config.js not being used?
I've installed and configured the WYSIWYG module (latest dev) to use CKEditor, and I have downloaded the latest version of CKEditor (latest full release) to `sites/all/libraries`. I'm able to use the editor.

I need to customize a few additional things, so I'm applying configuration changes to config.js in `sites/all/libraries/ckeditor/config.js`. However, it seems like this file is not even being used or read at all. I tested this hypothesis by adjusting the stock `config.js` as so:

```
CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here. For example:
    config.allowedContent = true;
    alert('Hello!');
};

alert('World!');

```

Whenever I load the editor, I would expect to get either one or two alerts, one saying either `Hello!` or `World!` or both. However, no alert windows are launched.

How does one customize the configuration of CKEditor when using the WYSIWYG module?

# Answer
This took some research, but I found this article which describes how to do it.

The meat of the article is the following hook, which defines a custom config file:

```
<?php
/**
 * Implements hook_wysiwyg_editor_settings_alter()
 */
function MODULENAME_wysiwyg_editor_settings_alter(&$settings, $context)
{
    // The $context variable contains information about the wysiwyg profile we're using
    // In this case we just need to check that the editor being used is ckeditor
    if ($context['profile']->editor == 'ckeditor')
    {

        // The $settings variable contains all the config options ckeditor uses.
        // The array keys correspond directly with any setting that can be applied
        // to CKEditor - as outlined in the CKEditor docs:
        // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
        // Another way to override configuration is to use your own configuration javascript
        // file. In this case, we're going to add our own configuration file that will
        // Hold our stylesSet customizations...
        $settings['customConfig'] = base_path() . drupal_get_path('module', 'MODULENAME') . '/ckeditor_custom_config.js';
    }
}

```
> 13 votes

# Answer
I had a similar problem, and it turns out that CKEditor was caching the config.js file. Not even pressing control-F5 would solve that: I had to delete the cache manually from the browser's setting.

Hope this helps someone =)
> -1 votes

# Answer
All you need to do is to edit `/sites/all/modules/ckeditor/ckeditor.config.js` instead of `ckeditor/config.js` file.
> -3 votes

---
Tags: 7, wysiwyg
---


title: Get the default value of a variable

text:
# Question
Title: Get the default value of a variable
I want to display the default value of a variable when no value is set. I checked the Drupal 8 documentation pages, but I couldn't find any information about the default value.

> In Drupal 7 if variable value is not set then default value is displayed.
>
> ```
> variable_get('variable_name', 'hello');
>
> ```
>
> If "variable\_name" is not set at that time, *hello* will be returned.

Now for Drupal 8 I am trying the following way.

```
$config = $this->configFactory->get('module_name.settings');

$config->get('variable_name', 'hello'),

```

I am not getting *hello*.

# Answer
Your module ships with a default config; it gets installed. Now your config has the default value; if someone overrides it, it doesn't have one anymore. `$config->get('foo')` doesn't have a default value.
> 8 votes

---
Tags: 8
---


# Question
Title: Language specific menu items when adding content
I am building a bilingual site that's English and French. When I add a content item in English, then go to Menu Settings, click on Provide a menu link, and click on Parent Item drop down menu, I get *all* the menu items English and French. How do I get the drop down menu item to display only English menu items if my content is in English language?

# Answer
No one gave me an answer, so I decided to modify the core, which is completely pathetic. In hacking the core, I was able to add a `class="en"` or `class="fr"` to the option of a select menu. Now I can use jquery to hide and show options as needed. Here's a git diff of changes I made to the core system.

```
diff --git a/includes/form.inc b/includes/form.inc
index a337b03..55f705f 100644
--- a/includes/form.inc
+++ b/includes/form.inc
@@ -2564,7 +2564,14 @@ function form_select_options($element, $choices = NULL) {
       else {
         $selected = '';
       }
-      $options .= '<option value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
+       $choice_text = check_plain($choice);
+       $class=' class="opt"';
+       if(preg_match('/\{\{\w{2}\}\}/',$choice_text,$matches))
+       {
+               $class = ' class="'.preg_replace('/[^\w]/','',$matches[0]).'"';
+               $choice_text = preg_replace('/\s\{\{\w{2}\}\}/','',$choice_text);
+       }
+      $options .= '<option value="' . check_plain($key) . '"' . $selected . $class.'>' . $choice_text . '</option>';
     }
   }
   return $options;
diff --git a/modules/menu/menu.module b/modules/menu/menu.module
index fc8f68a..b991970 100644
--- a/modules/menu/menu.module
+++ b/modules/menu/menu.module
@@ -408,7 +408,7 @@ function _menu_parents_recurse($tree, $menu_name, $indent, &$options, $exclude,
       if ($data['link']['hidden']) {
         $title .= ' (' . t('disabled') . ')';
       }
-      $options[$menu_name . ':' . $data['link']['mlid']] = $title;
+      $options[$menu_name . ':' . $data['link']['mlid']] = $title.' {{'.$data['link']['language'].'}}';
       if ($data['below']) {
         _menu_parents_recurse($data['below'], $menu_name, $indent . '--', $options, $exclude, $depth_limit);
       }
diff --git a/themes/seven/seven.info b/themes/seven/seven.info
index 599879f..b625854 100644
--- a/themes/seven/seven.info
+++ b/themes/seven/seven.info
@@ -12,6 +12,7 @@ regions[page_top] = Page top
 regions[page_bottom] = Page bottom
 regions[sidebar_first] = First sidebar
 regions_hidden[] = sidebar_first
+scripts[] = lang.js

 ; Information added by drupal.org packaging script on 2011-05-25
 version = "7.2"

```

And I added a js file called /themes/seven/lang.js which toggles the options to appropriate language.

```
if (typeof jQuery == 'function'){
  jQuery(document).ready(function($) {
        $('#edit-language').change(function(){
                if($(this).val() != 'und')
                {
                        $('#edit-menu-parent option').css('display','none');
                        $('#edit-menu-parent .'+$(this).val()+', #edit-menu-parent .opt').css('display','block');
                }
        });
  });
}

```

Please suggest a better way to achieve the same objective as this answer.
> 1 votes

# Answer
My experience is that user 1 (admin) sees all menu items no matter their language setting, but i'm not sure if it's meant to be or if it's a bug.

Better have a look at the Issues of i18n and in particular at Drupal 7 & i18n: Only current language items visible in Menu Settings / Parent menu item
> 3 votes

# Answer
After struggling on issue my solution was:

* Enable -\> **Multilingual select** (module)
* Go To: **admin/config/regional/i18n/select**
* Check the *Select nodes by language*
> 1 votes

# Answer
I think you can use Drupal's hook\_form\_alter to filter out items that are not in the user's language or neutral.

It would be something like this:

```
function hook_form_alter(&$form, &$form_state, $form_id) {
    global $user;

    foreach ($form['menu']['link']['parent']['#options'] as $key => $option) {
        $keyArray = explode(':', $key);
        $mid = $keyArray[1];
        $node = menu_node_get_node($mid);

        if ($node && ($node->language !== $user->language && $node->language !== 'und')) {
            unset($form['menu']['link']['parent']['#options'][$key]);
        }
    }
}

```

Terribly late answer, but probably relevant for people finding this on Google today.
> 0 votes

---
Tags: 7, routes, i18n-l10n, nodes
---


# Question
Title: Why drush sql-sync fails with mysqldump unknown variable error?
I am having issues trying to sync my staging server with my local server using `drush sql-sync` command.

I've set my aliases right and the same configuration is working with my development server and local machine.

Here are the issues I get once I type in:

```
drush sql-sync @stag @local

```

I get the standard warning about backing up my target database.

Then I'm having this error:

```
stdin: is not a tty
mysqldump: unknown variable 'table_cache=67108864'
Database dump failed

```

So I am pretty sure this has something to do with MySQL configuration on the staging server.

From what I've googled/read, a large value for the `table_cache` is not necessarily a good one for the server and can slow it down. But I am not sure what a "good" value is.

# Answer
> 0 votes
This does look like an issue with mysql, not Drush. Run your Drush command again with the `-s` flag (simulate);

```
drush sql-sync @stag @local -s

```

Drush will then print out the shell commands that it would execute, without doing anything. You can copy the mysqldump command into your shell, and experiment with the options until the dump works.

---
Tags: database, drush
---


# Question
Title: how do I change the number of nodes that the admin layout shows?
The drupal 7 admin overlay for nodes seems to show 50 by default. How do I a raise or change that number? I've googled for this information, but apparently I'm not guessing the right keywords, because I didn't get any relevant results.

# Answer
> 1 votes
You could create a nodes view of all your nodes. Set the pager to whatever number of nodes you want to view, and put various exposed filters on the View to help you find the content you need.

You could also access your database directly. Depending on your hosting provider, you probably have access to some sort of database interface. PhpMyAdmin is very common. If you go to the nodes table, you can view as many nodes as you'd like and figure out the NID you need to pull up the node. Clunky, but it'll work.

There's an old doc page for Drupal 6 regarding this same issue, but based on some of the comments, I don't think it'll work for D7. Worth a shot, though.

# Answer
> 0 votes
In Drupal 7 you can find it in /modules/taxonomy.admin.inc (line 262 in current version, 7.28):

$page\_increment = variable\_get('taxonomy\_terms\_per\_page\_admin', 50); // Number of terms per page.

---
Tags: 7, users, modal-dialogs
---


# Question
Title: Migrate a filefield to another filefield?
I'm using Drupal 7. I have a field called **field\_a** which is a *file-field* and want to create another *file-field* called **field\_b**. What I want to do is to *migrate* all the files from **field\_a** to **field\_b**, then I also want to erase the records from **field\_a** without erasing **field\_a**. Note that **field\_a** and **field\_b** are in the same content type.

Is it possible? Is there a way to do this with VBO?

# Answer
The best way to do this without writing a module or messing with your database is to use views bulk operations with rules.

Here is an example of moving a file from one file field to another. You'll have to change the field names before you import this rule.

Basically add a rules component- then add your conditions and action

**Variables**

Datatype Node

Usage Parameter

**Conditions**

Entity has field - field\_a

Entity has field - field\_b

**Actions**

Create a loop to loop over multiple values in field\_a.

Inside loop add item to list

Inside same loop remove item from list

Outside of loop Save your node.

```
{ "rules_fa_fb" : {
    "LABEL" : "Move resource files from one field to another.",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "TAGS" : [ "Dev" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "nodes" : { "label" : "nodes", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "nodes" ], "field" : "field_field_a" } },
      { "entity_has_field" : { "entity" : [ "nodes" ], "field" : "field_field_b" } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "nodes:field-field-b" ] },
          "ITEM" : { "file" : "files" },
          "DO" : [
            { "list_add" : {
                "list" : [ "nodes:field-field-a" ],
                "item" : [ "file" ],
                "unique" : 1
              }
            },
            { "entity_save" : { "data" : [ "resource" ], "immediate" : "1" } },
            { "list_remove" : { "list" : [ "nodes:field-field-a" ], "item" : [ "file" ] } }
          ]
        }
      },
      { "entity_save" : { "data" : [ "nodes" ], "immediate" : 1 } }
    ]
  }
}

```

Then create the view with a bulk operations field, you'll need to change some values to import into your system.

```
$view = new view();
$view->name = 'move_files_from_on_field_to_another';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Move files from on field to another';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Move files from on field to another';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_operations'] = array(
  'action::node_assign_owner_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_revision' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::flag_node_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_sticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_unsticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_modify_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'show_all_tokens' => 1,
      'display_values' => array(
        '_all_' => '_all_',
      ),
    ),
  ),
  'rules_component::rules_fa_fb' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 1,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::node_promote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_publish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpromote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_save_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_send_email_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::redhen_fields_email_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_by_keyword_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::auto_entitylabel_entity_update_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::pathauto_node_update_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Files - for digital */
$handler->display->display_options['fields']['field_resource_file']['id'] = 'field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['table'] = 'field_data_field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['field'] = 'field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_resource_file']['delta_offset'] = '0';
/* Field: Content: Files - for print */
$handler->display->display_options['fields']['field_files_for_print']['id'] = 'field_files_for_print';
$handler->display->display_options['fields']['field_files_for_print']['table'] = 'field_data_field_files_for_print';
$handler->display->display_options['fields']['field_files_for_print']['field'] = 'field_files_for_print';
$handler->display->display_options['fields']['field_files_for_print']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_files_for_print']['delta_offset'] = '0';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'resource' => 'resource',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'admin/move-files-from-on-field-to-another';

```
> 2 votes

# Answer
You might need to get creative on this one. Can you accomplish this by just renaming labels to your liking and create new fields? If you're comfortable making database changes you could always change the name of field\_a to field\_b in all of its instances (which may or may not be a nightmare given your patience and time frame).

But to my knowledge there is no quick solution to copy all of the data in one field to another without either writing a fancy Migration Migration script, or renaming fields in the database.
> 1 votes

# Answer
Gotta second what Johnathan wrote, there is no easy way to do this. In all honesty, I don't understand why you would want to either. It sounds like you just want to literally change the name of the field in Drupal, and unless there is a good reason to do that you're much better off just changing the label associated with the field in the content type.

If you absolutely have to change the name of the field, then identify all the instances in the database where that field name is mentioned (i.e. columns names, entries in various configuration settings, etc.) and then physically change them through whatever database administration mechanism you have at your disposal.

Before you do anything like that though, be sure to backup your database in full.
> 0 votes

# Answer
You can easily achieve this with Migrate 2, check this: Migrate Contents in Drupal 7 Using Migrate 2

This is the query and mapping part I wrote for you, you can try using it in your migrate class.

```
<?php
// Grab data from tables in source database
$query = db_select(SOURCE_DATABASE . '.node', 'n')
      ->fields('n', array('nid', 'vid', 'type', 'language', 'title', 'uid', 'status', 'created', 'changed', 'comment', 'promote', 'sticky', 'tnid', 'translate'))
      ->condition('n.type', NODE_TYPE, '=');
// Grab the field
$query->join(SOURCE_DATABASE . '.' . NODE_TYPE, 'ct', 'ct.vid = n.vid');
$query->addField('ct', FIELD_A);
if (module_exists('statistics')) {
  $query->join(SOURCE_DATABASE . '.node_counter', 'nc', 'n.nid = nc.nid');
  $query->addField('nc', 'totalcount');
  $query->addField('nc', 'daycount');
  $query->addField('nc', 'timestamp');
}
$query->orderBy('n.nid', 'ASC');
// Set up our destination - nodes of type migrate_example_beer
$this->destination = new MigrateDestinationNode(NODE_TYPE);

// Mapping: Assign mappings TO destination fields FROM source fields.
$this->addSimpleMappings(array('nid', 'vid', 'type', 'language', 'title', 'uid', 'status', 'created', 'changed', 'comment', 'promote', 'sticky', 'tnid', 'translate'));
$this->addFieldMapping(FIELD_B, FIELD_A);
$body_arguments = MigrateTextFieldHandler::arguments(array('source_field' => 'teaser'), array('source_field' => 'format'));
    $this->addFieldMapping('body', 'body')->arguments($body_arguments);
if (module_exists('statistics')) {
  $this->addSimpleMappings(array('totalcount', 'daycount', 'timestamp'));
}
?>

```
> 0 votes

---
Tags: 7, files, views
---


# Question
Title: form jquery events fired multiple times after using AJAX
Does anybody know how to avoid jQuery firing events multiple times after ajax has returned a form.

I have tried with `.once()` and i am still getting 3 click events from one click.

**EDIT**: this was my starting point

```
jQuery('.node_form .form-radio').live('click', function(event) {
  console.log(jQuery(this).attr('id'));
});

```

# Answer
Can we unbind the click event when click event happens and just add the click event again after we receive some responses from Ajax.

The idea is something like this:

```
jQuery('.node_form .form-radio').live('click', function(event) {
    jQuery(this).unbind('click');
    //make some ajax calls and if it returns something. We will bind the click event again.
});

```
> 1 votes

# Answer
Use `.one` versus `.live`...like so:

```
jQuery('.node_form .form-radio').one('click', function(event) {
  console.log(jQuery(this).attr('id'));
});

```
> 0 votes

---
Tags: forms, ajax, javascript
---


# Question
Title: Can I use a universal no-results display for Views?
In Drupal 7, is there a way to set a default, universal No results message for Views? Which of these following options should work?

Should I use a `Rendered Entity`? If so can I create a node (say, called 'no-results')? Is the Entity Id field, the URL of the entity?

# Answer
You can copy views-view.tpl.php template to your theme folder, then modify relevant part.

```
<?php if ($rows): ?>
  <div class="view-content">
    <?php print $rows; ?>
  </div>
<?php elseif ($empty): ?>
  <div class="view-empty">
    <?php print $empty; ?>
  </div>
<?php endif; ?>

```

To:

```
<?php if ($rows): ?>
  <div class="view-content">
    <?php print $rows; ?>
  </div>
<?php else: ?>
  <!-- HTML for no results here -->
<?php endif; ?>

```

You can keep the `<?php elseif ($empty): ?>` part if you still want to be able to override your custom output.

Cheers,
> 1 votes

---
Tags: views
---


title: "Time ago" from "date end" in views

text:
# Question
Title: "Time ago" from "date end" in views
How to print Date Field in Views in format "time ago" for "end dates"? If I config field in views like: Display: End date only, Formatter: Time ago. I get duration form Start date :(

Example for today (7 jun 2014). date field values: start 1 jan 2013, end 1 jan 2014. I wanna get: Expired - 5 mounths and 7 days. But views printing: Expired - 1 year, 5 mounths and 7 days.

# Answer
You can write this in javascript to avoid caching issues and use the users machine time.

https://drupal.org/project/timeago

http://momentjs.com/

http://timeago.yarp.com/

otherwise there is a patch here: https://drupal.org/node/2026545
> 1 votes

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


title: Hook for bulk node modifications

text:
# Question
Title: Hook for bulk node modifications
I'm trying to unpublish nodes where a field = 'Closed'. This field can change so I need to run this bulk operation automatically. I've tried these hooks:

* hook\_update\_N
* hook\_flush\_caches
* hook\_cron

The only hook I've had success with is a view hook (hook\_view\_pre\_render) and sure enough my bulk operation worked. Here's my code for the operation:

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'custom_type')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_status', 'value', array( 'Closed' ), '=' );

$result = $query->execute();

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);

 foreach ($nids as $nid) {
    $node = node_load($nid, NULL, TRUE);
    // do something awesome
    $node->status = 0;
    node_save($node);
  }
}

```

# Answer
> 0 votes
Where you place the code depends on when you want it to run. Usually these things goes best in `hook_cron()`, but cron needs to be set up to run for that to work.

Instead of doing bulk update you might want to consider changing the published value in `hook_node_presave()` instead, i.e. when saving the node. Example (untested):

```
function mymodule_node_presave() {
  $w = entity_metadata_wrapper('node', $node->original);
  $var = $w->field_status->value();
  if ($var == 'Closed') {
    $w->status = 0;
    $w->save();
  }
}

```

Concerning your code otherwise it should work afaik, but it would be better to load all nodes at ones. Something like this:

```
$nodes = node_load_multiple(array_keys($result['node']));
foreach ($nodes as $node) {
  $w = entity_metadata_wrapper('node', $node);
  $w->status = 0;
  $w->save();
}

```

Cheers,

---
Tags: database
---


# Question
Title: add a search field which search for values of specific field in a content type
I've created a content type "Submission", which have many fields. One of them is "ID".

Now, I need a search box (apart from regular search box). It should be searched with ID value, it should display search result of content which have this ID value.

Any suggestions please.

# Answer
> 1 votes
You can create a separate Search Page using Views: Here is a tutorial (http://webwash.net/tutorials/how-create-search-pages-using-views-drupal-7)

Views:

> You like the default front page view, but you find you want to sort it differently. You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically. You use /tracker, but you want to restrict it to posts of a certain type. You like the idea of the 'article' module, but it doesn't display articles the way you like. You want a way to display a block with the 5 most recent posts of some particular type. You want to provide unread forum posts. You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of Month, YYYY (X) where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.
>
> Views can do a lot more than that, but those are some of the obvious uses of Views.

---
Tags: search
---


# Question
Title: How to re-enable content notifications for Notify?
I turned off content notifications for all users for Notify some time ago because it was sending duplicates. There was a checkbox somewhere that I unchecked. It is not in notification settings.

This is Drupal 6.

# Answer
> 0 votes
Reading your comment on my question above, I guess you're using Actions & Triggers in Drupal 6.

To see which actions you have defined or to define new actions, go to Administer \> Site Building \> Actions. There e.g. you can define an action for sending an email. From your question I think you already have done that (in the past).

To assign this action to an event, you have to go to Administer \> Site Building \> Triggers. There you can choose (under Content) to assign an action to an event, such as published or updated content.

# Answer
> 0 votes
There is no master checkbox or switch for the *admin* in Notify (there is one for each user).

To turn of notifications for all users with one click, you disable the module, to turn it on again, you re-enable the module. This is the same for the Drupal 6 and Drupal 7 versions.

As for the per user master switch, is can be found under *My account ➔ Notification settings*, as shown on the screenshot below.

For more about the use of this module, please see the community documentation.

# Answer
> -1 votes
The documentation I was looking for is here: https://drupal.org/documentation/modules/notify

The "master switch" appears to be a feature of the D7 version of the module.

---
Tags: notifications
---


title: Clear Cache without logging in

text:
# Question
Title: Clear Cache without logging in
I added an if statement around the content render php in my page.tpl.php file. Only problem is I made a mistake and accidentally prevented it from rendering content on any page. I cleared the cache and logged out to test it, and realising my mistake I corrected the template file. But now I can't log back in to clear the cache again as my site won't render content and thus won't render the login box.

Can someone give me a way in Drupal 7 to either log in without the login in box (like a way to render the login box separately to the content) or a way to clear the cache?

# Answer
> 6 votes
The best solution I found in the end was to do it through phpmyadmin. I logged in and emptied any tables that had "cache" at the start of their name. Easy if you don't work in drush.

# Answer
> 12 votes
i. If you have drush installed (http://drupal.org/project/drush) — if you don't have it, think about that next time :), open up the console (WIN+R) in Windows or Ctrl+Alt+T in Linux point to your site folder (e.g. `cd /www/mydrupalsite/` and type:

```
 $ drush cc all

```

from the command line.

ii. Another method is to log into your phpmyadmin select your cache\_ tables and flush/empty them.

# Answer
> 5 votes
In addition to the options mentioned above, as a last ditch effort you could call the function `drupal_flush_all_caches()`, to clear all caches.

You may do this by placing the code below in a php file in your document root and visiting it with a browser:

```
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_flush_all_caches();

```

I have not tested this code, and make sure to remove it after you have cleared your caches.

# Answer
> 2 votes
You can set

```
$update_free_access = TRUE;

```

in settings.php (around line 226) and browse to /update.php. This will clear the cache.

# Answer
> 0 votes
You can clear the Drupal cache by executing the following command either in the Windows command console or from a .bat file (or from the Linux console):

> php -r "define('DRUPAL\_ROOT', '../web'); chdir(DRUPAL\_ROOT); define('MAINTENANCE\_MODE', 'update'); global $\_SERVER; $\_SERVER\['REMOTE\_ADDR'\] = '127.0.0.1'; require\_once DRUPAL\_ROOT.'/includes/bootstrap.inc'; drupal\_bootstrap(DRUPAL\_BOOTSTRAP\_FULL); drupal\_flush\_all\_caches();"

Just make sure that DRUPAL\_ROOT in the code points to the Drupal directory.

# Answer
> 0 votes
```
delete from cache where cid <> '';
delete from cache_block where cid <> '';
delete from cache_bootstrap where cid <> '';
delete from cache_field where cid <> '';
delete from cache_filter where cid <> '';
delete from cache_path where cid <> '';
delete from cache_libraries where cid <> '';
delete from cache_image where cid <> '';
delete from cache_page where cid <> '';
delete from cache_token where cid <> '';
delete from cache_update where cid <> '';
delete from cache_views where cid <> '';
delete from cache_views_data where cid <> '';

```

---
Tags: 7, users, caching
---


# Question
Title: How to get event node to pull in data from a seperate node?
I'm trying to setup an events calendar in drupal 6. I have an event content type and a location content type. My problem is that I want the event node to display relevant data from the location node such as location name, address, hours, etc.. I'm not sure of the best way to set this up?

Additional info: My event content type has a cck node reference that points to the location node. I was looking at the reverse node reference module but wasn't sure if that was necessary, maybe this can be accomplished using existing views and block functionality.

# Answer
> 0 votes
As I understood from you question you want to know the best way to display some information from the location inside the event node view page, if this the case you might need to create a block view (from views module) takes the reference node location (nid) in the current node event being viewed, and as you have the view you can display all the information needed.

I hope this will help.

# Answer
> 0 votes
You should be able to edit the formatter on the manage display tab. Instead of the default formatter, which is something like link to referenced node, change it to use the rendered node

---
Tags: 6, nodes
---