# Question
Title: How to join another table via altering view query as exposed filter
Hi I have created a view and exposed the view with node title. Searching is done on title and its working fine. But I have a requirement that when some one searches through title, the search text should also be matched to body field and if the content is found in any of the field it should display result. Like if the search text is not in title but found in body it should display the result as found.Please help

# Answer
Add a filter from the `Global` group as a `combined filter`. Then assure the View has both the `title` and `body` fields avaiable in the View (they can be `hidden` from the View if you want).

Then set the `combined filter` to use the `title` and `body` fields when a search is done.

Then your single exposed filter will show results from your query criteria from either of the fields.
> 0 votes

---
Tags: views
---


# Question
Title: How to reload Google chart on ajax submit?
I have a simple Drupal form. I am using `hook_theme()` to draw a chart right under my form. I am using *Google chart API*. When the page loads first time, my chart appears with no problems. But when I submit my form I use `ajax_command_replace()` to replace my chart with another one (without page reload). The goal is to make it possible to send variables from my form right to my theme function and draw another chart according to them. The problem is when I push the submit button the old chart disappears (which is good) and the new chart doesn't appear (which is bad). What am I doing wrong?

# Answer
The issue is already created on drupal.org for this and you can try the code from the below mentioned url: Ajax load of chart
> 1 votes

---
Tags: forms, ajax, charts
---


# Question
Title: How to create a drag & drop sorting interface programmatically?
If you have seen the **Views** module, there is "**sorting criteria**", where we add fields and then rearrange fields to set the priority. In order to rearrange, we click on "**rearrange**" link and all fields get a **draggable** UI so that we can move it up or down to set sorting priority.

**How can I do this thing exactly programmatically?**

# Answer
Here is a drupal\_add\_tabledrag function using which you can add draggable functionality programmatically.

> Assists in adding the tableDrag JavaScript behavior to a themed table.
>
> Draggable tables should be used wherever an outline or list of sortable items needs to be arranged by an end-user. Draggable tables are very flexible and can manipulate the value of form elements placed within individual columns.

See this blog for example. You may need to imprement theme function.

```
$element = $vars['element'];
drupal_add_tabledrag('sample_table', 'order', 'sibling', 'item-row-weight');

$header = array(
  'label' => t('Attribute'),
  'checkbox' => t('Enabled/disabled'),
  'weight' => t('Weight'),
);

```
> 1 votes

# Answer
Here are the 3 simple steps to create a form with drag and drop ordering:

> 1. Implement hook\_menu, to register the URL of the form

```
function module_name_menu() {
$items = array();
$items['admin/config/content/module_name/manage'] = array(
    'title' => 'Recent News: List Links',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('module_name_manage'),
    'access arguments' => array('access administration pages'),
);
}

```

> We will use the following function to render the form:

```
function module_name_manage() {
$db_result = db_query( "select id,title position from recent_news order by position");
// create array and add one element called data
$rows= array();
$form['#tree'] = TRUE;
$max = 60;
foreach($db_result as $row){
    $title = $row->title;
    if(strlen($title)>$max)
        $title = substr($title,0,$max).' ...';
    $form['slides'][$row->id]['id'] = array(
        '#type' => 'hidden',
        '#default_value' => $row->id,
    );
    // Textfield to hold content id.
    $form['slides'][$row->id]['title'] = array(
        '#type' => 'item',
        '#title' => $title
    );
    // This field is invisible, but contains sort info (weights).
    $form['slides'][$row->id]['weight'] = array(
        '#type' => 'weight',
        '#title' => t('Weight'),
        '#title_display' => 'invisible',
        '#default_value' => $row->position,
    );
}

$form['submit'] = array('#type' => 'submit', '#value' => t('Save changes'));
return $form;
}

```

> 2. implement hook\_theme, to register theme implementation of form with drag and drop support

```
function module_name_theme($existing, $type, $theme, $path) {
return array(
    'module_name_manage' => array(
        'render element' => 'form',
    ),
);
}

```

> And here is the callback function which will render the form with drag and drop capabilities

```
function theme_module_name_manage($variables) {
$form = $variables['form'];

$rows = array();
foreach (element_children($form['slides']) as $nid) {
    $form['slides'][$nid]['weight']['#attributes']['class'] = array('slides-order-weight');
    $rows[] = array(
        'data' => array(
            array('class' => array('slide-cross')),
                drupal_render($form['slides'][$nid]['title']),
                drupal_render($form['slides'][$nid]['weight']),
            ),
        'class' => array('draggable'),
    );
}

$header = array('',t('title'),t('position'));
$output = drupal_render($form['note']);
$output .= theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'slides-order')));
$output .= drupal_render_children($form);

drupal_add_tabledrag('slides-order', 'order', 'sibling', 'slides-order-weight');

return $output;
}

```

> 3. Implement hook\_submit, to handle form submit and save the ordering

```
function module_name_manage_submit($form, &$form_state) {
$slides = array();
foreach ($form_state['values']['slides'] as $slide) {
    $slides[] = array(
        'id' => $slide['id'],
        'weight' => $slide['weight'],
    );
}
if (!empty($slides)) {
    usort($slides, '_module_name_arraysort');
}
$position = 1;
foreach($slides as $slide){
    $id = $slide['id'];
    $sql = "UPDATE recent_news SET position={$position} WHERE id = {$id}";
    db_query($sql);
    $position++;
}

drupal_set_message(t('Ordering have been saved.'));
}

// Custom array sort function by weight.
function _module_name_arraysort($a, $b) {
if (isset($a['weight']) && isset($b['weight'])) {
    return $a['weight'] < $b['weight'] ? -1 : 1;
}
return 0;
}

```

The code is quite long but you can just copy and paste then modify it if necessary. This tutorial is based on Ki Kim's post on http://www.urbaninsight.com/2012/09/11/creating-table-with-draggable-weights-in-drupal-7
> 1 votes

---
Tags: views
---


# Question
Title: Need advice on remote storage for load balanced drupal site
Not quite sure if this is the correct thread to be posting this in, so please feel free to move it if its not.

**Background:**

Our developers have nearly finished developing our Drupal 7 based web application and as with any start up, I am assuming the role of the sys admin, financial controller and everything else under the sun! My experience with Linux is limited to what i've been able to learn through the internet i.e - install and configure apache, mysql, php, memcache, varnish etc.

**Current set up:**

After having spent the best part of 4 weeks stress / load testing various cloud service providers we ended up with Google Cloud.

2x web servers (8 cores + 7.5gb ram each) running: \- Ubuntu 14.04 LTS \- Apache 2.4 (mpm\_event + PHP\_FPM) \- Memcache 3.0

1x database server (4 cores + 26GB ram) running: \- MySQL 5.6

1x Load balancer for the two web servers

**Problem:**

I'm now at the part where I need to decide how / where to run the filesystem for our load balanced Drupal application. As you all know, Drupal stores assets by default on the local disk /sites/default/files. Now, obviously this isn't going to work with a load balanced solution since files that are written to server 1 will not be available to be served from server2.

**Potential solutions?**

These are the following potential solutions I have thought of:

1) Use the Amazon S3 module for Drupal which allows the application to both write and read from an S3 bucket. This seems to be the easiest solution, but i'm a bit reluctant after having spent a lot of time configuring my servers for speed and performance. That extra bit of time its going to take Drupal to write to S3 is what worries me and the fact that I have less control over the situation.

2) This is where my inexperience in terms of implementation lacks, but the second option would be to spin up another instance, mount it to the servers (is it possible to mount another server to both web servers??). Then change Drupal so that it writes to that mounted filesystem. (This seems more performant, but not sure whether possible and certainly a more complex task).

3) Use rsync between the two web servers. Again, my experience with rsync is very limited and i'm not sure whether it would be able to read / write fast enough.

So, that is my current dilemma. And any input whatsoever would be greatly appreciated.

**Thank you!**

# Answer
Upon further research, I decided to boot up another VM instance and mount my two web servers to it then installed NFS server and client respectively. This seems to work very well.
> 1 votes

# Answer
I Have done it for one of my clients, we used separate server as a storage, and we mounted it to 3 servers. Worked very well. Also speaking of performance, have you considered using a CDN. this will make your life much easier. if you have a high traffic site CDN is your way to go to serve static files. take a look at the Drupal CDN module
> 0 votes

# Answer
Thank you sam2de. I've done some further research and actually found out that you can use GCS fuse which is developed by Google and it allows you to mount a Google Storage bucket as an extension to your filesystem on your server instances. I'm gonna give it a try and report on my findings. https://cloud.google.com/storage/docs/gcs-fuse?hl=en
> 0 votes

---
Tags: database
---


# Question
Title: How to retrieve a file or image from a content type?
I'm using services module to get data from database, among those data there is an image.

All fields are loaded except the image, the uri seems to be wrong.

here's the postman response :

```
  "writer": "writer1", <==== ok
  "picture": "public://couverture_harry_0.jpg",<=== not ok(wrong path)
  "review": null, <====== ok
  "date": "2010-02-05",<===== ok

```

I've configured drupal to store on sites/default/files

the picture is there but the real path is :

```
drupal/sites/default/files/couverture_harry_0.jpg

```

(if I enter this path manually on postman it shows me the picture) But by default the path services put is wrong.

How to "configure" services or drupal to get the good path ?

**EDIT** This is my custom resource to retrieve a book (livre in french) :

```
function my_module_get_livre($entity_id) {
// check uid && entityID

$result = db_query("SELECT `field_title_value` as titre, `field_prix_value` as prix, `field_auteur_value` as auteur, `uri` as couverture, `field_resum__value` as resumé
    , `field_date_de_parution_value` as parution, `denomination_ed` as editeur,`field_nombre_de_pages_value` as pages FROM {field_data_field_titre_en_arabe} as t_ar
    inner join {field_data_field_prix} as pr on t_ar.entity_id = pr.entity_id
    inner join {field_data_field_auteur} as aut_ar on t_ar.entity_id = aut_ar.entity_id
    left join {field_data_field_photo_de_couverture} as ph_couv on t_ar.entity_id = ph_couv.entity_id
    left join {file_managed} as file on ph_couv.field_photo_de_couverture_fid = file.fid
    left join {field_data_field_resum_} as resu on t_ar.entity_id = resu.entity_id
    left join {field_data_field_date_de_parution} as d_paru on t_ar.entity_id= d_paru.entity_id
    left join {field_data_field_edit} as edi on t_ar.entity_id = edi.entity_id
    left join {editeur} as ed on edi.field_edit_target_id = ed.uid
    left join {field_data_field_nombre_de_pages} as pages on t_ar.entity_id = pages.entity_id
    WHERE t_ar.entity_id = $entity_id ")->fetchAll();

return array('code'=>'0', 'response'=>$result);
   }

 function my_module_livre_retrieve ($entity_id){
      return my_module_get_livre($entity_id);
    }

```

I've also tested this (it works) :

```
$fid ='2'; <=== i put it manually(but it would be set by select query
$file = file_load($fid);
$realURI = $file->uri_full = file_create_url($file->uri);
var_dump($realURI);<==== returns the real url (localhost/drupal/sites/...

```

I want to 'alter' or just put the $realURI value to every book(livre) in his field : "photo de couverture" (which is the pitcture i want)

Thank you

# Answer
> 0 votes
Yes, this is an annoyance, no doubt. Drupal stores the uri using a public:// streamwrapper. Thankfully, someone has written the code to resolve that into a full url that gets attached to the file object for you whenever one's loaded: https://www.drupal.org/project/full\_url\_file\_info

---
Tags: nodes, media, services
---


# Question
Title: Drush not reading config file from top-level /drush folder within Drupal install?
I'm trying to have localized *drushrc.php* configurations and alias configurations per site I'm working on, but no matter what I'm trying right now, drush refuses to find or load my *drushrc.php* configuration file.

Based on #2 in the example configuration file found here: https://github.com/drush-ops/drush/blob/master/examples/example.drushrc.php

I should be able to place a *drushrc.php* configuration file in a top-level /drush folder location:

* $DRUPALROOT/../drush/drushrc.php (top-level parent above root folder)

No matter what I'm trying drush never seems to detect the configuration file in this location when I do a *drush status* in the drupal root folder. Everything works fine if I place *drushrc.php* within my home folder (*~/.drush/drushrc.php*) or in a sub-folder of my install (\*$DRUPALROOT/drush/drushrc.php). Problem is I don't want there and would like it in a top-level folder above my root install!

Is there a secret to getting drush working based on this ?! I've tried *drush cc drush* every time I move my configuration around but it's never found!

On Mac OS X if it matters? Please help!

# Answer
Sorry, there is a typo in Drush preventing this:

https://github.com/drush-ops/drush/pull/1542

This fix should be in the next version of Drush. Sorry for the inconvenience.
> 3 votes

---
Tags: 7, drush
---


# Question
Title: Creating a template file for one specific page created by a custom module
How do I call a custom theme file (stored in the theme folder) that displays on a specific page that is created by a module.

It's a module for viewing mortgages in a full-page view. The template file is called page--single\_view.tpl.php

The module is named single\_view and has these functions:

```
<?php
/**
 * @file
 * Single Mortgage Views module file
 */

 /**
 * hook_menu() add to menu
 */
 function mortgage_single_view_menu() {

  $items = array();

  $items['mortgage/%/view'] = array(
    'page callback' => 'single_view_theme', //This isn't correct but just set this way for now
    'page argument' => array(3), //pass 3rd argument of url -- 1. drupal 2. mortgage 3. %
    'access callback' => TRUE,
  );

  return $items;
 }

 /*
 * Implementation of hook_theme().
 */

function single_view_theme($existing, $type, $theme, $path){
  return array (
    'page__single_view' => array (
      'variables' => array(),
      'template' => 'page--single_view' ,
      'base hook' => 'page',
      'path' => drupal_get_path('module', 'single_view'),
    ),
  );
}

```

I'm guessing my implementation of hook\_theme isn't correct. The page that comes up is just blank?

# Answer
> 0 votes
I think you can't pass the single\_view\_theme as a page callback.

create a new function with something like this:

```
function single_view_callback($something) {
  return theme('page__single_view', $variables);
}

```

And in your page callback replace 'single\_view\_theme' with 'single\_view\_callback'.

---
Tags: theming
---


# Question
Title: How to prevent entering a time-slot that is already taken when using the Calendar module?
I have installed and enabled the Calendar module. I have noticed that this allows multiple events for the same time slots. It means if event 1 is on Aug 12th from 11-12, I can still enter the same time slot for event 2.

In this case, how can I apply a logic so it complains that if the time-slots already taken?

# Answer
> 0 votes
I'm not aware of any way to use the Calendar module for this. However, you may want to look at this set of modules (with an official D7 release) that may help to implement the logic you are trying to implement:

1. Availability Calendars (Reported installs: 2.061 sites).

> ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.
>
> An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.
2. Rooms (Reported installs: 1.575 sites).

> ... is a booking and room management solution for hotels, vacation rentals and B&Bs.

Its module page also mentions some related modules you may want to look at, such as:

* Rooms Package: Define special offers for bookings.
    * Rooms Availability Constraints \- Allows admins to define availability constraints such as the minimum period of a booking.
    * Rooms Views\- Provides a "Rooms availability" filter and a "Booking form" field to improve the Views integration for Rooms.
3. MERCI (Reported installs: 441 sites).

> ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.
4. Resource Conflict (Reported installs: 329 sites).

> ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.
5. Simple Reservation (Reported installs: 202 sites).

> ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.
>
> The module provides the possibility to create reservations for other users (dependent on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.
>
> There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.
6. Room Reservations (Reported installs: 156 sites).

> ... for use by academic libraries to manage access to and use of their study rooms.
>
> All academic libraries have rooms set aside for student study and collaboration. These rooms are often available on a first come, first serve basis. Many libraries would like to have a room reservation system that would allow students to better plan their use of these often scarce resources, but setting up and administering such a system without computer support is a very difficult and time consuming undertaking.
>
> The Room Reservation module was created to meet this need. It allows any library to very quickly put together a reservation system customized to its own particular requirements. And once the system has been set up, it performs all the functions necessary to manage the use of group study rooms with practically no involvement from the library staff.
>
> Although this application was written specifically for use by academic libraries, it could also be useful to any facility that provides rooms that can be reserved and used on a short term basis.

# Booking Systems Comparison

Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.

This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).

# How to pick the module that fits best

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.

So do your homework to pick the right one for you. E.g. by using criteria such as those I often use for selecting module, as mentioned in the community documentation about Maintenance Scorecards. Here is the intro about it (from that page):

> ... contains a list of 23 criteria (=28-5) that might help to evaluate the maintenance and support of contributed modules. Below is an attempt to apply those criteria to each of the native charting modules ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

**Disclosure:** I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph).

---
Tags: datetime, bookings
---


# Question
Title: How do I relate two similar text fields between users and content with user as argument?
Getting a bit mixed up and need help with this. My restrictions are that I cannot use entity reference fields (or any reference type field); this is because Salesforce Suite isn't able to translate single strings to the array object normal reference fields use upon import and object creation.

I have two entity types, User and Content, which are dynamically created via the Salesforce Pull module. Both entities share a plain text field (*SFID*), which is the user's main ID.

The Content nodes' *SFID* field value can match any user's *SFID* field value, and I want to create a view that lists nodes on the user's page related in this way.

For example, I have the following users and nodes.

* User 5
SFID 120
* Node A
SFID 120
* Node B
SFID 130
* Node C
SFID 120

On /user/5/mynodes, I need a list of the nodes whose SFID matches the user's SFID. In this case above, the page would list the following nodes:

* Node A
* Node C

# Answer
> 1 votes
You need to make a View that lists nodes, containing a contextual filter that filters by SFID. Do that, and what remains is the problem of how to pass the user's SFID value to the contextual filter. There are many ways to do this, depending on how you're generating the user/%user/mynodes page.

## Panels / Page Manager approach

My go-to recommendation for this sort of thing is to use Panels / Page Manager to generate the user/%user/mynodes page, and embed your view there. If you enable the Views Content module (bundled with CTools) you will have a new type of Views display available called "Content pane". Build your view using this type of display. In the view configuration when configuring this display there's an option for "Argument input". You'll probably want to choose "input on pane config". Then, when embedding the view in your page (using Page Manager) you'll be given the opportunity to plug in a token there from the ctools user context that represents the user's SFID.

## Custom module alternative:

Since you said you can't use Panels, your best alternative is probably to create your own menu callback at user/%user/mynodes wherein you extract the SFID from the user object and return the view by calling `views_embed_view()`.

This is greatly simplified, but here's the gist of it:

```
function mymodule_menu() {
 $items['user/%user/mynodes'] = array(
  'page callback' => 'mymodule_user_nodes',
  'page arguments' => array(1),
 );
 return $items;
}

function mymodule_user_nodes($account) {
 return views_embed_view('viewname', 'displayname', array($account->field_sfid['und'][0]['value']));
}

```

Note: I haven't tested that code, it's just off the top of my head. I may have forgotten something. Don't forget to add things like an `access callback` since I presume you'll want to limit access to this page.

## Views Field View or Entity Views Attach (EVA) alternative

This is a little bit icky but should work. Either of the modules I listed (Views Field View or Entity Views Attach) will work for this approach. I'll specifically outline how to do this with Views Field View but you could adapt these methods to EVA if you want; it would be similar.

You will make 2 views:

1. A view that lists users and accepts the user ID as a contextual filter. So this view will always return only 1 single user (whatever user is passed in the URL).
2. The view that you've already likely created; the one that has a contextual filter that accepts a SFID value and lists nodes.

What we'll do is use view #1 to generate the page at user/%/mynodes, and view #2 will be embedded inside of view #1; view #2 will generate the actual list of nodes for us.

We'll assume you've created view #2 correctly already (it's basically what we've already discussed previously) and I'll focus on view #1.

1. Create a view based on the users table
2. Path for the view should be user/%/mynodes
3. Add a contextual filter to the view that filters on uid
4. Configure the view to output fields
5. Add the SFID field to the view, but check the "exclude from display" option so it's not actually displayed. We add this to the view so that it's available as a substitution for our next step.
6. If you've installed Views Field View then you'll have a new field available called `Global: View`. Add this to your view. This field has a few settings; you'll need to select the name and display of view #2, above, and enter \[!field\_sfid\] (this is the substitution token we get from the field we added in step 5) into the Contextual filters option.

Now you need only visit user/%/mynodes with an appropriate uid in place of the % and it should work.

---
Tags: entities, views
---


# Question
Title: How enable Taxonomy to work with Basic Pages
When I create an Article I choose an appropriate Tag from my Taxonomy List and save the article. When I click the tag after I save the article I get a list of articles with the same tag.

But how do you make a Basic Page work this way? I've researched Manage Fields and Manage Displays in admin-structure-types-manage and I CAN choose a tag and save it with the Basic Page...but I can't click on a tag on a Basic Page and get a list of all Basic Pages with the same tag.

Can you assist?

# Answer
**You probably have your field being displayed as *Plain text***. To display as links:

1. Go to your content type and ***Manage Displays***
2. Find the *Tags* field and make sure the ***Format*** column has the ***Link*** value

Note that I'm assuming that you added the *Tags* field to your *Basic Page* content type and it's showing up in your page.
> 2 votes

---
Tags: taxonomy-terms
---


title: How to display files in a web browsers?

text:
# Question
Title: How to display files in a web browsers?
I have a new OA site spun up and have some content available for the few users I have. One of the requests from the user's is to be able to view (and most likely edit) the documents via the web browser.

I was able to open a Word document in the browser when using IE, however I was unable to edit the document. Also, opening project files was a no go.

I am pretty new to Drupal, however any research I did on this issue just brought me different file manager modules.

Is it possible to view/edit files in the browser with Drupal/Open Atrium? I know it is possible with SharePoint but that utilizes a back end office.

Or is it possible to have it so people can open files automatically in their client side applications (Project, Word etc.) and have it save to the OA file system?

# Answer
I'm not aware of any web based file browser that "*opens* files in the client site applications" like Project, Word, etc. and *saves* them.

**Some ideas:**

However, this could be possible if you open your files with a FTP manager, as they will be opening from your client's computer, therefore using its applications.

Another option might be the **download / re-upload** approach, for what you could use a module like elfinder, which *does* allow you to edit text based files (note that we are not talking about propietary software like Microsoft Word).

*Disclaimer: I'm not endorsing any of these methods, just offering alternative ideas.*
> 0 votes

---
Tags: files, distributions
---


# Question
Title: Fatal error: Unsupported operand types in includes\common.inc on line 3022
I have upgraded *Drupal 6* to latest version `6.36` and *PHP* to `5.6`. I am getting *Fatal error* saying;

> Unsupported operand type while accessing `admin/content/node`.

Which is actually nothing but simple addition of an array to variable;

`$elements += array('#title' => NULL, '#description' => NULL);`

Any help?

# Answer
From official system requirements:

> PHP 5.3.x and higher may produce errors or unexpected behavior

Thus, sadly, what you are seeing is pretty much "expected" unexpected behaviour. Drop back to PHP 5.2.x (x ≥ 5) or upgrade to Drupal 7 or 8 for a full fix.

If you want to only fix this one, consider what AyeshK wrote in comment:

> The `$elements` variable probably contains an array element that the key does not start with a hash sign and the value is scalar.

There is a lot of things about array operators. Comments under PHP documentation shows that many things are far from obvious. Also, it changed a bit from version to version. Have you tested if `$elements` is an array in the first place? *"Simply"* add tests to make sure if operand is still valid, and provide a fallback if it isn't (recreate original behaviour) and you will be good to go.
> 1 votes

---
Tags: 7
---


# Question
Title: Add items to batch queue operations on the fly
I have some code which generates a batch with a single operation; to go off to an API and get some data. This data could be any number of items.

I would like to be able to populate the rest of the batch's operations during the first operation.

I have tried this, but it doesn't seem to work...

Batch initialisation (drush command callback):

```
function example_drush_sync_entries() {
  $batch = array(
    'operations' => array(
      array('_example_fetch_data', array())
    ),
    'finished' => '_example_batch_finished',
    'title' => t('Processing'),
    'progress_message' => '',
    'error_message' => t('The update has encountered an error.'),
  );

  batch_set($batch);
  $batch = &batch_get();
  $batch['progressive'] = FALSE;

  drush_backend_batch_process();
}

function _example_fetch_data(&$context) {
  $response = drupal_http_request('http://blah.com/data');
  $data = $response->data;
  $data = drupal_json_decode($data);

  $batch = &batch_get();
  $batch_set = &$batch['sets'][$batch['current_set']];
  foreach ($data as $entry) {
    $batch_set['operations'][] = array('_example_process_entry', array($entry));
  }
  print_r($batch);

  _batch_populate_queue($batch, $batch['current_set']);
}

function _example_process_entry($entry, &$context) {
  print_r(func_get_args());
}

```

I can see `$batch` has a load of new operations in it, however `_example_process_entry` never seems to fire.

Is it possible to dynamically add items to the batch queue while its processing?

# Answer
> 6 votes
I was really quite close! As always, asking the question on here caused the answer to reveal itself.

```
function example_drush_sync_entries() {
  $batch = array(
    'operations' => array(
      array('_example_fetch_data', array())
    ),
    'finished' => '_example_batch_finished',
    'title' => t('Processing'),
    'progress_message' => '',
    'error_message' => t('The update has encountered an error.'),
  );

  batch_set($batch);
  $batch = &batch_get();
  $batch['progressive'] = FALSE;

  drush_backend_batch_process();
}

function _example_fetch_data(&$context) {
  $response = drupal_http_request('http://blah.com/data');
  $data = $response->data;
  $data = drupal_json_decode($data);

  $batch = &batch_get();
  $batch_next_set = $batch['current_set'] + 1;
  $batch_set = &$batch['sets'][$batch_next_set];
  foreach ($data as $entry) {
    $batch_set['operations'][] = array('_example_process_entry', array($entry));
  }
  $batch_set['total'] = count($batch_set['operations']);
  $batch_set['count'] = $batch_set['total'];

  _batch_populate_queue($batch, $batch_next_set);
}

function _example_process_entry($entry, &$context) {
  var_dump($entry['id']);
}

```

Notable differences: * The operations need to be added to the next set, not the current one. * You need to define a total and count, otherwise the percentage progress is considered 100% and, therefore, complete before it even starts.

I hope this helps other people :)

---
Tags: drush, batch-operations, queue
---


# Question
Title: How to refresh block view of flags when the flag list is empty? Link operations issue
I'm trying to have a simple block of flags for my site. I created a block view of content of my custom product type with a relationship to Flags: my\_product (by any user).

The issue is have is that the block is only refreshed if I used the confirmation form link type. Is there a way to get the list to refresh (and the block to be updated) with using the other link types?

thanks in advance.

# Answer
Since this tumbleweeded the answer is that there are a few modules that to time based refreshes of the view. Views by default, serves up content that ends up being static. Refreshing a view can be done a number of different AJAXY ways with custom code, but one of the more interesting involves using the Drupal node.js module and refreshing the view based on the execution of the flagging event. But using node.js you can have the view refreshed by server-side events (i.e. submissions by other users) all behind the scenes!.

Views Auto-Refresh is interesting but only has the on-click functionality in it's feature request que. I haven't developed a working implementation of this, but the node.js route is the one I would pursue at the moment.

A little more research turned up this little bit of jquery posted with a good explanation here Jquery views refresh

```
/**
 * @file
 * This JavaScript reacts to certain AJAX events on the view.
 */

jQuery(document).ready(function(){
  jQuery('input[type="submit"][name="op"][value="Save"]#edit-submit').hide();
})

/**
 * Function built on wireframe from
 * https://drupal.org/node/1781988#comment-6835168
 */
Drupal.behaviors.my_view_machine_name = {
  attach: function(context, settings) {
    if (Drupal.views !== undefined) {
      jQuery.each(Drupal.views.instances, function(i, view) {
        if (view.settings.view_name == "my_view_machine_name") {
          jQuery(document).ajaxComplete(function(event, xhr, settings){
            jQuery('input[type="submit"][name="op"][value="Save"]#edit-submit').hide();
            var response = JSON.parse(xhr.response);
            var resp_keys = Object.keys(response[0].settings.ajax);
            if (response[0].settings.ajax[resp_keys[0]].callback == "editablefields_form_update") {
              jQuery('#view-auto-refresh').click();
            }
          });
          view.$view.once('view-refresher', function() {
            var html = '<a class="view-refresher" href="' + view.settings.view_path + '" id="view-auto-refresh" style="display:none">Refresh</a>';
            view.$view.append(jQuery(html).each(jQuery.proxy(view.attachPagerLinkAjax, view)));
          });
          return false;
        }
      });

    }
  }
}

```
> 0 votes

---
Tags: blocks, flags
---


# Question
Title: Redirect to anchor after form validation
I am trying to redirect users to the anchor of the error form field after form validation.

In the form I set the form validation handler with the following code.

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

```

In the validation handler, if the form shows some error message, I am trying to scroll to error field.

```
function my_form_validate() {
    ...
    $form_state['redirect'] = 'node/' . $form['nid']['#value'] . '#' . $error_field_anchor;
    ...
}

```

The form is not redirecting after validation.

I have tried other paths, such as user/1, node/123 without anchor but the form is not getting redirected to that one.

# Answer
Use this and put in you form

```
$form_state['redirect'] = 'url';

```
> 0 votes

# Answer
What you're looking for is `drupal_redirect_form($form_state)`. In the validation function, set the `redirect` element in `$form_state` to the parameters used by `drupal_goto()`.

```
function my_form_validate() {
  // @TODO: Add validation function check
  $form_state['redirect'] = array('node/' . $form['nid']['#value'], array('fragment' => $error_field_anchor));
  drupal_redirect_form($form_state);
}

```
> 0 votes

---
Tags: forms, 6, redirection
---


# Question
Title: Migrate files attached to comments from D6 to D7
While migrating from Drupal 6 to Drupal 7 (into a new blank site), I noticed that **files attached to comments** are not handled by the Migrate module. The D6 site uses a contributed module „Comment Uploads“ that associates files with comments in a table **comment\_upload**:

```
+------+------+-------+----------------------+------+--------+------------+
| fid  | nid  | cid   | description          | list | weight | legacy_fid |
+------+------+-------+----------------------+------+--------+------------+
| 1002 | 1001 |  1000 | under_149.jpg        |    0 |      0 |          0 |
| 1774 | 1969 |  6855 | ruler.png            |    0 |      0 |          0 |
| 1706 | 1712 |  6009 | 1.png                |    1 |    127 |          0 |
| 1703 | 1712 |  6006 | 2.png                |    1 |    127 |          0 |
| 1704 | 1712 |  6006 | 3.png                |    1 |    127 |          0 |

```

Nodes, comments and files already migrated successfully to D7 using the migrate\_d2d module and its user interface. Node attachments went through fine. Except comments no longer have files attached now. Since files and comments exist, it should be possible to attach the files to their original comments, using the above table.

Q: How would I go about and migrate comment attachments properly?

a) Would it make sense to hack the migration class for D6 comments? The issue is: The comment attachments do not appear as a source field in the Migrate user interface, as they do for nodes. Maybe if this could be achieved, this would be the best solution.

b) Why not grab that above table’s data (some 1000 rows only), iterate over it and call the appropriate D7 API to attach each file (fid) to its original comment (cid)? If so, which API calls should be used and where do I place this code?

Despite doing software development for decades, Drupal’s inner underpinnings are new to me. Any help is highly appreciated.

**Edit**: I don't want to use the Comment Upload module under D7 anymore.

# Answer
Consider looking at this Github link mentioned in Comment #35 of Issue # 554986 ...

If it works for you, then please add an appropriate comment about that in that issue (which currently has status "needs review" ...). And of course let us know about it around here also ...
> 0 votes

# Answer
Maybe not perfect, but this worked for me: Find a solution here. It boiled down to extending the query in migrate\_d2d to include all attached file IDs and map them to the new D7 File field.
> 0 votes

# Answer
You can bring the source file field info over directly from the comment\_upload file by adding this code to drupal d2d ui comment migration:

```
    $query->leftJoin('comment_upload','cu','c.cid = cu.cid');
    $query->addExpression("GROUP_CONCAT(cu.fid SEPARATOR ',')", 'comment_upload_fid');
    $query->addExpression("GROUP_CONCAT(cu.description SEPARATOR ',')", 'comment_upload_description');
    $query->addExpression("GROUP_CONCAT(cu.list SEPARATOR ',')", 'comment_upload_list');
    $query->addExpression("GROUP_CONCAT(cu.weight SEPARATOR ',')", 'comment_upload_weight');
    $query->groupBy('c.cid');

```

Then you map the d6 comment\_upload file fields (created above) to d7 comment file fields.
> 0 votes

---
Tags: 7, comments, files, migrations
---


# Question
Title: Move file uploads in webform into subdirectory using hook_webform_submission_presave
I'm using the webform\_multiple\_file module to let users upload files in a webform. There is a second form component in that form. It's a number. I want to change the upload directory, which is defined on webform admin and is 'webform/uploads' in my case. I want the uploaded files to be stored in subfolders named by the number in the second form field. So the upload directory should be s.th. like 'webform/uloads/102'.

I first tried to accomplish it with hook\_webform\_submission\_presave, but I only can change the file id.

Then I found hook\_file\_presave, which seems to be the perfect function to solve my problem, but now I'm stuck with the question, how to get the value from my form field into the presave function? The only parameter is $file.

Can someone help me on this? Submission- or file-presave? Is it possible to change the file- and upload-directory in hook\_webform\_submission\_presave?

UPDATE:

I was able to get the form value with $GLOBALS in hook\_file\_presave.

```
$order_number = $GLOBALS['_POST']['submitted']['upload_formular']['upload_wrapper']['bestellnummer'];

```

Some string-functions on $file-\>uri do get the split point and first and second part of uri. Append first part with the value of 'bestellnummer' as the subdirectory. Next I create the subdirectory with

```
file_prepare_directory($newdir, FILE_CREATE_DIRECTORY);

```

Then I change $file-\>uri and $file-\>destination to new URI, and dpm($file) shows, that it's changed. The new directory is created, but the file is still in the original folder after submitting the form.

It seems I'm missing something here...

# Answer
> 0 votes
I finally sorted something out. Now in hook\_webform\_submission\_presave the files are moved into subdirectories named by the value of a number form field. The field is mandatory, so I don't need extra validation in my function.

Here is the code I use in a custom module with plenty of comments, mostly for me to remember what I did.

```
/**
 * Implements hook_webform_submission_presave().
 *
 * @param $node: The Webform node on which this submission was made
 *        $submission: The Webform submission that is about to be saved to the database
 *
 * - Move uploaded files to subdirectory based on order-id
 */
function custom_module_webform_submission_presave($node, &$submission) {

  if ( 15 == $node->nid) {
    // get ordernumber for subdirectory
    $subdir = $submission->data[4][0];
    // get files from submission and move them one by one
    $upload_files = entity_load('file', $ids = $submission->data[5]);
    foreach ($upload_files as $key => $file) {
      $uri_old = $file->uri;
      // find last '/' in URI to get filename
      $uri_break = strrpos($uri_old, '/') + 1;
      // extract filename
      $file_name = substr($uri_old, $uri_break);
      // replace filename in uri with subdirectory to get new directory
      $new_directory = str_replace($file_name, $subdir, $uri_old);
      // if not already exists create subdirectory
      file_prepare_directory($new_directory, FILE_CREATE_DIRECTORY);
      // move file in new directory and show message
      $moved_file = file_move($file, $new_directory, $replace = FILE_EXISTS_RENAME);
      if ($moved_file) {
        drupal_set_message(t('<i>@file</i> uploaded to server.', array('@file' => $file_name)));
      }
    }
  }
}

```

---
Tags: webforms, files
---


title: Migrate d2d UI Comment Fields

text:
# Question
Title: Migrate d2d UI Comment Fields
Running Drupal-to-Drupal 7.x-2.1. I am attempting to migrate d6 comment attachments to d7 using the UI. In d6, I used the Comment Upload module for comment attachments. d7 does not have such a module, but you can attach files to comments by adding a file field to the comment structure.

I created migration code which provides the source file field information I need (from the d6 comment\_upload table). I created a file field in the d7 destination content type comment structure.

However, when I run the Drupal import option in the d2d UI and navigate to the destination map for the content type comment in question, I do not see the file field I created.

Is this normal? A bug?

I have seen a 'solution' to migrating files attached to comments from d6 to d7 advertised here, but after following 3 links, it only provides a vague explanation with examples of core node file migration. There is no example, or logic, provided to show how to actually map a d6 file field to a d7 comment file field.

My hope was to be able to do this through the d2d ui, but it does not appear to display comment file fields.

Any help on this?

Thanks!

# Answer
There is no bug. I ran the import the first time, then discovered that I was migrating nodes to the wrong content type, so ran it again with the correct content type.

Thing is, if you don't configure your destination content type as allowing comments, then comment migration will be skipped for all sources mapped to that destination.

So, I thought d2d ui wasn't working correctly when all the time it was my configuration. Oops!
> 1 votes

---
Tags: migrations
---


# Question
Title: node_access check against array of node ids
I am in middle of a problem where i have to check node access of current user against an array of node ids.

I have a two content types (A and B) and one contains the reference of other based on a taxonomy. A contains a user role reference fields to allow access to certain roles only. Now i want to show related contents from A on detail page of B. I have used a custom query to fetch all nodes from A somehow related to B. So code is looks like:

```
$related_nodes = <function_to_get_related_node>;
$result = node_load_multiple($related_nodes);

```

I have restricted couple of node from A content type to display only certain user roles but $result shows all node from A. Node access not worked.

In my function i have used db\_select() with addTag('node\_access') but it doesn't seems to be working.

So Basically i want some sort of code to check node\_access on array of $related\_nodes and filter before it passed to node\_load\_multiple function. Could someone help me find a way? Thanks!

# Answer
How about adding checking if the node has reference of current user while fetching related nodes.

So,

```
$related_nodes = <get_related_node>;

  // Might look Dumb
  function get_related_node($user=NULL) {
    if(is_null($user)) {
      global $user;
    }
    db_select('node','n')
     //Your existing joins
     // One more join for the user reference field, :O
     ->leftJoin('field_data_userreference','ur','ur.entity_id=n.nid')
     // your existing conditions for query.
     // One more condition for the current user as the value on the field.
     ->condition('ur.entity_id',$user->uid,'=')
    // And the execution continues.
  }

```

Fields mahcine names to be fixed as per the names provided. It should filter your reference nodes while fetching.
> 0 votes

# Answer
This is untested, but assuming the reference field table (let's call it *"field\_data\_field\_roles"*) is structured something like this:

```
entity_type | entity_id | field_roles_rid (role id)

```

...then this should return a new array of node ids filtered by the conditions described in your post:

```
global $user;

$rids = array_keys($user->roles); // array of role ids belonging to current user
$nids = array('1', '2', '3'); // array of node ids

$query = db_select('node','n');

// Set up the join, targeting the table containing the reference field data.
$query->join('field_data_field_roles', 'r', 'n.nid = r.entity_id');

// Declare your conditions. I threw in the 'node_access' tag, not knowing
// whether the check was applied when you retrieved the original set of nids.
$query
  ->fields('n', array('nid'))
  ->condition('n.nid', $nids, 'IN')
  ->condition('r.field_roles_rid', $rids, 'IN')
  ->addTag('node_access');

// Fetch matching nids.
$result = $query->execute()->fetchField();

```

Cheers -
> 0 votes

---
Tags: 7, users
---


# Question
Title: Remove attribute ID from site-logo (Panels Page Elements)
I use a module panels everywhere with *Omega 4*. I try to put a site-logo in header and footer but *Logo Page Element from Panels* takes site-logo and render it with ID. So I have same ID twice in my page.

***Header***

***Footer***

* How I can remove ID or render element with my markup?
* How I can create own element for panels?

Thank you

# Answer
This logo is created in ctools\_page\_logo\_content\_type\_render function. Unfortunately we can't alter code of this function. As a solution you may create your custom Ctools content type plugin, that will return logo without 'id' attribute. You can find more information about Ctools plugins here.
> 1 votes

---
Tags: panels
---


title: format_date not working as expected

text:
# Question
Title: format_date not working as expected
I'm using Drupal 7.38 and I'm trying to print the creation date of a node in 3 separate divs, to be able to format it appart, so I created the following on the node.tpl.php:

```
            <div class="fecha">
                <div class="mes"><?php print $date; ?></div>
                <div class="mes"><?php print format_date($node->created, 'custom' , 'M'); ?></div>
                <div class="dia"><?php print format_date($node->created, 'custom' , 't'); ?></div>
                <div class="año"><?php print format_date($node->created, 'custom' , 'Y'); ?></div>
            </div>

```

But, when I go to the result page I've got this:

MAR, 07/28/2015 - 16:20

JUL

31

2015

So, why is the day showing the incorrect date???

Thanks.

# Answer
> 1 votes
You should use `d` for the day of the month. Using `t` php displays the number of days for the given month. Reference: http://php.net/manual/en/function.date.php

# Answer
> 0 votes
`t` isn't the correct value for `format_date` when using the day. The custom option for `format_date` uses PHP's `date` syntax. As such `t` outputs the number of days in that month. What you want to use is `j` to list the day in that month.

---
Tags: theming, datetime
---


# Question
Title: How to show a Select list (dropdown) for state and dependent cities of India?
I want to show the list of state and city of particular state in dropdown.

I have done it using the Conditional Fields module but not helpful as I have to show the filter for cities in view.

Any suggestions?

# Answer
If you have City and State list in CSV, you can import to taxonomy using **Taxonomy CSV import/export** module.

> This module allows you to import or export taxonomy from or to a CSV (comma-separated values) file or with a copy-and-paste text.

you can use **Hierarchical Select** Module to list it in content type

you can find Indian states and city list in xlsx format here
> 2 votes

# Answer
I like to suggest Hierarchical Select Module.

> Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, \>you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!
> 1 votes

---
Tags: 7
---


# Question
Title: Problem with anonymous Flag and webform_select_ options_info() only visible to logged in users
So I've been trying to implement an anonymous "wish list" for an eCommerce site using webform\_select\_options and Flag. My implementation uses an anonymous flag set on my products and uses webform\_hook\_select to add a select list of the flagged products to a webform.

The issue I have is that the webform\_select\_options only show up in the webform when the user's logged in, thus failing as an anonymous implementation.

UPDATE (number 2 8/12/15)

I can confirm that the items are flagged when an anonymous user flags them. I tested this with a block displaying the flagged items when the site was viewed in incognito mode, the list is modifiable (I can add and remove flagged items), so it behaves more or less the way I expect it to.

The view shows commerce products that have been flagged by the current user. This shows me that the items are flagged. I have tested this with multiple browsers in incognito mode and can confirm that the lists are different for different anonymous users.

I tried the dpm($view-\>result); and it looks like the function doesn't get called with anonymous users. The function prints results with an authenticated user, but no result with anonymous users. I adjusted anonymous permissions to see devel information and can confirm that the function is called with anonymous viewers but returns an array with 0 objects.

Here is the code I'm using, the flag is defined through the flag module UI.

```
<?php
 function webform_hook_webform_select_options_info() {
   $items = array();
   if (function_exists('webform_hook_user_flag_sample_requests')) {
     $items['webform_hook_user_flag_sample_requests'] = array(
      'title' => t("Sample Requests (User Flag list)"),
      'options callback' => 'webform_hook_user_flag_sample_requests',
     );
   }
   return $items;
 }
 function webform_hook_user_flag_sample_requests() {
       $view = views_get_view('webform_flag_views', TRUE);
       $view->set_display('webform_options');
       $view->execute();
dpm($view->result);
       $options = array();
       if ($view->result) {
         foreach($view->result as $item) {
        $options[$item->product_id]= $item->commerce_product_title . render($item->field_field_image[0]['rendered']);
          }
           }
       else {
         $options[0] = t("Nothing");
       }
    return $options;
          }

```

So, I am at a loss at to what is wrong here, or how to approach this problem. I followed the tutorial here http://drupalsteve.com/node/57, but there doesn't seem to be an obvious way to resolve this.

I now strongly suspect that this is related to the general issue of showing a view to an anonymous user. Normally, you'd mitigate this by disabling SQL rewriting. Now, I wonder if my flags aren't showing up because I haven't programmaticaly set the advanced options of the "view" being created in the script.

So, I can think of two options: 1) create the flag array without generating a view; or 2) set the advanced query setting to disable sql rewriting.

thanks in advance.

# Answer
> 2 votes
So, after some frustration and headbanging, I was led to the answer by someone on #drupal-support IRC. The solution was in fact related to the SQL rewriting. The view was editable through the UI. There under the advanced section, I selected 'diasable sql rewriting.' This ultimately solved the problem.

# Answer
> 0 votes
Don't know what was the problem. But first time I used view **block** and saw only authenticated user's flags. Now I'm using view **page** and can see admin's flags under admin and anonymouse flags under anon. Just copypasted the code from your link and it works.

I can't figure out why did you name your functions in that way. Did you put your functions in webform\_hook.module?

*Sorry, can't post comments.*

---
Tags: views, webforms, flags, sessions, users
---


# Question
Title: How to set advanced views setting in code? Specifically disabling SQL rewriting with webform_select_options
So, I'm having trouble with a little custom module that places a list of flagged items in a webform with: webform\_select\_options\_info, views, and anonymous flag.

The issue I'm having is that the select list generated by my custom module doesn't appear for anonymous users. I suspect this has to with the issue of showing views to anonymous users by disabling SQL rewriting. I suspect this because I'm using a view generated in code via the custom module and that the advanced settings aren't set and the function isn't being shown to anonymous users.

So, how do I set advanced options like disabling sql rewriting in code?

here's my custom function minimally adapted from drupal steve's tutorial:

```
<?php
function webform_hook_user_flag_sample_requests() {
   $view = views_get_view('webform_flag_views', TRUE);
   $view->set_display('webform_options');
   $view->execute();
   $options = array();
   if ($view->result) {
     $row_class = $view->style_options['row_class'];
     $attributes = $row_class ? " class='$row_class'" : '';
     foreach($view->result as $item) {
       $options[$item->product_id] = '<a' . $attributes . '>' . render($item->field_field_image[0]['rendered']) . ' ' . $item->field_title . ' (' . $item->commerce_product_title . ')' . '</a>';
     }
   }
   else {
     $options[0] = t("Nothing");
   }
   return $options;
 }
 function webform_hook_user_flag_sample_requests() {
   $view = views_get_view('webform_flag_views', TRUE);
   $view->set_display('webform_options');
   $view->execute();
   $options = array();
  foreach($view->result as $item){
      $options[$item->product_id]= $item->field_field_image[0]['rendered'];
      }
return $options;
 }

```

I have a block view which shows the flags of the current user, I can confirm that each anonymous users flags work and generate unique flag lists on a per user-agent basis.

So, how do I diable sql rewriting for this view in code? or is there another reason this is happening?

Thanks

# Answer
> 0 votes
So this approach let's you edit the view through the Views UI. I thought the view was created on-the-fly by the module, but the module loaded the view into the db and exposed it to the views UI. Though this doesn't address the question directly.

---
Tags: views, users
---


# Question
Title: How to create a custom template for entities?
I'm having a dickens of a time overriding entity.tpl.php to create custom themes for my entities.

I am using ECK and Inline Entity Form. I've created entity `section` with bundle `masthead`. I've linked this to a node.

In a subtheme of the bootstrap theme, I then try to create a custom theme for this entity in a file called `entity--section--masthead.tpl.php` (note: I've also tried `section.tpl.php` and `section--masthead.tpl.php` and all sorts of permutations). Clear Cache. Nothing.

The only documentation is a few years old, and one of the most recent comments says this SHOULD work without the need for various hooks.

# Answer
> 1 votes
You don't need to add `entity` string to the template file name. These are theme hook suggestions for entity built with ECK (assuming your entity and bundle names):

1. `section.tpl.php`
2. `section--masthead.tpl.php`
3. `section--masthead--full.tpl.php`
4. `section--[ID].tpl.php`

As you can see there is a naming conflict because `section` is a drupal builtin template. It would be safer to use different name for your entity.

---
Tags: entities
---


title: Caching options and modules

text:
# Question
Title: Caching options and modules
My guess is that many ppl like me make Drupal websites just by using modules and simple CSS. Several content types, taxonomies, views, panels or DS to get results fast and more/less nice looking. Maybe add forum to all that.

When it comes to caching there are many options and i have no idea which ones to use. All my websites are on shared hosting (most popular ones).

In "performance" i always enable everything. Minimum cache lifetime and expiration of cached pages are options i always gaze at for several minutes and in the end choose "1 day". No idea if thats good. All other check boxes are clicked of course.

Views 3 are cached by default, nice, if i remember good i had to enable that in previous versions.

Now the fun part is picking modules from drupal.org for caching.

On this page Caching: Modules that make Drupal scale (updated 2014-07-09) we have 15 modules for D7. How many to use ? Which ones are "best" ? Which one you reccomend for shared hosting ? Should i for example disable default caching in performance and in views if i use those ?

So the final question would be: For nondevelopers who use shared hosting, what are the easiest/best modules - plugnplay.

# Answer
I have usually used the Boost module. It provides a lot of functionality and works really well, but can be a bit to set up since many times you have to modify .htaccess files when rules changes are made. I've used Boost for many sites where Varnish or some other server-side solution was not available and the results were satisfactory. Keep in mind that boost will not work when authenticated --- in fact many caching solutions will not. But Boost does have other modules to help cache authenticated pages for users.
> 0 votes

---
Tags: caching
---


title: How to hide node field if value is x?

text:
# Question
Title: How to hide node field if value is x?
Hiding a node field works great by default when the field is empty.

But I wonder how to hide a field when viewing a node if the value of a field is for example 3.

For now, I just need it for integer field.

Any suggestions?

# Answer
> 3 votes
Views Conditional or Conditional Fields can help you reach your goal .

> Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy) with fields in views. Conditions include:
>
> * Equal To
> * Not Equal To
> * Greater Than
> * Less Than
> * Empty
> * Not Empty
>
> Views conditional allows you to output text based on the result of the condition.

# Answer
> 3 votes
The Field formatter conditions module is a good starting point to answer your question. However, if the "Simple conditions and actions" are not sufficient, then you should consider using its integration with the Rules module.

Refer to the video about Field formatter conditions for a demo of what is pretty close to what you're looking for. Especially starting from around 4:50 in the video, you can see the Rules Action "Hide a field".

So your question is reduced to something like "*How should my the event and optional conditions for the Rules module look like (to apply the "Hide a field" action)?*". The answer to that question is something like so:

* **Rules Event**: A field is rendered.
* **Rules Condition**: Data comparison (to check if the value of your field is 3).
* **Rules Action**: Hide a field.

**Note**: The article about Introducing Field formatter conditions for Drupal provides some more background reading about this video also.

# Answer
> 1 votes
I think you go for Field formatter conditions module.

Adds conditions to field formatters. Configuration happens on the "Manage Display" screens of every entity type on a per field basis.

Simple conditions and actions

```
Hide source field when target field is empty.
Hide source field when target field is not empty.
Hide source field when current user has specific roles.
Hide source field on specific pages.
Hide source field when target field contains a specific string.
Hide source field when target field doesn't contain a specific string.
Hide link field if title is empty.
Hide date field if from/to has expired.

```

# Answer
> 0 votes
How did you implement your node display(view) page?

if you are using default themes like `Bartik` and the field name is `field_body` you can use `kpr()` function of devel module in `hook_preprocess_node` function to get the field then use `unset()` function to remove it from displaying. you also need to install entity module. As an example the following function

```
function bartik_preprocess_node(&$variables) {
    if($variables['node']->type=="memory"){
        kpr($variables);
        $wrapper = entity_metadata_wrapper("node",node_load($variables['node']->nid));
        $value = $wrapper->field_body->value();
        if($value == 3)
            unset($variables['content']['field_body']);
    }
}

```

This is the `kpr` result, I removed the `field_body`

---
Tags: nodes, entities
---


# Question
Title: How to show/hide fields with the Rules module based on the user's language?
I have a multi-language support website.

My question: can I show/hide some fields based on the user's language choice with Rules module?

# Answer
The Conditional Fields module might be of help to you.
> 3 votes

# Answer
Use the Field formatter conditions module, and its integration with the Rules module.

Refer to the video about Field formatter conditions for a demo of what is pretty close to what you're looking for. Especially starting from around 4:50 in the video, you can see the Rules action "Hide a field".

So with that, your question is reduced to something like "*How should my the event and optional conditions for the Rules module look like, related to the user's language choice (to apply the "Hide a field" action)?*". The answer to that question could be another question of course ...

**Note**: the article about Introducing Field formatter conditions for Drupal provides some more background reading about this video also.
> 0 votes

---
Tags: 7, entities, rules, i18n-l10n
---


# Question
Title: Array of items as contextual filter in Views
I need to create a View which displays content of users that their username should be passed as contextual filter. The number of parameters (usernames) are not specified but the View must include every username that is passed via url, as an example

```
example.com/some-path/user1
example.com/some-path/user1/user2
example.com/some-path/user3/user2/user12

```

the view must include all of pathes like the above ones and filter the contents but I really have no idea how to implement this using Views UI. I can do this programmatically by looping through each component of the url but I don't want to use such methods.

# Answer
> 1 votes
All you need to check "Allow multiple values" true by click on **More** toggle part of contextual filters field works well.

example.com/some-path/user3,user2,user12

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


title: Hide summary if empty (no trimming)

text:
# Question
Title: Hide summary if empty (no trimming)
In many cases we're using a view of content using the *summary or trimmed text* of a body field. Clients sometimes remark that, if there's nothing in the summary, nothing should be displayed at all, so no trimmed text of the full content either (which Views does by default).

Instinctively I went looking in the *Behaviour when no results* options of that body field in the View, but couldn't find anything there that would hide the summary if the summary is empty, disregarding what's in the full content.

What would be the recommended approach to achieve this?

# Answer
> 2 votes
1. Check the *Rewrite the value of this field*-option of the body field,
2. Fill out the following token in the text area: `[body-summary]`

Now it will only display text from the summary, and nothing when that very summary is empty. So it won't use the trimmed text of the full content either. Perfect.

---
Tags: 7, views, entities
---


title: Entity Reference Roles

text:
# Question
Title: Entity Reference Roles
I've created a **Entity Reference** from **customer** to **contract** and I created a user which can create a **customer**.

Now is the problem that I can't select any **contract** with the new user when I try to create a new **customer**.

The only solution I found is to give the new user the **Bypass content access control** permissions. But then he also can create a **contract**. And I don't want that user to do that.

Can anyone explain me what I'm doing wrong?

# Answer
> 1 votes
Probably you must not have given that specific user/role, the permission to "View Published Content". Verify that please.

---
Tags: nodes, entities
---


title: Exact link of vertical tabs

text:
# Question
Title: Exact link of vertical tabs
I am using Field Group.

With 2 Vertical Tab, '**Step 1**' and '**Step 2**'.

I want to put a link "**NEXT**" on '**Step 1**' that should open '**Step 2**', same a back link on '**Step 2**' that should go back to '**Step 1**'.

I tried different combinations with **Multipage** but did not work here. How can I do this? I can put text but I don't know how to get the link of the other tabs directly.

# Answer
> 1 votes
Just add the ID of the pane (fieldset) to the URL as a fragment, e.g.

```
http://example.com/node/[ID]/edit#edit-metatags

```

Assuming metatag is installed, that code will open the metatags tab directly on page load.

An example for core might be:

```
http://example.com/node/[ID]/edit#edit-options

```

For the "Publishing options" tab.

---
Tags: forms
---


# Question
Title: image_style_url() function not giving proper image in drupal 7
I am using `image_style_url()` function in drupal 7 with custom style. In my custom style I have taken a height:200 and width:200. But its cropping my image with these style not re-sizing it.

```
$query_bigimg = db_query(" select * from  {node} WHERE  type =  'cont' ORDER BY nid ASC LIMIT 0 , 1 ");
foreach($query_bigimg as $data) {
  $data_nid = $data->nid;
  $_Data = node_load($data_nid);
  $_bigImg = $_Data->field_ua_news_photo['und'][0]['uri'];
  $_styles = 'big';

```

`<img src="<?php print image_style_url($_styles,$_bigImg); ?>" class="big-img img-hover">`

# Answer
Then it is likely the rule you are referencing is not configured to do what you want it to do. It may be cropping instead of scaling or do a scale and crop.

Edit the image style at: admin/config/media/image-styles/edit

Check to see if it is scaling or cropping. Adjust it or create a new one and reference that in your code.
> 3 votes

---
Tags: hooks
---


title: menu item call from tpl file

text:
# Question
Title: menu item call from tpl file
I have create one form in .tpl file with simple html form tag. In action attribute of this form element i passed a url like `'action=savequestion'`. Now in my .module file, inside hook\_menu(), I am defining menu with the above url mentioned in action.

```
$items['savequestion'] = array(......); //like this

```

But when i am submitting that form defined in tpl file, It is not calling this menu item and page not found comes.

any one have idea about this? Thank you.

# Answer
> 1 votes
The right way to do this if you are using a Drupal module is to set up a form using the Form API and process things within the context of a module. You can also use a contributed module such as Webform to accomplish this too, but if you want something really custom, you should not just create a form in a template file.

All of this said, make sure your "action" is set to the same path as your menu item and that after you have created your hook\_menu entry you clear the cache, so your menu item becomes part of Drupal's menu registry.

---
Tags: theming, routes
---


# Question
Title: How to make my Drupal custome Service return data on GET?
I have defined few Drupal custom Services and they are working fine via POST requests. But one of them needs to be available via GET.

This one:

```
function rooms_services_services_resources() {
    return array(
        'api' => array(
            'actions' => array(
                'hotel_inventory' => array(
                    'help' => 'Inventory of all Hotels',
                    'callback' => 'rooms_services_hotel_inventory',
                    'access callback' => 'rooms_services_access_callback',
                    'access arguments append' => false,
                    'args' => array(
                        array(
                            'name' => 'params',
                            'optional' => true,
                            'source' => 'param',
                            'type' => 'struct',
                            'description' => 'all passed URL parameters'
                        ),
                    ),
                ),
            ),
        ),
    );
}

```

It's working fine when I am making a request via POST with headers:

```
`Content-Type: application/x-www-form-urlencoded`

```

or

```
`Content-Type: application/json`

```

as those I have enabled in my REST Server...

How do I make it work via simple GET request ?

# Answer
> 1 votes
`hook_menu()` would work well for this. And it sounds like you have already worked out some of the functions, so given that, something like this might work:

```
function rooms_services_menu(){
  $items['api/hotel-inventory'] = array(
    'title' => 'All Hotel Inventory',
    'page callback' => 'rooms_services_hotel_inventory',
    'access callback' => 'rooms_services_access_callback',
  );
}

function rooms_services_hotel_inventory(){
  ...
  return $inventory; //or whatever you want the GET request to return
}

```

I imagine you could put this in the same module as your REST hooks.

# Answer
> 1 votes
The short answer is *you can't*, unfortunately (AFAIK). For all non *action* resources, the Services module assumes that they are part of the entity C.R.U.D. spectrum, and then decides what to do based on the HTTP method. For example:

```
POST = Create
GET = Retrieve
PUT = Update
DELETE = Delete

```

So unless you're building an entity C.R.U.D. layer, you'll have to use *POST* on the *actions* array. Alternatively you could use `hook_menu()` to make your own custom `page_callback` that outputs JSON, then it could be accessed over GET. Another alternative is to use something like *Views Datasource* and compose a *Views JSON* to output your data (also available via *GET*).

# Answer
> 0 votes
rather than use an action , you could use the approach that is used in the documentation here: https://www.drupal.org/node/783460. Essentially just like you have the CRUD operations, create an 'index' operation.

Have a look at the node service too - that impliments an index service

call /endpoint/node - and it lists all nodes, it has parameters for fields, page size.

```
'index' => array(
      'help' => 'List all nodes',
      'callback' => 'rooms_services_hotel_inventory',
      'args' => array(

```

It seems the perfect fit for your inventory list.

---
Tags: 7, services
---


# Question
Title: Adding a vertical tab the the content type form page
How can i add a vertical tab to the content type manage form page?

I want to add a vertical tab that has a form like the ones it currently has. For example: it has menu settings, display settings, etc. I want to add a tab that ties a theme to a content type. Can you someone help me out?

Thanks

# Answer
> 3 votes
Try this. Or read about `hook_form_FORM_ID_alter()`

```
function mymodule_form_node_type_form_alter(&$form, &$form_state) {
  $default_value =TRUE;// auto_nodetitle_get_setting($form['#node_type']->type);

  $type = $form['#node_type'];
  $form['mymodule'] = array(
    '#type' => 'fieldset',
    '#title' => t('mymodule'),
    '#weight' => 0,
    '#collapsible' => TRUE,
    '#collapsed' => false,
    '#group' => 'additional_settings',
    '#attached' => array(
      'js' => array(drupal_get_path('module', 'menu') . '/menu.admin.js'),
    ),
  );

}

```

# Answer
> 0 votes
You can simply add vertical tabs into content type just using Field Group module.

**Field Group:**

> Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
>
> The field group project is a follow-up on the field group module in CCK. The release will only exist for Drupal 7 release and higher, so since the existence of the Fields API in core. By moving field group to a separate module, this may open some new perspectives.

# Answer
> 0 votes
`additional_settings` is the magic keyword. Search https://www.drupal.org/project/examples for it and you'll get at least two good examples:

First in `vertcial_tabs_example.module` for the basic setup.

Second in `nodeapi_example.module` and `nodeapi_example.install` when it comes to saving variables and working with them.

---
Tags: nodes, theming, routes
---


# Question
Title: How to code custom entity to access more than one database table?
I have an entity that uses two tables, when I describe it in `hook_entity_info()` as far as I know I can only tell it about the `base table`. The base table is subscriber, I also have a table disease\_catagories which stores the results of a select list. (stores the subscriber id, and the taxonomy term id. It can store any number of items with the same subscriber id and different taxonomy term ids)

I need the entity to contain an array of those taxonomy term ids, but I don't know how to connect that database table with the `base table`. are there any good articles that discuss how to attach a second table to the entity (maybe as field data)?

# Answer
> 0 votes
Entity API itself can only interact with one base table for joining to fields, querying with EntityFieldQuery, loading/saving revisions, etc, but you can use more than one table for storage if you implement your own storage controller which you can specify in your hook\_entity\_info().

You'll want to subclass DrupalDefaultEntityController and override the load() method and buildQuery() method if you want some EntityFieldQUery support.

If you are using Entity API module, you'll want to extend EntityAPIController and override the save(), load(), and delete() methods for full CRUD support.

---
Tags: entities
---


# Question
Title: Altering the Title of node using Preprocess
I am trying to alter the page title of history content type using this function

```
function mytheme_preprocess_page(&$variables) {
   if(isset($variables['node']) && $variables['node']->type == "your_content_type") {
   drupal_set_title("my_title");
 }
}

```

But you know what, I dont get anything in node array.

# Answer
> 2 votes
You could use `hook_node_view`, which also gives you more flexibility, (e.g. control what view mode / language you affect):

```
function MY_MODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'your-node-type' && $view_mode == 'full') {
    drupal_set_title('your-title');
}

```

Instead of using a preprocess function, which is better for template changes, (for example, adding variables to it):

> The main role of the preprocessors is to set up variables to be placed within the template (.tpl.php) files.

Preprocess and process functions

---
Tags: nodes, theming
---


# Question
Title: How to use function like 'rtrim' in drupal?
I need to remove extension from string, i'm wondering what function could do that ?

Some like the `rtrim($string,'string to remove')`

$string could be the filename

I've added a file into database, now to retrieve it, i want to remove the extension '.epub'

this is the postman response :

```
{
 "code": "0",
 "response": [
{
  "epub": "http://localhost/drupal/sites/default/files/moby-dick.epub",
  "f_id": "5",
  "uid": "64"
   }
 ]
 }

```

I want to retrieve :

```
"epub": "http://localhost/drupal/sites/default/files/moby-dick",<== no .epub

```

This is my first try :

```
$file = file_load($fid);
            //$realURI = drupal_realpath($file->uri); ca marche

            $realURI = file_create_url($file->uri);
            $new = drupal_basename($realURI, '.epub');
            $n = file_create_url($new);
            $res->epub = $realURI;<== show the new (without .epub)

```

but now it shows :

```
"epub": "http://localhost/drupal/moby-dick"

```

I need to keep `/sites/default/files/` because the file is there What can i add for keep it work with the right path please

Thank you

# Answer
Use the Drupal file API to do this; `file_move()` will take care of renaming.

```
  $file = file_load($fid);
  $new_file_uri = preg_replace('/\\.([a-zA-Z]+)$/', '', $file->uri); //Remove .whatever from the file name
  file_move($file, $new_file_uri);

```
> 2 votes

---
Tags: files
---


# Question
Title: drush sqlq --file on remote server with local file
Im trying to run run write a command where I can execute remote queries stored local.

I was trying:

```
drush @remote.master sqlq < src/sql/data.sql

```

but no luck, also tried the option --file=path/to/file but it's only for remote files :(

Any ideas?

# Answer
Try this: `cat src/sql/data.sql | drush @remote.master sql-cli`
> 1 votes

# Answer
you should try with other command:

```
drush sql-sync --source-dump=src/sql/data.sql --target-db-url=mysql://remoteusername:remotepass@remoteserver/remotedatabase

```
> 1 votes

---
Tags: drush, ssh
---


# Question
Title: How do I remove the site name from the head title in drupal 8?
The `<title>` element in the `<head>` of every page currently has the form page\_name | site\_name. I would like to make this have the page name only site wide. I've found advice about how to do this in earlier drupal versions (eg here), but not for drupal 8. How is this possible?

Thanks

# Answer
> 4 votes
Until metatag's module port has not finished you should code a bit for doing that.

If I were you I'll edit YOURTHEME.theme file and add this:

```
/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 *
 * Adds body classes if certain regions have content.
 */
function YOURTHEME_preprocess_html(&$variables) {
    unset ($variables['head_title']['name']);
  }

```

---
Tags: 8
---


# Question
Title: How Do i implement an alternative for the Privatemsg Bulkmail module?
I'm using the modules Private Message, Invite and Organic Groups in Drupal Commons.

I get listed with trusted content using Views and need to set private Message button for bulk operation just like the Privatemsg Bulkmail module from D6 (for which there is no D7 version yet).

How can I get the Private Message module to work with the VBO module, or any other module, in Drupal 7?

I created an Email system with bulk operation via external mail system.

> "User can invite friends and send email using VBO module "

But I want to send mail/message internal system like the Private Message system for bulk trusted contacts. How can I achieve this?

# Answer
Looks like there are currently no plans for a D7 version of the Privatemsg Bulkmail module you are referring to. However, I'd use the integration of the Privatemsg module with Rules instead (make sure to checkout this community docu, and its child pages ...), together with the VBO module.

For more details, refer to the video about Using Rules components with VBO. Possibly you also want to look at the 2 prior videos and/or the 2 subsequent videos (all about Views Bulk Operations), i.e.:

In this specific case;

* use Views bulk operations to create the list of your users to be targeted.
* use Rules action "Send a message" (provided by Privatemsg module).

PS: yet another great usage of the Rules module, in this case in combination with the Privatemsg module. So I wouldn't worry too much about the Privatemsg Bulkmail module not being available for D7.
> 3 votes

---
Tags: 7
---


# Question
Title: Re-writing View Comment link to display node title
I'm trying to re-write the \[view\_comment\] field in a Comments View with the \[title\]. I have the \[title\] excluded and I'm re-writing \[view\_comment\] with \[title\].

What I'm hoping is to show the node title in the view and it will link to the latest comment on the node. I think I need to 'output the \[view\_comment\] field as a link' possibly with node/???? (or similar) as the absolute link.

Can anyone point me in the right direction?

# Answer
If you are using Drupal 7 you can take advantage of core's new API to create permalinks to comments.

From the patch on d.o

> Since comments are paged there is no way to guarantee which page a comment appears on. Comment paging and threading settings may be changed at any time. With threaded comments, an individual comment may move between pages as comments can be added either before or after it in the overall discussion. Therefore we use a central routing function for comment links, which calculates the page number based on current comment settings and returns the full comment view with the pager set dynamically.

In drupal 7, this routing function is

```
comment/%comment

```

So it would be best in your view (with comment as a base table) to pull out:

* cid (display none)
* title (node relationship, required)

Display title as a link, path it to

```
comment/[cid]

```

---

If you are using Drupal 6, I would suggest rolling with contrib to fix core - with https://drupal.org/project/permalink which backports the above functionality
> 1 votes

# Answer
add the relationship "last comment" and don't select "relationship required" (otherwise it will only show nodes with comments.

Then add the "node id" and "comment id" fields above the title field and exclude them from display. Edit your title and under "rewrite results" check "Output this field as a link" and enter "node/\[nid\]#comment-\[cid\]" for the link path.

Now your title links to the last comment for every node and if there is no comment it will just link to the node ("#comment-" won't have any effect).
> 0 votes

# Answer
Note : a common issue, and annoying one, is that comment field options in Views 3 (7.x-3.11; and Views 2 also I believe) are not offered all the time. So MotoTribe is quite right that you need to add a relationship to make them appear (not obvious; should be simpler imo).

**I'd like to add to the trick MotoTribe describes** :

If you use the Rewrite Output from Views, but from inside the Comment Count field, you can then specify to **Hide if empty**. Therefore, if there are zero comments, none of the rewritten output proposed by MotoTribe will show up for nothing. It makes for a cleaner tracker table.

Also, if you use the Comment Title field instead, you can get a direct link to the comment. In this case, by default, it will appear only if there is a comment.
> 0 votes

---
Tags: views, comments
---


# Question
Title: Views to Display Nearby nodes according to user current location(latitued/longitute)GPS
I have Content type named Restaurant, When creating restaurant nodes I am imputing the Latitude/Longitude using the GEOFIELD module.

I have managed to Display all the restaurants in One Map using Views, Leaflet and leaflet Markercluster modules, you can see the attached screenshot.

My task now is to create a page named Nearby, where all restaurants near to user's current location(Latitude/Longitude) will be displayed, let say restaurant within 2km from the current users location.

To get the current user location, A prompt will appear on his/her browser asking them to share their location this is more specific for anonymous users.

I believe there must be a way to accomplish this task using Views or custom module.

Please Guide me step by step on how to make it happen.

any help will be highly appreciated.

# Answer
> 3 votes
Having messed with many Drupal mapping modules, I've found IP Geolocation Views & Maps to be the best overall helper (along with Leaflet, which I love). Give it a shot! It has lots of options, supports lots of maps, has geolocation stuff built in, marker clustering and some other stuff.

---
Tags: views, javascript
---


# Question
Title: How can i delete user profile picture in drupal 7?
Is there a way that I can remove/delete user profile picture through programing? or How can i override existing image with my new one?

# Answer
> 1 votes
use code below in hook\_user\_delete($account)

```
// Load user by using user id
$user = user_load($uid);
// Get file id of profile photo
$fid = $user->picture->fid;
// Load the file object
$file = file_load($fid);
// delete profile photo from.
file_delete($file);
// Unset the image object (my case it's 'picture')
unset($user->picture);
// Save the user
user_save($user);

```

---
Tags: 7, users
---


# Question
Title: How to create a block to remind special dates as stored in user profiles?
I'm looking for a way to remind special dates per user profile. I mean remember birthdays, marry dates, graduations.

The idea is to display in the home page a block with all those reminders for all the users.

Any suggestions?

# Answer
# Step 1: Flag appropriate users/nodes

I assume you want to show a **Block** with such reminders (not "*sending eMails*" ...). To do so, use the Flag module to create a global flag, say you name it "Show Reminder", and then use the Views module to create a block of all "*flagged content*" (using this flag), similar to what is explained in Creating global flags and listing flagged content in Views.

# Step 2: Use Rules to automate the flagging

You don't want to manually flag (and unflag) all such content every day, right? But that's what the Rules module is for: create a (1st) rule to "flag" whatever node, user, etc fits your criteria for "current day", and a similar (2nd) rule to later on "unflag" them again.

# Step 3: Trigger both rules once a day

Use the Rules Once per Day module to schedule both rules described in Step 2.

# Bonus Features

### Handling invalid or missing dates

In case any node or user that "should" show up, doesn't show up on a specific date (since its date is missing or wrong), it's a matter of just flagging such node or user to have it also appear in the block.

### Spotlights

For some node or user you for which you don't have a date, but which for some reason you also want to be shown, just flag it and it shows up also.

### Creating reminders does not require edit permission

Flagging a node or user can be configured in such a way that you can separate its required permission from editor permissions. That opens possibilities for having various types of users contribute to producing such reminders (if that is what you'd want).
> 6 votes

# Answer
Try the Date Reminder module. Some more details about it, from its project page:

> Date Reminder allows a registered user to request an email reminder to be sent at a specified time before an event.

Flexible enough to work with different type of events, as it works with any node type which has a CCK datetime.
> 2 votes

---
Tags: users, 7, blocks, datetime
---


# Question
Title: Recover content from "story" after content type was deleted accidentally
in a very stupid action, I accidentally deleted the "Story" content type which had a lot of content. Just to be clear: I didn't delete the content, only the content type. When I realized what I was doing, I pressed `esc`, so I got a drupal message that very few content types were deleted. Still, much of the content is not in the back up. I am checking whether I can restore some of the lost content.

Apparently the titles of all stories appear normally. Unfortunately the body content is missing. I recreated the content type manually and still nothing. But when I looked in the database, I noticed that sql tables `node`, `field_data_body` and `field_revision_body` actually contain the content from the nodes that were deleted.

Going further, I realized that the database entries of these sql tables have a column `deleted` which was set to 1 for the 'story' entries. I found an article which explains how deleted fields stay in the database and suggests to set the value of the column back to 0, if you want your deleted fields back. I did that, but still the stories display only the title and not the body.

I also looked at mysql table "node\_type" and story is there. It looks exactly like page.

What can I do to convince drupal to display again the body of the stories, as it is still in these fields in the database?

# Answer
I had this same situation - deleted nodes, only titles left.

With D7, I used phpmyadmin to go into the database

open the field\_data\_body table

Sort this by type and locate the type you deleted - there should be a "1" in the deleted column. I did two as a test and then cleared caches and checked the node on the site - the content was back.

Then I ran this sql query, copied from the changes I did: UPDATE `databasename`.`field_data_body` SET `deleted` = '0' WHERE `field_data_body`.`entity_type` = 'content type name' AND `field_data_body`.`deleted` =1

Everything was back. Yay!

change database name to your database and content type name to the content type you deleted.

And be sure to backup your DB before doing this in case of disasters. Like deleting a node type.
> 3 votes

---
Tags: entities, nodes, database
---


# Question
Title: How to use redirects on Nodes that are only used to populate block Views
I have a custom content type that is really only used to populate a views banner, so I don't want that node to ever be browsed to or indexed.

I'm thinking this is a redirect kind of scenario, but I don't know exactly what that should mean. I'm using Clean URLS and Path Auto

Would something like Global Redirect be what I need or is there something else I should use?

Thinking ahead, there are other content type nodes that will have the same requirement.

# Answer
You can use Rabbit Hole module for this.

> Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page. Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.
>
> **Options**
>
> This works by providing multiple options to control what should happen when the entity is being viewed at its own page. You have the ability to
>
> Deliver an access denied page.
>
> Deliver a page not found page.
>
> Issue a page redirect to any path or external url.
>
> Or simply display the entity (regular behavior).
>
> This is configurable per bundle and per entity. There is also a permission that lets certain roles override Rabbit Hole completely.
> 2 votes

---
Tags: nodes, redirection
---


title: Biblio import "choose file" disabled

text:
# Question
Title: Biblio import "choose file" disabled
I exported a .enw file from Biblio in drupal 6 and am attempting to import it into my drupal 7 site. However on the "data import" tab, "choose file" is grayed out and disabled. What needs to be done to import the drupal 6 biblio nodes?

# Answer
> 0 votes
I had to enable the Advanced Import module from Biblio in order to get the file to import.

https://www.drupal.org/project/biblio\_advanced\_import

---
Tags: importing-exporting
---


title: Unable to load autoload.php

text:
# Question
Title: Unable to load autoload.php
I've looked through all similar issues reported but none of them solves my problem. I always install drush with composer and installing 6.4.0 is working just fine, but when I install dev-master then I get the error

`Unable to load autoload.php. Drush now requires Composer in order to install its dependencies and autoload classes. Please see README.md`

Composer is at the latest version.

When I go to ~/.composer I never get a ./vendor/ directory as suggested by answers to other questions.

My environment is Ubuntu 14.04 and I'm using PHP 5.5 - any idea what else could be wrong?

# Answer
you might try running "composer install" from inside your drush directory.
> 3 votes

---
Tags: drush
---


# Question
Title: Setting a user as an administrator via drush command line?
How can I set a user to a specific role via drush? In my case I want to give the role of administrator to the user.

# Answer
```
drush help user-add-role
Add a role to the specified user accounts.

Examples:
 drush user-add-role "power user" 5,user3  Add the "power user" role to the accounts with name, id, or email 5 or user3, uids 2
 --uid=2,3 --name=someguy,somegal          and 3, names someguy and somegal, and email address of billgates@microsoft.com
 --mail=billgates@microsoft.com

Arguments:
 role                                      The name of the role to add
 users                                     (optional) A comma delimited list of uids, user names, or email addresses.

Options:
 --mail=<me@example.com>                   A comma delimited list of user mail addresses of users to operate on.
 --name=<foo>                              A comma delimited list of user names of users to operate on.
 --uid=<3,5>                               A comma delimited list of uids of users to operate on.

Aliases: urol

```

So, for your use case:

`drush user-add-role administrator USERNAME`
> 23 votes

---
Tags: users, drush
---


# Question
Title: How to filter types of Webforms with Views
I am trying to create a simple View of webforms to display a list of currently available jobs.

This is what I am trying to accomplish:

```
Webform1
description description description description...
[Read more]

Webform2
description description description description...
[Read more]

Webform3
description description description description...
[Read more]

```

I thought webforms would be a decent solution considering I can add/remove them once the job listing is expired. It is also very easy to go through submissions.

Only issue I am having is that the contact form I have is also a webform.

So I am getting some unwanted items in my view query. I am having a difficult time figuring out a simple yet robust solution to filter the different types of webforms.

The only filter criteria available for a view of webforms are `Webform: Node` & `Webform: Status` and I believe neither will help me accomplish what I need.

**Anybody got any ideas of what I could do to differentiate between webforms for views filtering?**

# Answer
You can enable Webform functionality on all the different content types. You don't have to use the Webform content type which comes pre-packaged with the module.

Make a new content type, and go to: `/admin/config/content/webform` and enable webform functionality on the new content type you created. Then add the webform to it.

Then you just need to filter by content type on Views.
> 1 votes

# Answer
Take a look at the webform view module, this module let's you place a view in your webform.
> 0 votes

---
Tags: views, webforms
---