# Question
Title: How do I model content (types) from a database-centric point of view?
How can I model content from a "database-centric" point of view?

For example to show Appartments in a District in a City, as in this example:

```
Table Cities:
CityID (int) primary key
City (string)

Table District:
DistrictID primary key
CityID foreign key
District (string)

Table Appartment:
AppartmentID primary
DistrictID foreign
AppartmentName
NrOfRooms
.....etc....

```

How would I create content types (?) to do this?

# Answer
> 4 votes
I'm assuming this question is about Drupal 7 ... Only using Site Building features (no custom module development yet) should get you *pretty far* (if not *far enough* ...).

# The Relativity Data Model for Drupal

Have a look at the (illuminating) article "Relativity Model for Drupal", for which this is an introduction to it (quoted from this linked page):

> The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:
>
> * Data architecture and data modeling merging as a single step through a documentation procedure.
> * Customized user interfaces that cater to individual workflows throughout permission roles.
> * Multi-level relational data structures that relate to other multi-level relational structures.
> * Mimicking the concept of database joins within Drupal's UI's.
> * Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

The *small handful of modules* (cfr. the last bullet) is like so (apart from Drupal core):

This same topic is also presented in the video "Revolutionary DRUPAL Data Modeling Concept!! (This will change your Drupal life!)".

# Typical add-on modules

Even though that *small handful of modules* above can get you already extremely far, I often add a subset of other contributed modules to it also, as further detailed below.

### Tables, Columns and Foreign keys

* **Tables**: Use the Entity Construction Kit (ECK) module to create 'entities' (= fieldable things ...). In your case that would be entities like Cities, District and Appartment.
* **Columns**: For each of those entities use "fields" for each of the columns you mentioned. Should you run into fields such as dates, you would have to add modules such as date also.
* **Foreign keys**: For the "foreign keys" use the Entity reference module (possibly some related modules of it also, extending its functionality, as mentioned on the ECK project page) and/or the References module (cfr. 'node\_reference' and 'user\_reference' as contained in CCK for D6).

### Business logic

Using the Rules and Flag module, it is possible to implement all sorts of business logic (= *rules*), simply using the typical Drupal admin UI for those modules.

### Queries, custom reports and charts

* To perform queries (listings, etc), use the views module, possibly further extended with modules such as Views Slideshow: Galleria (there are dozens of modules to further enhance views).
* The Forena module can be used as a supplement / alternative (e.g. if you'd need to also create charts or so, or if you have a need to access data in some external database such as MS SQL, Oracle, etc).
* Create charts using the views integration of the Charts module to visualize a lot of data in a way that can be quickly digested.

### Page Layout

Modules like Display Suite and/or Panels can help to enhance the look and feel of it all also.

### Many more modules

* Group (a pretty new alternative to Organic groups, to create arbitrary collections of your content and users and grant access control permissions on them).
* Workflow (to create arbitrary workflows, and assign them to entities).
* IP Geolocation Views & Maps, a mapping engine to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**)
* Or, or ... on and on goes the list.

Disclosure: I'm a (co-)maintainer of Forena and Charts.

---
Tags: 7, nodes
---


# Question
Title: Adding readonly wysiwyg field to entity form
I'm using entity forms and I want to add a wysiwyg text block in between two form fields, that is just an explanation text. This text does not need to be submitted and should not be editable for the user. It is just an explanation text block that needs to be in the form and that has to be entered via an wysiwyg editor in the backend as it contains some formatted stuff like an headline etc.

Any ideas? Thanks!

# Answer
You can try the Markup module. Should do exactly what you're after.

> This module adds the ability for site admins to add "Markup" widgets to the form. These essentially let designers of cck content-types insert additional markup into the node/edit form to display to content-authors. This is the equivalent of adding additional elements to $form of the type '#markup'.
> 0 votes

---
Tags: entities
---


title: How to access the Webform Mysql View

text:
# Question
Title: How to access the Webform Mysql View
I enabled the module Webform Mysql Views (https://www.drupal.org/project/webform\_mysql\_views). Enabled the webform for which I want to create the view through here - http://YOURWEBSITE/admin/content/webform/mysql

I am still unsure how can I actually see my view in this case. Where do I find it? I was expecting it under the results section just in case but I am unable to find it.

Thanks.

# Answer
> 0 votes
This answer is probably not timely to pal4life, but for anyone else still looking for answers.... this view doesn't show up via the Views module per say. It is best used in conjunction with other modules or code.

For example, I wanted to get filtering functionality on my Webform views and using the Webform MySQL View module seemed to be the recommended way to go. However, you will most likely need to install the Data and Schema modules as well. A great walk through on how to use all three together to create filterable, sortable webform data via Views can be found here:

http://knackforge.com/blog/sivaji/displaying-webform-submission-data-drupal-views#comment-1085

---
Tags: 7, webforms
---


# Question
Title: Unable to use rules to update field after the first update
I currently have a field that shows the last updated date on a user edit page.

I'm using the current configuration for rules.

```
Event:
    After updating an existing user account
    After saving a new user account

Conditions
    Entity has field
      Parameter: Entity: [account], Field: field_last_updated

Actions
    Set a data value
      Paremter: Data: [account:field_last_updated], Value: now

```

It works great the first time but subsequent updates do not update the last\_updated field with the current time. Is there something I'm doing wrong?

# Answer
The issue appeared to be that the 'last updated time' field was updating only in 15 minute increments. Though I'm still not sure why it is in 15 minutes increments or how to turn that off.
> 0 votes

---
Tags: rules, users
---


# Question
Title: Is there a way to schedule Automatic Source Code and Database Backups?
A colleague told me about a plugin that he used to run on Word Press that would save his Source Code and DB automatically. He asked me to look into any plugins like this for Drupal 6.x and 7.x.

Does anyone have any experience with this that they can share?

Thanks,

# Answer
> 2 votes
You can use Backup and Migrate module. It is available for both, Drupal 6 and 7.

> Back up and restore your Drupal MySQL database, code, and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

---
Tags: backups
---


# Question
Title: Content Type vs Webform vs Form API vs Custom Form vs?
I'm currently working on a new Drupal 7 site, which will be used as a data collection and reporting site. After much research / trial and error / etc, I've decided to bring this question to this forum, and am sincerely hoping that it won't be thrown out as being "too generic."

I've created a Content Type, which consists of roughly 25 fields, and am wondering what the best approach for having users populate that content would be? Out of the box (even using Manage Display) the form itself still resembles nothing that I'd actually want to present to the users. And, it seems a bit insane to alter the form using one of the hook\_form\_alter flavors, because the code involved seems way overkill just to hack the form into looking/acting like I intend it to. I've also spent a bit of time with the Webform module, which is ok, but there's still quite a bit of customizing that needs to be done in order to have the form look/act like I intend it to, and there seems to be mixed reviews on that module in general (no offense to anyone!). Same goes for using the Form API...lots and lots of code just to come up with a basic form to collect data.

My latest approach is to simply use the markup type to create the form itself (basically, just straight html / css / javascript, and then populate / update the Content Type behind the scenes. From a developer's point of view, this approach is very, very straight forward - no rocket science - easy to maintain, but I'd certainly like to hear from those of you that know your way around Drupal. Am I overlooking something?

Thanks in advance! cmmsites

# Answer
I'm using Drupal for exactly the same purpose. Basically, what I'm doing is using the Field Group module to wrap particular items together in DIV tags so that I can use CSS styles to properly layout my forms.

Drupal provides a very structured set of container elements with appropriately named classes. Accordingly, leveraging the power of CSS to your advantage should be the first thought that goes through your mind when it comes to manipulating layouts.

I mucked with the Webform module, and although it is quite capable, I've found that just sticking with Drupal's standard content type system for collecting information has suited me best. Utilizing Views and the Rules module, I'm able to generate reporting pages that show me the critical information I want with less modular bloat to my Drupal installation.

So definitely read up on Views, Field Group, and the Rules module to see if the functionality as described will fit your bill.
> 2 votes

# Answer
If you want to move form elements only, you must take a look at Display suit.

You can put the element as you want without write nothing of code.
> 1 votes

# Answer
I you don't need nodes, I'll try with form api and entities. I think it's drupal's future.

It's true that form api it's hack to customice, but it's easy with form api that use a node-form.

Also, if you use the form api you will work as drupal say, if not it'll be hard to have a code for future developers.

Oskar
> 0 votes

# Answer
I worked with webforms extensively over the past couple of months. I am using Webform module, for some things it's really an overkill, but it really depends what is your form, is it complicated with plenty of conditional fields, validation rules etc.

Try having a look into Entity Forms drupal entityforms

And some interesting read here http://stidwill.com/content/web-forms-dead-long-live-entity-forms
> 0 votes

# Answer
I know this question is old, but here is what I think. How you want to use the data is an important determination for how you build the form.

Webform is made for surveys and does it well. It is easy to list your forms and enable/disable them, or change as needed. Each webform has a link to its submissions.

Using a content type (node/entity/whatever) has different permission implications, and allows more flexibility in actions later. You can use the 5-star module or Flag module on a content type, but not on a webform submission.

Making a custom form with the form api is good if you want to process the information yourself and not store it in the database for long term retrieval. I would not go through the trouble of defining a separate form, validation and submission handlers to just do what both node and webform already do. But it sounds like you have already invested the time in doing this. That just goes to prove there is always more than one way to skin a drupal.

Both webform and a custom content type can use the Markup field, https://www.drupal.org/project/markup Both can trigger rules to fire on submission for minor automation tasks (or large automation, depending on your developer's skill) Both have views integration for making a statistics or summary page, if desired. (https://www.drupal.org/project/webform\_mysql\_views)

So if the question really is only "Which method is easiest for custom form display?" then I would say the answer is the custom content type. Field groups, field collections (rarely needed, irritating to handle, but so useful when they are what you need), and the above mentioned markup field will do most things for you. I have used field groups and js to convert a set of radio buttons into tabs when tabs within vertical tabs were not possible with contributed modules. There was one project I built where the form had 80+ fields with heavy repetition. I made this module for use there because I only needed 6 field styles and I was tired of using field names in the form-alters and having copy-replace errors. https://www.drupal.org/sandbox/developerweeks/1964036
> 0 votes

---
Tags: forms, nodes, webforms
---


# Question
Title: How to add auto taxonomy to node fields?
How to add auto categorization(Taxonomy Term) to node based on node body/description.

Node Body/Description: **Retro is back in style, so flaunt the same when wearing this T-shirt from PUMA. Fashioned for men, this piece can be easily worn when heading out for a crazy day ahead with friends. Live in the moment by wearing this T-shirt with casual trousers and flip-flops when you hit the street with your best buddies** Here i have : -\>T-Shirts, flip-flops, MEN etc, By reading this content i want to assign auto **taxonomy term reference in node field** as T-Shirts to node. Is it possible to do this? Anyone help me ASAP. Thanks in advance.

# Answer
If I understand you, there is a few modules which can handle it:

1. Word Link (I recommend it)

> The Word Link module allows you to automatically convert specific words into links. It works as text filter. This can be useful for crossposting your site's pages, or for the contextual advertising of your partners (SEO).

2. Active Taxonomy Links

> Active Taxonomy Links module processes nodes of selected content types replacing words in the nodes with links to taxonomy terms.

3. Glossify (this one supports Drupal 6 also)

> The Glossify module provides filters that scan and parse content and replace terms in the text with links to their pages. The d7 version is a complete rewrite of the module to be as simple and performant as possible.
> 0 votes

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


# Question
Title: Change field input type on node edit form
I'm looking to change the input field widget on my form, but still accept the same value at the end of it.

I have an integer field, and I only want them to be able to select certain integers which are relative to another field in the system. Normally I would just make an integer list field, and change the safe value to the words I want them to pick. eg:

```
1 | Red
2 | Blue
3 | Green

```

However the list is constantly growing so I couldn't manually set it. I've also tried using an Entity Reference field with an Entity Reference view for the values, but I've found that it creates an error when used in conjunction with a Field Collection field in the same node form, so I'm running out of ideas.

I've written some code to give me an array of the values, keyed by the integer number I want on a per node basis which is working, but what I want is to change the input widget from a textfield to a dropdown of my allowed values, but still accept the integer key value when it's submitted.

# Answer
Try this in a custom module...

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_NAME_form_YOUR_FORM_ID_alter(&$form, &$form_state) {

  // Replace the next 5 lines with your logic to set the array of values
  $options = array(
    1 => 'Red',
    2 => 'Blue',
    3 => 'Green',
  );

  $form['FORM_ELEMENT_ID']['#type'] = 'select';
  $form['FORM_ELEMENT_ID']['#options'] = $options;
}

```

Replace MODULE\_NAME, YOUR\_FORM\_ID and FORM\_ELEMENT\_ID with your module name, form id and form element key respectively.
> 0 votes

---
Tags: 7, forms
---


title: Entity reference count in a parent node

text:
# Question
Title: Entity reference count in a parent node
I have two content types

For example say X and Y

Every Y should refer any one of the X . I want to display how many number of Y is refering a particular X while viewing the X node. Please suggest some module which direclty achieve this requirement.

# Answer
> 1 votes
You can either use Views and `Aggregation` to `Sum` the number of references to show on a list.

But, I recommend using the Computed Field module to write some PHP code that is run on save to store an integer value that is the count of references. This value can be cached by drupal and used within Views and other modules.

> Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

---
Tags: nodes
---


title: How to print image url in foreach

text:
# Question
Title: How to print image url in foreach
I successfully print the image url for a individual images by the following:

```
$file = file_load($node->field_hp_slideshow_image['und'][0]['fid']);
                print file_create_url($file->uri);

```

How can I do something similar but display the url of multiple images in a for or for each loop? Below I have this but it doesn't work:

```
<?php $slide_image = $node->field_hp_slideshow_image['und'];
    $slide_url = $node->field_hp_slideshow_link['und'];
    $file = file_load($node->field_hp_slideshow_image['und'][0]['fid']);
    print $field_hp_slideshow_image['und'][0]['filename'];
    print file_create_url($file->uri);
?>
<?php for ($i = 0; $i < count($slide_image); ++$i): ?>
    <div class="slideContent">
        <a href="<?php print $slide_url[$i]['url']; ?>">
        <img src="<?php print $base_url . "/" . $path . "/" . $slide_image['filename']; ?>" alt="" />
        </a>
    </div>
<?php endfor; ?>

```

# Answer
> 1 votes
Install Image URL Formatter and change the format to its url. To do so create a view of set of nodes, select the image as the field and change its format to `URL`. You can also change the format to URL in the manage display of the content type.

---
Tags: 7, theming, uri, media
---


title: Can't load library path files

text:
# Question
Title: Can't load library path files
I have added a library to the libraries folder. I have the Libraries API module installed and I wrote this code:

```
function my_module_libraries_info() {
  $libraries['google-api-php-client'] = array(
    'name' => 'Google Api PHP Client',
    'path' => 'src/Google',
    'vendor_url' => 'https://github.com/google/google-api-php-client',
    'download_url'=> 'https://github.com/google/google-api-php-client',
    'files' => array(
      'php' => array(
        'Client.php',
        'Service.php',
      ),
    ),
  );
  return $libraries;
}

```

and the code to call it

```
$library =libraries_load('google-api-php-client');
dpm($library);

```

This dpm did give me a library array, so it looked like it was ok. But then I tried

```
$client = new Google_Client();
```

and I got an error:

```
PHP Fatal error:  require(): Failed opening required 'http://[site-name-here]/sites/all/libraries/google-api-php-client/src/Google/Client.php'
```

When I tried this

```
 global $base_root;
  require $base_root . '/'. libraries_get_path('google-api-php-client') . '/src/Google/Client.php';

```

I got the same error message. I checked and saw tat the files were still there. What is going wrong?

# Answer
Clearing the cache might help. I had tried to use libraries\_flush\_caches but that didn't seem to work. General CC did though - that will ensure libraries\_load detects and loads the files you put in your files array.

Also, for this library (at least composer version "google/apiclient": "1.0.\*@beta") , you want to put 'autoload.php' in your files array - it'll do what it sounds like, auto-load all the classes you want to use instead of you manually having to do it.
> 0 votes

---
Tags: files, theming
---


# Question
Title: How do I create a total blank page without any header and footer?
I am using Drupal 6 and I am stuck in a situation where I need to create a blank page without any header footer which comes as a part of your theme when you create a new page in Drupal.

I have searched lot on this problem :

1. Drupal link that I used to get solution, but not helped.
2. Create a content type to get blank page solution also not able to solve my problem.

Can any one help me to create blank page without any theme components.

I also read about creating a hook but I am not able to create any hooks.

How I can resolve this issue?

# Answer
> 1 votes
You can make a copy of `page.tpl.php` in your theme and rename it according to the Template Suggestions for Drupal 6.

Your theme should be in a directory like `site/all/themes` or `sites/default/themes`.

So if you wanted a custom `page.tpl.php` for http://yoursite.com/path/to/override, your file name will end up being something like `page--path-to-override.tpl.php`.

# Answer
> 0 votes
In Drupal 6 you likely want to override `page.tpl.php` for your theme; and remove the "header" and "footer" HTML elements.

See the source here: https://api.drupal.org/api/drupal/modules%21system%21page.tpl.php/6

This file outputs your page's full HTML structure. So you can tweak it for content type (using a theme *suggestion*) as need be.

In Drupal 7 to get do the same thing you would tweak `html.tpl.php`.

---
Tags: theming, nodes, 6
---


# Question
Title: How to dynamic change the size of the icon marker when using Leaflet maps and views
I am using the module Leaflet and its sub-module "Leaflet views" and IP Geolocation Views & Maps (IPGV&M for short), which provides a nice way to assign icon images to, in my case, content type in order to get a map displaying markers. I have set it up so to show different markers depending on the content type. I have also a field linked to the nodes, displaying a number, which is the number of users subscribed to that node.

What I need is to **change dynamically the size of the marker**, so that the nodes with more people subscribed (bigger int) will appear bigger than others with lower number.

I am using a view to display the map and the markers.

Any help would be greatly appreciated!

# Answer
Maybe the Leaflet Extension module "Leaflet Label" helps to implement what you are trying to do? It provides a light-weight alternative to marker popups for Leaflet maps using labels, provided by the Leaflet Label javascript plugin.
> 0 votes

---
Tags: javascript
---


# Question
Title: Where do you put your template override files?
I am trying to get Drupal to recognize a template override that is a theme hook suggestion. However, I don't know how to get Drupal 7 to recognize it.

Specifically, Drupal commerce allows for the override of a customer order using the template file commerce-order--commerce-order--customer.tpl.php

I don't know where to put this.

I tried putting the file in my own theme directory, and clearing the cache. But it didn't recognize it. Do I need to add something to the .info file of my theme?

I DID GET THIS TO WORK when I put the template in the main theme of the site, namely the omega\_kickstart template directory. But this is not ideal for upgrading.

Finally, I tried making my theme a sub theme of omega\_kickstart thinking it would override then, but that didn't work.

# Answer
> 0 votes
When creating new templates for your theme you need to name it to match your theme.

You'll want something like:

```
YOURTHEMENAME--commerce-order--customer.tpl.php

```

# Answer
> 0 votes
What exactly this file is going to override? if it is a node then use this code in `template.php`

```
function MYTHEME_preprocess_page(&$variables) {
    if ($variables['node']->type == 'SomeThing') {
    // This will look for template named page--commerce.tpl.php in your theme.
        $variables['theme_hook_suggestions'][] = 'page__commerce';
    }
}

```

then create file `page--commerce.tpl.php` in your theme directory

and if it is a view you can do the same in `hook_preprocess_views_view` or there is another solution in here

# Answer
> 0 votes
You can put the file in your theme directory, you need to clear the theme-registry cache to get the new template to register.

If you have drush: `drush cc theme-registry`

If you do not, use the Clear Cache button (Admin \>\> Configuration \>\> Development \>\> Performance) a few times. You should then have your new template registered.

---
Tags: theming, commerce
---


title: Custom "normal" page in module

text:
# Question
Title: Custom "normal" page in module
Is it possible to create a normal content page in a module? At the moment I only know the $form type. But I need to add a page with some statistics.

Or is there a way to add normal content to a hook\_form?

At the moment I have:

.module file:

```
$items['admin/config/services/push_notifications/stats'] = array(
'type' => MENU_SUGGESTED_ITEM,
'title' => 'Push messages stats',
'access arguments' => array('Push messages stats'),
'page callback' => 'drupal_get_form',
'page arguments' => array('push_notifications_stats_form'),
'description' => 'Push messages stats',
'file' => 'push_notifications.admin.inc',
'file path' => drupal_get_path('module', 'push_notifications') . '/includes',
'weight' => 80,
);

```

And in the .admin file:

```
function push_notifications_stats_form($form, &$form_state) {
$form = array();
$id = $_GET['id'];

$form['id'] = array(
'#type' => 'item',
'#title' => 'Application ID',
'#description' => t('The application ID you are viewing: @appId', array('@appId' => $id)),
);

return $form;

}

```

# Answer
what you want is hook\_menu:

```
  function pushnotifications_menu() {
    $items['admin/config/services/push_notifications/stats'] = array(
      'page callback' => 'yourverycustomcallbackforpushnotfiers_abc_view',
    );
    return $items;
  }

  function yourverycustomcallbackforpushnotfiers_abc_view($ghi = 0, $jkl = '') {
    // all your logic here
  }

```

btw: DO NOT DO THIS!!:

`$id = $_GET['id'];`

Sse drupal\_get\_query\_parameters() instead, if you really have to fiddle with it directly. Otherwise use $args.
> 1 votes

---
Tags: 7
---


# Question
Title: Help Needed with a Hook_form_alter Module
I've written the following module and it's not working. By that I mean it's not printing the #prefix to the webform above the 'resource\_name' field. In fact, it's not printing it anywhere on the page. I'm trying to alter a webform-created node. I've already verified the form\_id is correct as listed. And according to the webform the 'resource\_name' is the field key for the field above which I want to place the #prefix markup. Any help is appreciated, thanks.

Note also that yes I've enabled the module.

```
    <?php

    function webformalter_form_alter(&$form, &$form_state, $form_id) {
      // Check when the right form is passed
      if ($form_id == ' webform_client_form_289') {

        // Add the directions
        $form['resource_name'] = array(
          '#prefix' => '<p>Do you know of a high-quality resource that should be in our
listings?</p><p>Please let us know! We will review it before publishing it, and we will
follow up with any questions.</p>',
        );
  }
}

```

# Answer
> 1 votes
I think your not setting the prefix correctly. I think you want to do something more like this:

```
if ($form_id == ' webform_client_form_289') {
    // Add the directions
    $form['submitted']['#prefix'] = '<p>Do you know of a high-quality resource that should be in our listings?</p><p>Please let us know! We will review it before publishing it, and we will follow up with any questions.</p>';
}

```

Looks like what your trying to do on in your code is set resource\_name to be an array with just prefix in it.

---
Tags: hooks, webforms
---


# Question
Title: Installing and loading google client php api
I am developing a php module that uses the Google Client class from the google client php api. I have downloaded and unzipped the latest google client php api at sites/all/libraries, and put my module at sites/all/modules. The code loading the library is this:

```
if (($library = libraries_load("google-api-php-client")) && !empty($library['loaded'])) {
    print "success";
}

$client = new Google_Client();

```

However, I am getting "Class 'Google\_Client' not found" when I try to access it. Also, the print is not showing, as if the library never loads. However when I use `libraries_get_path()` I do receive the correct path: sites/all/libraries/google-api-php-client

I have tried the checks here but they all fail. I am using the Libraries API 7.x-2.1 and drupal 7.22

My hook\_libraries\_info() implementation:

```
function hook_libraries_info() {
    $libraries['google-api-php-client'] = array(
        'name' => 'Google API PHP Client',
        'vendor url' => 'https://code.google.com/p/google-api-php-client/',
        'download url' => 'https://code.google.com/p/google-api-php-client/downloads/list',
        'version arguments' => array(
            'file' => 'README',
            'pattern' => '/Version (\d+)/',
            'lines' => 5,
        ),
        'files' => array(
            'php' => array(
                'Google_Client.php',
                'config.php',
            ),
        ),
        'integration files' => array(
            'calendarVis' => array(
                'php' => array(
                    'Google_Client.php',
                    'config.php',
                ),
            ),
        ),
    );
    return $libraries;
}

```

Other than that, I have tried creating an .info file, which worked on my initial wampserver setup, but I cannot make it work anywhere else. Here is the .info file:

```
name = calendarVis
description = Google Calendar Visualization for P-space
core = 7.x

dependencies[] = libraries

```

Also, after accessing the page that uses the module and returning to administrator menus, I am getting this error message:

"Warning: Invalid argument supplied for foreach() in libraries\_invoke() (line 161 of drupal-7.22/sites/all/modules/libraries/libraries.module). Notice: Undefined index: installed in libraries\_load() (line 621 of drupal-7.22/sites/all/modules/libraries/libraries.module)."

# Answer
Here's an updated answer (the version of the client library I'm using is "google/apiclient": "1.0.\*@beta")

```
    function hook_libraries_info() {
     $libraries['google-api-php-client'] = array(
     'name' => 'Google API PHP Client',
     'vendor url' => 'http://developers.google.com/api-client-library/php',
     'download url' => 'http://developers.google.com/api-client-library/php',
     'path' => 'src/Google/',
     'version' => '1',
     'files' => array(
      'php' => array(
        'autoload.php'
      )
    )
  );
  return $libraries;
}

```

Note, the 'autoload.php' file in the files array. This will automagically load all the classes you might want, and seems to work well for me; rather than manually selecting each file the library includes that I might need.

I load the library and then use it like this:

```
$library = libraries_load('google-api-php-client');
module_load_include('inc', 'page_speed', 'page_speed_client');

```

My inc file contains the logic I want for defining a new client and service (see the Google docs) and does a Pagespeed Insight query, and (for now) simply dumps the returned data onto a page.

Final caveat, remember to clear cache if you edit your files array, otherwise the library won't load properly, that caught me out a couple of times.
> 1 votes

---
Tags: theming
---


# Question
Title: Possible to hide admin toolbar for testing display
I've worked on and off with Drupal for a few years.

One thing that has bothered me a bit, is that the admin toolbar at the top doesn't give you the full flavour of what the public will see.

I usually get around this by using a second browser where I'm not logged in.

I wonder if there is a simple url parameter or some other setting that can turn off or hide the toolbar for testing display.

searching the web reveals a trick with some permissions.

https://kitt.hodsden.org/blog/2011/02/turning\_drupal\_7\_admin\_toolbar

But using a second browser seems easier as I'll want this for just a few minutes at a time.

Could I write a simple plugin that will catch some url parameter and hide the admin toolbar, is there such a thing already?

# Answer
If your using the built in D7 tool bar, take a look at Toolbar Hider.

> This module will hide/show the toolbar with the press of a key that you configure. It will optionally adjust the page padding to hide the white space. You can also configure if you would like to hide the toolbar by default.

If your using the contributed admin menu, there is also Admin Menu Hider, which does the same thing, but is in alpha.
> 3 votes

# Answer
You could use Masquerade and create user without the permission to use the toolbar.
> 2 votes

---
Tags: users, uri, toolbar
---


title: View Preview Correct , Actual Page Not

text:
# Question
Title: View Preview Correct , Actual Page Not
I have a block view that I am placing in every page containing the content type "class". There are several "lesson" content types referencing it through entity reference "field\_class".

I want the view to display all lessons referencing the class.

I set my view up like so:

When I pass the args through it, it displays correctly, as in the first image.

When I go to the same page whose node id I passed through the view preview to get a correct output, I find that the page is displaying something different:

The result showing is the "no results" default summary.

Can anyone tell me what I'm doing wrong, or suggest advice to clear up the problem?

I'm using drupal 7. To place the block in the page I'm using panelizer. I'm not using any internationalization modules

Any help would be greatly appreciated.

EDIT:

Here is the screenshot of my contextual filter:

# Answer
Change the filter to "Provide default value", and then choose the node ID from the URL.
> 0 votes

---
Tags: views, panels
---


# Question
Title: cache issue - misaligned views cached output
I am trying to set the view on the home page. http://www.userbase.com/

The content gets misaligned for anonymous user. I can see proper output if I am logged in.

Any ides?

I am using following cache plugins:

* Block Cache Alter
* Render cache
* Render cache for comments added to a node
* Render cache for display suite views integration
* Render cache for node\_show
* Render cache for views\_plugin\_row\_node\_view
* Safe cache\_form Clear

# Answer
> 0 votes
It looks like you need to add `clearfix` to the css attribute of your views rows.

---
Tags: views, caching
---


title: Override login page with Panels

text:
# Question
Title: Override login page with Panels
I want to override the login page using panels. I found a tutorial that shows me how to do it using Panels Everywhere, but that overrides the whole page (with `site_template`). I just want to override the page content.

Is this possible?

# Answer
You can override existing paths with the Page Manager Existing Pages Module.

I have not used it with a login page but it works well for other cases. You can use it to override an existing page's path and then add the original content for that path as a panels pane alongside your custom additions.
> 10 votes

# Answer
It's not impossible to do what you want, but it's close. I wont go into the details of how to code it, but will explain what needs to be done.

The main problem is that panels can't override existing paths.

One solution would be to unset the `user/login` path with `hook_menu_alter` and then create a panels page for that path. Step two would be to create the login form as a content pane. If this works, it would be the most simple solution, but this is also the most fragile solution.

The other solution would be to use `hook_menu_alter` to alter the callback and with panels APIs render a panel page. This is quite tricky, and I wont go into the details, but an example of this can be seen in the Commerce Panels Integration sandbox module. It does this, only in a more complex case, for the commerce checkout progress. You would also need to create the user login form as a content pane in this solution.

I've tried using the concept in Commerce Panels Integration but found that there were some bugs when doing AJAX stuff. So none of these solutions might be ideal, it depends a bit on what you need on the panels page you are creating.
> 2 votes

# Answer
For those who do not want to want to read the entire issue https://www.drupal.org/node/807754

It is suggested to use the following module: **User Pages**.

> The **User Pages** module allows you to manage following user related pages:
>
> * user
> * user/login
> * user/register
> * user/password
>
> By, default these user page are not available in **Chaos Tool Suite**. Once you install it, pages will be automatically available in **Page Manager** and can be managed via Panels.
> 2 votes

---
Tags: 7, panels, users
---


# Question
Title: Why are there two default image options in an image field
When you create a field of type image in Drupal 7, there are two default image fields.

One is in settings and the other is in field settings. There is a message with each of those two settings, but I still don't understand how they are different. In each case, they upload to the **sites/default/files/default\_images** folder.

What is the difference between the two settings fields?

# Answer
One is the default image information for that field as a global entity, while the other is specific to that instance of the field. Fields can be re-used across different content types, so the global default would apply to every content type that used that field, unless those content types override that behaviour with their own specific default.
> 2 votes

---
Tags: entities, nodes
---


# Question
Title: Another question on Drupal files folder permissions and security
So there are the following two posts (among others) that say 755 is okay for the sites/default/files directory:

1. What are the recommended directory permissions?
2. Confusion about files permission

I took over a site that was hacked (due to missing a security update and improper Drupal/server configurations), whereby the hacker setup a generic form to download files (.js, .php, etc.) to the default files folder, then presumably they'd be able to execute them by setting up another page on the site that actually loads the file.

They did this by commandeering a site with admin privileges. And while I could not find an actual file they downloaded to the files directory, they did wind up altering the company's homepage with a "You've been hacked" message and an image of a country's flag.

Now to my questions:

1. Why have 755 on sites/default/files directory (and sub-directories) instead of 744? Isn't the files folder by definition for user files and system caching files? To flip the question around, is there any legitimate reason to allow "x" for the group/other users?
2. Is the new default .htaccess file (shown below for reference) that gets written to sites/default/files "secure enough" that even if a user hacks the front end or database, they can't really cause much havoc? If not, is there something that can be done to prevent all executables from running within /sites/default/files?

Here's the .htaccess file written by Drupal:

```
# Turn off all options we don't need.
Options None
Options +FollowSymLinks
# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
# Override the handler again if we're run later in the evaluation list.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>
# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
php_flag engine off
</IfModule>

```

# Answer
> 2 votes
> Why have 755 on sites/default/files directory (and sub-directories) instead of 744? Isn't the files folder by definition for user files and system caching files? To flip the question around, is there any legitimate reason to allow "x" for the group/other users?

Without the "x" being set for a *directory*, the group/user will not be able to look inside the directory. So you usually want the "x" bit set for group/users for the directory in order to be able to examine these in the CLI without being *root*.

> Is the new default .htaccess file (shown below for reference) that gets written to sites/default/files "secure enough" that even if a user hacks the front end or database, they can't really cause much havoc?

IMHO, the Drupal `.htaccess` is adequate for preventing executables downloaded to the upload from being executed.

However, having this file in place does *not* protect you from front-end or database exploits. And attackers gaining access to execute PHP from the database can remove or replace it.

So you also want to prevent PHP injected into the *datebase* from being executed. You do this by *removing* the core PHP module. Do this:

```
rm -rf modules/php/

```

You should never *enable* this misfeature (it has been removed from core in D8), but by physically removing out, you eliminate the risk of somebody making a succesful SQL injection exploit also being able to execute PHP.

Provided you don't use it (and you shouldn't), and it is already disabled, removing it has no side-effects.

---
Tags: security, .htaccess, files
---


# Question
Title: Change Profile2 Profile Type after registration
I am trying to get Profile2 module to work with Simple\_FB\_Connect but the flow of Simple\_FB\_Connect requires that the user signs up first and then i need to be able to set the Profile2 user type afterwards.

After returning from FB i want the user to be able to click "Consumer" for example and their Profile gets set. Something like this...

```
function MYMODULE_set_user_type() {
  global $user;
  //dsm($user);
  $uid = $user->uid;

  $type = $_GET['type'];
  if (isset($type)) {
    profile2_load_by_user($uid, $type_name = 'main');
    // Unsure what to put here.
    profile2_save($profile);
  }
}

```

# Answer
It's not currently possible with this module. The project page advertises a `hook_simple_fb_connect_register_alter()` hook to take action on registration, but looking at the current 7.1.15 version & the 7.2.x branch reveals only a placeholder hook. You'll have to wait for the maintainer to implement it, or to use another module that allows hooks following FB authentication.
> 1 votes

---
Tags: users
---


# Question
Title: Is a custom module the best way to build out a Form with full custom AJAX?
I have a project (problem) I've been thinking about for about a week now. When it was first presented to me it seemed to be a very easy solution, and frankly there are easy ways to accomplish this, but I don't necessarily like them. Let me lay this out though.

**The Simple Problem**

At its simplest this project is creating a simple (name, email, and one other field) form that will be available from any page of our site.

**Let's Get Complicated**

I want this form to be available on each page, but possibly tucked away with a call to action befitting our user base. On top of that I am not looking to just have a link to a Webform page, but an AJAX powered form so that my users do not lose their place in the site if they choose to submit their information.

**So what's the ultimate problem?**

I've looked into modules like Webform AJAX, but they don't allow the kind of fine grain AJAX control I want. I've done research into the Form API (Which, btw, if you have a great resource for understanding this better, please feel free to pass it along.), and it would appear that to accomplish everything I want to do with this simple form would require me to create a custom module.

**Questions I have.**

1. Is that right?
2. Am I way off base?
3. How much have I over-thought this project?

Thanks in advance.

# Answer
1. Building custom module for mentioned requirements would make your work easy and dynamic. Dynamic in sense you can add more links if you publish any new page in future.
2. It would be great if you use ctools-modal with custom module. I was facing the same problem. I had wasted a week for finding better way to get link with ajax form.
> 0 votes

---
Tags: forms
---


# Question
Title: Is there any way to export data to CSV file and then import updated data?
I have a website I started to build couple years ago. But the website itself grew up to something bigger, with more fields and details - and old data are missing these. E.g., recently added Long./Lat. fields but old content doesn’t have them. So I wonder if it’s possible (and what module) to export all data into csv file, update it (I think it's much easier than open one by one node) and than import the updated data? Or something like that.

Thanks for any help.

# Answer
If you want to do it that way, use Views data export. Here is an excerpt about it from the module's project page:

> ... designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> * CSV.
> * Microsoft XLS.
> * Microsoft DOC.
> * Basic TXT.
> * XML.

Then, re-import using the Feeds module. Here is an excerpt about it from the module's project page:

> Import or aggregate data as nodes, users, taxonomy terms or simple database records.
>
> * One-off imports and periodic aggregation of content
> * Import or aggregate RSS/Atom feeds
> * Import or aggregate CSV files
> * Import or aggregate OPML files
> * PubSubHubbub support
> * Create nodes, users, taxonomy terms or simple database records from import
> * Extensible to import any other kind of content
> * Granular mapping of input elements to Drupal content elements
> * Exportable configurations
> * Batched import for large files
> 1 votes

# Answer
The feeds module, as suggested by RoloDMonkey seems indeed the way to go for re-importing updated data.

However, to export the data, you may want to consider the Forena module. Here is a quote from that page:

> ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

> Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are **CSV**, XLS, DOC, HTML, etc.

The steps for creating such CSV files are:

* a **connection** to an external database (one time only, for each database).
* a custom **SQL query** (where you have the full power of SQL at your fingertips, and various extra features related to it provided by Forena, such as using report parameters, conditional SQL, etc).
* a custom **report** (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).
* saving the report in (eg) CSV format, using one of the typical hyperlinks to do so in a report.

These steps do not require any PHP coding.

If you're interested in an **online demo site** (prior to installing/testing Forena), then checkout these links:

Disclosure: I'm a **co**-maintainer (not owner ...) of this module,
I hope this does not violate the site's policy on self-promotion.
> 0 votes

# Answer
You can use the Data export import module for data importing exporting purpose. Here is an excerpt about it from the module's project page:

> The purpose of this module is to be able to export nodes, taxonomy terms and users to data files and then be able to import these data files into Drupal sites. There may be many uses for this module but the main one would be that it can provide a way to export data from a live Drupal site and then to import that live data into an updated version of that site.
>
> So, data can be exported and then imported - hence the name; Data Export Import.
> 0 votes

---
Tags: importing-exporting
---


title: Kick Out Form builder module

text:
# Question
Title: Kick Out Form builder module
I have install Form Builder module and Webform module.

**Webform module:** Create form feature

**Form Builder:** Integrate into webform for more friendly user by click and drag

Recently I realize form builder is a annoying module. Here are the problem cause by form builder:

> **1) Problem:** Unable to multiple select list.
>
> **Solution**: Webform module has a checkbox for multiple select. Just check will do. Unfortunately, does not appear in form builder.
>
> **2)** Install Webform Hints module(Placeholder feature): Does not appear in form builder.

As you can see without form builder, I realize all this features can be done by webform itself.

Now I uninstall form builder and face another stupid problem cause by form builder. Form component link is not working. Cant edit form unless I install back form builder module. See the picture below. I super regret to install such a useless module.

What should I do?

# Answer
First off, I think you misunderstand what form builder is for. As it's project page says ...

> ... \[it\] does not provide any permanent mechanism for saving data with the created forms. In other words, it does nothing but build the form....

It's a utility for building form data structures, not for creating and capturing data for forms.

The module you're looking for, as you've found, is webform. It provides an interface (albeit not as nice looking) to build web form content and capture data. That's the only module you need. It looks like from your image you've created a webform node. The form components tab link should present a form that allows you to add/edit components. As shown below...

If this interface isn't appearing I would make sure to uninstall both form builder & webform, remove form builder completely, make sure there is no node content type called **webform**, then try to reinstall webform again. It should work after a fresh install.
> 1 votes

---
Tags: 7, forms, webforms
---


title: Reset Password in drupal 7

text:
# Question
Title: Reset Password in drupal 7
I want following functionality when user click on forgot password.

I want user will get an email to rest his password. when he click the link, A new password wil generated and send into his email

Any idea?

Thanks

# Answer
By default Drupal has forget password functionality which will send the one time password link to the user. may be you can use this https://www.drupal.org/project/simple\_pass\_reset module if it matches your requirement

https://stackoverflow.com/questions/24051390/change-admin-password-in-drupal-7
> 0 votes

---
Tags: 7, users
---


# Question
Title: bookmark organize for anonymous user permission
I have use drupal 7. I download and install the flag , flag bookmark, bookmark module.I have also add settings for bookmark. Bookmark functionality is work for authenticated and admin user. i wanna functionality for anonymous user. So how can I use for anonymous user ?

I have check the permission but they can't provide the permission for anonymous user.

so can you explain me how can I do this task ?

# Answer
> 1 votes
To my knowledge, the features of the flag module are designed to be used by authenticated user only, so not by anonymous users.

The closest you can come to address your question, is as is described in How to display a flag to anonymous users?, i.e.:

> When an anonymous user clicks on flag, then such user should be redirected to the login page. After login the user should be able to set flag.

And then do as described in the answer to that same question, i.e.:

> You can do this in your 'node.tpl.php' ...: if user is logged in then display flag as normal; if not logged in then redirect user to logging page with destination parameter.

---
Tags: flags
---


# Question
Title: How can I filter by a term when on a sub-page of that term?
I have a non-hierarchical taxonomy and 2 content types.

I need to make these pages with Views:

```
Mysite.com/something/termA/ContentTypeA
(This will display nodes of content type A that are tagged with termA.)

Mysite.com/something/termA/ContentTypeB
(This will display nodes of content type B that are tagged with termA.)

Mysite.com/something/termA/ContentTypeA
(This will display nodes of content type A that are tagged with termA.)

Mysite.com/something/termB/ContentTypeB
(This will display nodes of content type B that are tagged with termB.)

```

In actual fact there are a lot of terms so I need these pages to be from 1 or 2 Views (EG with dynamic filters). I cant just make 4 Views with static filters.

I could create 2 Views, one for each content type. Filtering by the content type is simple so my issue is just that I need to figure out how to filter by a term when you are on a sub page of that term, not on the term's page itself.

```
Eg filtering by termA on this page is easy:
Mysite.com/something/termA/

But how do you filter by termA when on this page?
Mysite.com/something/termA/ContentTypeA

```

# Answer
This can be done by adding a module.

First clone the default View "Taxonomy term". Then add a page displays which use the default term URL followed by whatever the sub page needs to be eg taxonomy/term/%/ContentTypeA. On this page I can filter by the content type.

Now the page will work at this URL: /taxonomy/term/1/ContentTypeA

However it wont work with the Pathauto path that ive previously set for the term page. EG this wont work: /something/termA/ContentTypeA

To make Pathauto recognize the URL you just need to install the Sub Pathauto module: https://www.drupal.org/project/subpathauto

Credit to @Paul Querol who helped me out here: Views contextual filter not working for Pathauto path
> 0 votes

# Answer
I'm a little confuse on what you're trying to show but I think you can do what you want with contextual filters.

To do so:

* Add taxonomy to the filter critera (Has taxonomy term ID)
* In the first section (when not available), select Provide default value
* Type : Raw Value from URL
* Select your path component (let say 2 for your term1, categories would be 1)
* In the "When the filter value IS available or a default is provided" section, check "Specify validation criteria"
* Validator : Taxonomy
* Check the appropriate vocabulatory
* Filter value type : Term name converted to ID

What that filter will do is check a part of the url and match it against the vocabulary. If a term is matched, let say term1, it will show nodes that have the term. You can add multiple filter to validate multiple part of the url. It's pretty much the same for the content types.

So /term1 could filter all node with term1. term1/activities could filter all term1&activities... You get the idea. Just don't hide the view if the filter doesn't validate, make it show all results.
> 0 votes

---
Tags: views
---


# Question
Title: File_load for image path errors when empty
I need to print the URL of an image in a content type TPL file. I can do this with the following code:

```
<?php $file = file_load($node->FIELD_NAME['und'][0]['fid']); ?>
<?php print file_create_url($file->uri); ?>

```

However if the field is empty then I get errors on the screen. I tried only printing the URL if $file had a value:

```
<?php if (!empty($file)): ?>
  <?php print file_create_url($file->uri); ?>
<?php endif; ?>

```

However im still getting the errors if the field is empty. I understand that it is the first line of the code which creates the variable that is causing the issue. How can I rewrite this to not cause errors?

By the way im a themer not a back-end developer so if there is a more 'themer friendly' solution that would be my preference.

# Answer
Found the answer here: http://www.drupalden.co.uk/rendering-drupal-7-fields-custom-node.tpl.php-templates

```
<?php
// field_my_image is the name of the image field

  // using field_get_items() you can get the field values (respecting multilingual setup)
  $field_my_image = field_get_items('node', $node, 'field_my_image');

  // after you have the values, you can get the image URL (you can use foreach here)
  $my_image_url = file_create_url($field_my_image[0]['uri']);

  print $my_image_url;
?>

```
> 1 votes

# Answer
It sounds like your code is bugging out with `$node->FIELD_NAME['und'][0]['fid']`; the `'fid'` element (and its parent elements) don't exist so it breaks before you even get to `file_load()`.

Here's a themer friendly solution. Save yourself later headache if you just stick with render logic in your **node--TYPE.tpl.php** template. Place the `'fid'` null check in a `YOURTHEME_preprocess_node(&$variables)` inside your theme's **template.php**:

```
function YOURTHEME_preprocess_node(&$variables) {
  $file = isset($variables['node']->FIELD_NAME['und'][0]['fid']) ? file_load($variables['node']->FIELD_NAME['und'][0]['fid']) : null;
  $variables['file_url'] = !isset($file->uri) ? file_create_url($file->uri) : '';
}

```

Replace YOURTHEME with the machine name of your theme and empty your cache. At that point you should have a variable `$file_url` in your **node--TYPE.tpl.php** template that will either have the full URL or an empty string.
> 0 votes

---
Tags: theming
---


title: How do I create my own tokens?

text:
# Question
Title: How do I create my own tokens?
I use the Rules module. I want to add 1 to a CCK integer field on an action. Someone told me to create a custom token doing this addition.

So, I installed the tokenSTARTER module.

Now, how do I access the content profile (I load it in the rules chain) where the needed CCK field is in?

# Answer
> 8 votes
This module is very good for that: Custom Tokens.

> It gives the user the ability to create custom tokens for specific replacements that can improve other modules relying on the Drupal 7 token API or, for Drupal 6, the Token module.

# Answer
> 0 votes
Look for creation custom token for Drupal 7 at https://www.drupal.org/node/1308488

---
Tags: entities, tokens
---


title: How to manage user permissions?

text:
# Question
Title: How to manage user permissions?
I would like to manage user permissions with Drush, but I don't find any command on the official documentation website.

How to achieve this?

I am using Drupal 6, and Drush 6.0-dev.

# Answer
> 9 votes
Try this command:

```
drush role-add-perm 'user-role' 'permission'

```

# Answer
> 4 votes
You can install the Permissions API

> The permissions\_api module provides a method for granting and revoking permissions for a given role. This module helps with the issue of staging a Drupal site across multiple environments, from development sandbox to production environment.

...

> Version 6.x-2.9 adds support for **Drush**!

# Answer
> 2 votes
permissions\_api will work for your purposes, but as of yet it has no 7.x version. For those who want a solution that works with both Drupal 6 and Drupal 7, Drush v6.0-dev has commands to manage roles and permissions built in. See `drush help` and this previous answer: Creating a new user role with Drush

Regarding finding the commands available in a module that has Drush support, use `drush help --filter`, and Drush will show the available command groupings. Select the module you are interested in, and all of the Drush commands it supports will be displayed. If you are having trouble getting Drush to recognize a new commandfile, try `drush cc drush` to clear the Drush command cache. Drush will do this automatically when a new module is downloaded and enabled, but you may need to do it manually if you copy in a Drush commandfile by hand.

# Answer
> 1 votes
have you tried ?

```
 drush php-eval 'node_access_rebuild();'

```

---
Tags: drush
---


# Question
Title: Add foreign key to schema using hook_update_N
I've written a module that establishes a child/parent relation ship between magazine issues and the articles in each issue. The idea is that by associating articles with magazine issues they can all be automatically published on a given date via cron. That all works fine.

The problem is I'm trying to use a View to list a subset of those articles and list them according the parent issues date, but that isn't showing up as a relationship. I assume the problem is that I haven't defined a foreign key in my schema.

Is it possible to add one in hook\_update\_N or whatever?

To clarify, the relationship is created using fields defined in a custom module using the Field API where the parent node has the date info and the child node has a field for the parent NID.

# Answer
You can add keys to tables using native SQL. It's not supported by drupal 7 core api. I answered this previously elsewhere: Is there a way to add a foreign key to a table?

I doubt that simply adding a key will expose the relationship for you in Views though.

In order for Views to see this information you likely need to supply the info via hook\_views\_data() about your custom tables and relationships. A recent blog post I found about this today actually was: https://chacadwa.com/blog/2014/08/12/adding-full-views-support-custom-entities

From this blog post you can see that for a table that needs a join to add extra fields (and to do so by default in Views) they add the following array to their hook\_views\_data() function.

```
// Define a default relationship to the staffdir extra data table.

$data['hank_hrper']['table']['default_relationship'] = array(
  'hank_hrper_extra_data' => array(
    'table' => 'hank_hrper_extra_data',
    'field' => 'hrper_id',
  ),
);

// Now define the staffdir extra data table, so views can use it.

$data['hank_hrper_extra_data'] = array(
  'table' => array(
    'group' => t('Staff directory'),
    'entity type' => 'staffdir',
    'join' => array(
      'hank_hrper' => array(
        'left_field' => 'hrper_id',
        'field' => 'hrper_id',
      ),
    ),
    'default_relationship' => array(
      'hank_hrper' => array(
        'table' => 'hank_hrper',
        'field' => 'hrper_id',
      ),
    ),
  ),
);

// Now we can define fields from the staffdir extra data table for use in the relationship.

$data['hank_hrper_extra_data']['opt_out'] = array(
  'title' => t('Opt out'),
  'help' => t('Allows for users to be excluded from the directory.'),
  'field' => array(
    'handler' => 'views_handler_field_boolean',
    'click sortable' => FALSE, // could be TRUE, but why?
  ),
  'filter' => array(
    'handler' => 'views_handler_filter_boolean_operator',
     'accept null' => TRUE,
    'help' => t('Filter results to a particular result set'),
  ),
);

```
> 2 votes

# Answer
MySQL foreign keys and Views relationships are separate, unrelated concepts - to tell Views about a relationship between two fields, you need to use `hook_views_data()` (or `hook_views_data_alter()` if you're altering another module's data).

You *can* define foreign keys in `hook_schema()`, and subsequently update them using `db_change_field()` in an update hook, but it won't do anything.

Foreign keys are defined for documentation purposes only in Drupal, there's nothing enforced at the DBMS level.
> 1 votes

# Answer
In the end it turned out to be pretty easy to establish the relationship using some code stolen from the excellent references module (specifically node\_reference). I made that a dependency of my module so I could re-use their view handler `'references_handler_relationship'`. For completeness I'd have extracted that and placed similar code in my own module.

Incidentally that is also where I got the foreign key idea, which will apparently be more relevant in later versions of Drupal and currently only in use as documentation.

```
<?php
/**
 * Implements hook_field_views_data().
 *
 * In addition to the default field information we add the relationship for
 * views to connect back to the node table.
 */
function pubdate_field_views_data($field) {
  // No module_load_include(): this hook is invoked from
  // views/modules/field.views.inc, which is where that function is defined.
  $data = field_views_field_default_views_data($field);

  $storage = $field['storage']['details']['sql'];
  foreach ($storage as $age => $table_data) {
    $table = key($table_data);
    $columns = current($table_data);
    $id_column = $columns['pubdate_parent'];
    if ($field['type'] == 'pubdate_parent' && isset($data[$table])) {
      // Relationship.
      $data[$table][$id_column]['relationship'] = array(
        'handler' => 'references_handler_relationship',
        'base' => 'node',
        'base field' => 'nid',
        'field' => $id_column,
        'label' => $field['field_name'],
        'field_name' => $field['field_name'],
      );
    }
  }

  return $data;
}

```
> 0 votes

---
Tags: entities, database
---


title: How to edit Calendar title

text:
# Question
Title: How to edit Calendar title
Module: https://www.drupal.org/project/calendar

I wan to remove Saturday. Only display August 1, 2015.

Picture below show that I already change some setting, but not working at all.

What should I do? Many Thanks.

# Answer
The format of the pager header can be modified on the date view configuration page `admin/config/regional/date-time/date-views`. On that page, find the format that you wish to update, in your case **Date views day format with year**, which by default is `l, F j, Y`.

Update that value to be `F j, Y`, since `l` returns the weekday, and your date will show as you need it.
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: Views slideshow displaying multiple items
Under view action advanced Options of 'Views slideshow' I have defined 4 items per slide which is displaying 4 items one under each other. Is there a way we can display them in a single row?

# Answer
> 0 votes
You need to add views slidehshow cycle module as well

# Answer
> 0 votes
You need to add the following bit of CSS to get multiple items displayed in a single row:

```
.views-slideshow-cycle-main-frame-row-item {
  float: left;
  padding-right: 13px;
}

```

---
Tags: views
---


# Question
Title: Is there a way to disallow the node/* path for anonymous users?
The reason of my question is that I have built a one-page website, but if people who knows a bit of drupal patterns wants to try to request the site by editing the url with a path like domain.tld/node/12 (for ex.), they will be redirected to the clean url and it will work, but this behavior is not intended and the theming customized in a way which is not made for direct requests on nodes.
Apart from the one-page, all the other content is in views and blocks, with a few colorbox links to open one content type in detail.
What I want to do is find a way to disallow node/\* requests in path, just to "keep some control" of the way anonymous users visit the site (and potentially test it).

I have tested internal nodes which gives a partial answer, but it disallows all node's requests in colorbox.

I tried path rules but same issue as internal nodes.

Any idea to help me?

# Answer
You can give permission to particular node using hook\_permission().

```
function your_module_name_permission() {
  return array(
    'access your modulename module' => array(
      'title' => t('Access your modulename module'),
      'description' => t('Allows access to your modulename module'),
      'restrict access' => TRUE
    ),
  );
}

```

and then go to permission section under people menu. and uncheck above created permission for anonymous user.
> 0 votes

# Answer
I believe the Taxonomy Access Control or Taxonomy Access Control Lite is what you need. You can set the access control for user roles based on taxonomy categories. Here are the features.

* Automatically controls access to nodes(based on their taxonomy terms)
* Configuration page for each user role.
* Three node access permission types: View, Update, Delete.
* Two term access types: View tag, Add tag.

Here are the steps you need

1. Create a Vocabulary in Taxonomy, and named something like "Access Permission". Then add "Member" term.
2. Add a "**Term reference**" field on a Content type with that Vocabulary you just created. Make sure the **Required field is NOT checked**, so you can use the default None value.
3. Go to "**Configuration \> People \> Taxonomy access control**" and add that "Member" term to anonymous user. Set the View, Update and Delete to "**D**", then Save all.

This way, anonymous user will not be able to view any node with "Member" term. You may also want to set the Default 403 to the login page, so whoever try to access "Member" term page will require to login. You can change the default 403 in "Configuration \> System \> Site information".
> 0 votes

---
Tags: users, uri
---


# Question
Title: Add fieldset with add more button using ajax
I have one fieldset like,

Education Qualification: 1. School, 2. College, 3. Course, 4. Year (these are the fields which will be in this fieldset)

Now I want to do "Add more" button under this fieldset then it will add same another fieldset as per user's requirement. If anyone have an idea so let me know on this. I can use Webform or Content Type also. Which will be suited for this type of form.?

# Answer
This is easy to achieve with a content type and the Field collection module. With that you can set up a qualification field of type field collection, then go to admin-\>structure-\>field collections and add the individual fields (School / College / Course). If the qualifications field has a "Number of values" setting of "unlinmited" then you'll automatically get the "Add more" functionality as you described.

You may need to also use Field Group or Field Collection Fieldset in order to make the fields appear in a fieldset.
> 0 votes

---
Tags: 7
---


# Question
Title: How can I search internal blocks in the admin section?
I've inherited a very large site that I didn't build. I am trying to find one particular block amid around a hundred - I'd like to search these blocks for some of the specific HTML classes they contain to edit them.

It looks like https://www.drupal.org/project/block\_search isn't up to date anymore - is there a convenient way to search the admin section of a drupal site?

# Answer
> 1 votes
If the block you're looking for is a "custom block", i.e. one that you create via structure-\>blocks-\>Add block rather than one defined in a module then you should be able to query the database for it like this:

```
SELECT * FROM block_custom WHERE body like '%my-class%'

```

...changing "my-class" as appropriate.

Alternatively, you can inspect the markup of the block on the front end and look for a class such as block-123, then navigate to /admin/structure/block/manage/block/123/configure, replacing 123 with whichever block number you found.

If there's no body field on that page then it's probably a block defined by a module. Then you can try to find a clue as to where it's defined in the classes on the contents of the block, for example if you see lots of classes with the word views in it then it will be a block defined in views and you should look in the views UI to find where it's defined.

Also, turning on the core contextual links module may help as well.

n.b. All this is based on the assumption that we're talking about Drupal 7. Much of it applies for other versions with some tweaking.

---
Tags: search
---


# Question
Title: printing file entity fields in a node.tpl
I have some fields in a file entity type. Now I need to print some of these fields directly in a node.tpl.

How can I do this?

# Answer
> 0 votes
You could do this in a variety of ways. One way: in template.php, invoke `YOURTHEME_preproces_node(&$vars){}`. Inside it, do:

`if($vars['type' == 'YOUR_CONTENT_TYPE'){
 $wrapper = entity_metadata_wrapper("node", $vars["node"]);
 $file = $wrapper->YOUR_FILE_FIELD->value();
 ...
 }`

The `$file` variable should now contain your file object (or an array of file objects). Debug that with `print_r($file)` (or, preferably, with xdebug or another debugger) and you can add variables the `$vars` array there with:

`$vars['YOURVARIABLE'] = $file->YOURFIELD...`

which will then be available in your template as `$YOURVARIABLE`.

---
Tags: theming, entities, files
---


# Question
Title: Views block showing empty content on front end
I created a view to show a list of news items. I placed the view block in the content bottom region of the page. In the Views preview, it shows the results. However in the front end, the content is empty and shows:

```
<div id="block-views-news_list-block_1" class="clear-block block block-views">
<div class="content"></div>
</div>

```

I do have a view template for this block - views-view--news-list--block-1.tpl.php. In the Views page it shows this template as selected. I do not see that it is being rendered on the page though. Even when I just put a basic div with text in the views template, nothing shows in the content div.

What are the possible reasons for this? What can I do to get content to show?

# Answer
> 0 votes
Turns out it was my theme's block.tpl.php file. It was displaying content like so, `$block->content`.

I changed it to match the block.tpl.php file in modules/block:

```
<?php print $content ?>

```

# Answer
> -1 votes
I would check the following:

Does it work without the views template?

Does it use arguments in the view? If so, are they set correctly in the block.

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


title: Download Views CSV automatically Daily

text:
# Question
Title: Download Views CSV automatically Daily
I have a bunch of views/reports built for my client. The reviewers then click download csv for the excel file. They asked if the views could download themselves daily to a folder.

Is that possible? And could you share links or knowledge how to handle this. I have been trying to figure it out.

**Note**: Right now the user is downloading CSV's from Drupal 7, an install of Moodle 1.9 in a Drupal 6 Shell and Survey Monkey. After they download and combine using Excel, the user creates reports that way for the users we have come to our events. Being a Front-end developer, coding is not my strength.

# Answer
Maybe you want to consider the Forena module (disclosure: I'm a co-maintainer of it) ... Here is a quote from that page:

> ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.
>
> It is designed to leverage existing knowledge of HTML, CSS, SQL and JavaScript to help you create rich interactive web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

> Reports created by Forena (combined with SVGGraph and mPDF) can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are **CSV**, XLS, DOC, HTML, etc.

My answer to "How to retrieve data directly from a Drupal database" contains like a 1 minute summary to explain the typical (about 3) steps for creating:

* a **connection** to an external database (typically by an admin).
* a custom **SQL query** (typically by an admin).
* a custom **report** (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).

These steps (without any PHP coding involved ...) are like the equivalent to writing the PHP coding as included in the question there.

For an **online demo** (prior to installing/testing Forena), refer to these links:
> 1 votes

# Answer
You might want to take a look at Views Rules. It's just for Drupal 7, but it should allow you to integrate your view with rules.

Views Bulk Operations might be another option, it can also work with rules, but might be have a bit of a learning curve to get it set up.
> 1 votes

---
Tags: 7, views
---


title: User unregistration

text:
# Question
Title: User unregistration
I'm looking for the most Drupal way to allow registered users to request unregistration.

The website would provide a form to request the unregistration from the site, and the administration would then confirm the unregistration.

Is there a module that provides this functionality?

# Answer
There is a "Cancel own user account" permission in `admin/people/permissions`. If you assign it to your authenticated users, they will see a "Cancel account" link in their user profile ("Edit" tab). Would it be enough for your needs?

Additionally, you can configure the way the account is cancelled, in `admin/config/people/accounts`, in the "When cancelling a user account" section.

Hope that helps,
> 3 votes

# Answer
You could use the Webform module to create a form that sends an email to admin users with a link to cancel the account. In the email that is sent, you would just have to use the token for the Current User ID and create a link to cancel the account (yourwebsite.com/user/xxx/cancel) where xxx = their User ID.

The admin would just have to click the link in the email and follow through with the steps to cancel/deactivate the account.
> 0 votes

---
Tags: users
---


# Question
Title: Is it possible to set a single member of a complex-variable inside the variable table
I want to use Drush vset to modify a subset of values stored in the 'variable' table's theme\_themeName\_settings record.

I've found references to vget and vset but all I've found so far is for the entire complex-variable.

Any help would be appreciated.

# Answer
Drush does not support modifying elements inside a complex variable directly. You could instead use php-eval to do this:

```
$ drush php-eval '$v = variable_get("theme_themeName_settings"); $v["key"] = "value"; variable_set("theme_themeName_settings", $v);'

```
> 1 votes

---
Tags: drush
---


# Question
Title: Is there a way to determine what is powering the content behind a URL?
I have a relative URL in a large site that I inherited: `/my-url`.

For the life of me I can't find the View, Module, or other content that shows how to edit this URL. I've grepped the code base, and searched the database, but can't find it.

How can I tell how this URL gets edited? Is there some kind of search modules/views/blocks by URL?

# Answer
> 1 votes
You could try looking in the `menu_router` table, where the `path` column contains values like `node/%/revisions/view`. Also, the `url_alias` table has a `source` column (to check against the `menu_router` table) and the alias defining a path like `/my-url`.

I also use TextWrangler and PHPStorm to inspect my code. You could try to search.

# Answer
> 1 votes
You can try Devel and the Devel Themer module to check template file possibilities.

Check your themes /templates folder and template.php for modifications.

A lot of themes apply the nid or tid as a css class to the body or elsewhere in the form of `node-123` or `taxonomy-term-123` etc. You can check for this and try visiting `/node/123/edit` for example.

Another possibility is that it is coming from a custom module, so check the module list for any module that could be custom.

# Answer
> 0 votes
You might want to check your aliases. To do this, go to yoursite/admin/config/search/path/list, where you can filter for a url (like my-url). If it comes up, it will tell you content item it is aliasing, and you can edit it from there.

If your using ctools, you might also want to check to see if it's being controlled by the page manager. If page manager is enabled, then you can look at admin/structure/pages to see if any of those match the offending url. I suspect this is the most likely culprit, as it wouldn't show up in the url\_alias table of the db, as those paths are stored in page\_manager\_paths.

# Answer
> 0 votes
Last and least an easy and crude method. Just dump your database using mysqldump into a file and grep this URL. Locate the table then locate the module.

---
Tags: 7, search, uri
---


# Question
Title: Warning: unlink() expects parameter 2 to be resource, string given in drupal_unlink() (line 2194 of /includes/file.inc)
I'm using `drupal_unlink()` for deleting my files, but don't know why I'm keep on getting this error repetitively?

`Warning: unlink() expects parameter 2 to be resource, string given in drupal_unlink() (line 2194 of /includes/file.inc).`

```
<?php
$query = db_select('temp_container_mapping', 'c');
$query->innerJoin('temp_image_holder', 'i', 'i.nid = c.nid');
$query->fields('c', array('cid', 'nid', 'container', 'users_list', 'api_key', 'regions', 'abbreviative'));
$query->fields('i', array('id', 'nid', 'image_path', 'image_style', 'final_image_name_path'));
$query->condition('i.image_style', $param_image_style, '=');
$query->range(0, 10);
$entries = $query->execute()->fetchAll(PDO::FETCH_ASSOC);

if (!empty($entries)) {
  foreach($entries as $value) {

    $container_id = $value['cid'];
    $nid = $value['nid'];
    $id = $value['id'];
    $image_path = $value['image_path'];
    $image_style = $value['image_style'];
    $final_image_name_path = $value['final_image_name_path'];
    $container = $value['container'];
    $users_list = $value['users_list'];
    $api_key = $value['api_key'];
    $regions = $value['regions'];
    $abbreviative = $value['abbreviative'];

    //Establish Connection with server
    $client = new Rackspace(Rackspace::US_IDENTITY_ENDPOINT, array('username'=>$users_list, 'apiKey'=>$api_key));

    $service = $client->objectStoreService('cloudFiles', $abbreviative);
    $container = $service->getContainer($container);

    $temp_arr = explode("/", $final_image_name_path);
    $end_element = end($temp_arr);

    try {
      $file = $container->getObject($end_element);
      $fileExists = true;
    } catch (Exception $e) {
      $fileExists = false;
    }

    if ($image_style == "245") {
      $image_style_w = "168";
    } else {
      $image_style_w = $image_style;
    }

    $style = $image_style_w."w_".$image_style."h";
    $display_style[$image_style] = image_style_load($style);
    image_style_create_derivative($display_style[$image_style], $image_path, str_replace("rcf:///", "public:///rackspace/", $final_image_name_path));

    if ($fileExists) {
      //File is ther needs to overwrite
      $file->setContent(fopen('sites/default/files/rackspace/'.$end_element, 'r+'));
      $file->update();
      print 'existing overwrite<br>';
    } else {
      //New file just to upload
      $container->uploadObject($end_element, fopen('sites/default/files/rackspace/'.$end_element, 'r+'), array());
      print 'new one<br>';
    }

    drupal_unlink("public:///rackspace/", $final_image_name_path);
  }
}
?>

```

# Answer
probably a typo ',' -\> '.' drupal\_unlink("public:///rackspace/" . $final\_image\_name\_path);
> 2 votes

---
Tags: media
---


# Question
Title: Drupal 7 Ckeditor cannot edit profiles (picture added)
Recently I must have done something that changed something with my ckeditor. I can no longer edit my profiles. The strange thing is that I have multisite setup and only 3 sites are affected. The 3 sites have a different theme, looked everywhere there but I cannot seem to find it. Normally you see drop-down (clickable) buttons and then you can edit the options. This is what I have now:

Anyone have an idea of what I might have done wrong? The picture shows just plan text instead of buttons... I'm useing Omega 3.

# Answer
> 1 votes
Broken unclickable fieldsets are almost always a symptom of JS not being run to build the links & click events to trigger expansion.

If the JS console is reporting errors, try to disable JS caching/aggregation, if possible, and look for offending JS errors that would stop execution. That should give you a good idea where it's coming from.

Most likely, the 3 affected sites have a similar configuration that is injecting JS which breaks further JS execution. Look for similar modules across the 3 sites. Good places to look are any custom modules, JQuery update (is it overriding the default jQuery from Drupal core?), custom blocks with JS, or any modules designed to inject ad-hoc JS snippets (I've come across sites using JS snippets despite its alpha status).

---
Tags: 7, wysiwyg
---


# Question
Title: How do I hide a field from a Profile2 form without deleting it?
I have a field in a Profile2 form. I'm trying to streamline the signup process and not ask for users' phone numbers. However, I don't want to delete the phone numbers of users who have already inputted the field, so I don't want to delete the field.

How do I hide the field from the form, without deleting it, and having the ability to unhide it if I decide to do that later (or ask for the information at a later time, after initial signup)?

# Answer
You could do it using the Field Permissions Module, and set it to admin only. It can easily be changed later to allow everyone to see the field.

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.
> 0 votes

---
Tags: entities, users
---


title: what is the hook to preprocess a view?

text:
# Question
Title: what is the hook to preprocess a view?
What or is there a hook that you can utilize right before rendering results to the php template?

Also, is this means of altering view results bad practice? I'm trying to avoid using the views php field.

# Answer
> 12 votes
You can use something along the lines of this:

```
MYMODULE_views_pre_render(&$view) {

  if ($view->name=='NAMEOFTHEVIEW') {

    foreach($view->result as $r => $result) {
      // do whatever you want with each "row"
    }

  }

  // other views might go here

}

```

and this is certainly NOT a bad practice at all, and, at least IMHO, far superior to php fields in the view itself.

# Answer
> 11 votes
So by design, every single theme hook defined by `hook_theme` will have a preprocess function called for it. The trick with Views is knowing what all of those actually are.

To get the definition of every Views theme hook available for your current site, you'll need drush, but you can do the following:

```
drush @alias php-eval "var_dump(array_keys(views_theme()));"

```

That will spit back every theme hook defined for Views on the current site. For me it returned the following:

```
array(35) {
  [0] =>
  string(16) "views_mini_pager"
  [1] =>
  string(16) "views_view_field"
  [2] =>
  string(19) "views_view_grouping"
  [3] =>
  string(10) "views_view"
  [4] =>
  string(22) "views_view_unformatted"
  [5] =>
  string(17) "views_data_export"
  [6] =>
  string(28) "views_data_export_csv_header"
  [7] =>
  string(26) "views_data_export_csv_body"
  [8] =>
  string(28) "views_data_export_csv_footer"
  [9] =>
  string(28) "views_data_export_doc_header"
  [10] =>
  string(26) "views_data_export_doc_body"
  [11] =>
  string(28) "views_data_export_doc_footer"
  [12] =>
  string(28) "views_data_export_txt_header"
  [13] =>
  string(26) "views_data_export_txt_body"
  [14] =>
  string(28) "views_data_export_txt_footer"
  [15] =>
  string(28) "views_data_export_xls_header"
  [16] =>
  string(26) "views_data_export_xls_body"
  [17] =>
  string(28) "views_data_export_xls_footer"
  [18] =>
  string(28) "views_data_export_xml_header"
  [19] =>
  string(26) "views_data_export_xml_body"
  [20] =>
  string(28) "views_data_export_xml_footer"
  [21] =>
  string(14) "views_view_raw"
  [22] =>
  string(15) "views_view_list"
  [23] =>
  string(15) "views_view_grid"
  [24] =>
  string(16) "views_view_table"
  [25] =>
  string(18) "views_view_summary"
  [26] =>
  string(30) "views_view_summary_unformatted"
  [27] =>
  string(14) "views_view_rss"
  [28] =>
  string(28) "views_view_summary_jump_menu"
  [29] =>
  string(20) "views_view_jump_menu"
  [30] =>
  string(17) "views_view_fields"
  [31] =>
  string(18) "views_view_row_rss"
  [32] =>
  string(21) "views_form_views_form"
  [33] =>
  string(18) "views_exposed_form"
  [34] =>
  string(10) "views_more"
}

```

So, in my case, I needed to add some additional row data to views\_data\_export\_xml\_body. So I defined the following in my module:

```
function my_module_preprocess_views_data_export_xml_body(&$vars) {
  $vars['themed_rows'][0]['item_1'] = 'whatever';
}

```

It's not a very practical example but it does demonstrate how to discover, identify, and implement a preprocess function for any Views theme hook. Hope this helps.

# Answer
> 7 votes
I like this page : The life of a view

> Views is an amazing module not only because of its UI for query generating but also as it provides comprehensive hooks.
>
> Sometimes these hooks confuse beginners with their sequence.
>
> Here is the processing sequence of these hooks for your convenience.

# Answer
> 4 votes
It depends on what you want to do. Fortunately, all of the views functions are now in the Drupal API Reference.

There are two groups that you want to look at. There are the views hooks. These are used to mess with the `$view` object at various points in the view construction process. The documentation isn't that great. You can sometimes guess from the name about what you can do, but typically, you have to `dpm($view)`, see what is there and try stuff in different hooks. If you want to alter how a view works, use a hook.

Then there are the preprocess and process functions. Like the rest of Drupal, these match up one-to-one with the views template files. If you want to alter how a view is rendered, then use one of these.

I don't think altering view behavior with the hooks is a bad idea at all. I general, I try to avoid PHP code in UI config at all costs.

# Answer
> 1 votes
You're looking for hook\_views\_pre\_render(). All of the views hooks are defined in views.api.php, and are worth a read-through if you plan on altering anything in the view query-building and/or rendering process.

Gregory's answer also has a good link that outlines the order of hook calls.

Make sure, though, that whatever you need to do really needs to be handled through a hook—with Views 3.x, most of what I've ever needed to do, markup-wise, is easily achievable through the Views UI.

---
Tags: views
---


# Question
Title: Allow all users with a certain role to set Groups Audience to any Organic Group
I am using Drupal 7. What I am trying to achieve is the following: I have several users with a particular role say "A". And I have several content types set as "Group content" When a user with role "A" creates content I would like the user to be able to set the Groups Audience field to any of the existing Organic Groups.

Is it possible to achieve without adding those users as Administrators to all existing Organic Groups?

# Answer
I was able to achieve the above requirement using OG Role Override module. From Global Permissions for role "A" we would set: "Act as role 'member' in OG Node Group Main Page groups"

Hope this helps!
> 0 votes

---
Tags: 7, users, organic-groups
---


# Question
Title: Message "No pending update" after update.php (update module)
Today I updated the security update for the "views".

I always follow the steps for updating a module or core:

1) put site in maintenance mode 2) FTP the files 3) go to link site/update.php

But sometimes i get the message "no pending updates"... after step 3...

When I googled this I read something about some updates don't require a update of the Database.

So, ... If I see this message can i leave step 3 when i update my next site? I think so, but i prefer a conformation of a Drupal expert ;-)

Thanks for reading and all the info you will leave behind here :-) Kristof

# Answer
The "no pending updates" message means that there are no DB updates to be run. At that point, you are safe to go on with your normal process, which may include a few more steps:

1. If you use features, check to see if they have been overridden.
2. Clear caches.
3. Take your site out of maintenance mode.
> 1 votes

# Answer
It depends on the update if you need to run update.php. Personally, if I know a update doesn't contain a db update, I won't run update.php.

That being said, if your unsure if a db update is necessary, you might wanna run it just to be sure.
> 0 votes

---
Tags: database, updating
---


title: How to apply patches?

text:
# Question
Title: How to apply patches?
I have installed Drupal 7 in FTP server. I am trying to apply a Drupal patch.

I did see many links online but no one shows how to do it while Drupal is in FTP server of the hosting account. I think there are many ways I can do it. One way would be to get the Net Beans. I am not sure whether I need to install Net Beans in FTP server first or install to my local machine.

If you could provide some details for beginner, it would be helpful.

# Answer
If you're on UNIX based system (e.g. MacOSX, various Linux distros), the `patch` utility is a great tool here. I typically use the command:

```
patch -p1 < patch-file.patch

```

With the `-p1` option being important for installs already under a git repo.

It sounds like your use case is a bit different though. drupal.org has a good documentation page for applying patches in various environments.
> 7 votes

# Answer
There is a perfect tutorial in Applying patches with Git. There is also a simpler way to do this manually. as an example This patch fixes Ctools error. This is the code

```
diff --git a/includes/css-cache.inc b/includes/css-cache.inc
index d88160b..607b886 100644
--- a/includes/css-cache.inc
+++ b/includes/css-cache.inc
@@ -10,6 +10,12 @@ class CToolsCssCache implements DrupalCacheInterface {
   /**
    * {@inheritdoc}
    */
+  function __construct($bin) {
+  }
+
+  /**
+   * {@inheritdoc}
+   */
 public function clear($cid = NULL, $wildcard = FALSE) {
 // Only clear the caches if the wildcard is set, this ensures that the cache
 // is only cleared when the full caches are cleared manually (eg by invoking

```

the `/includes/css-cache.inc` determines the file that needs to be modified. the `+` sign is the code that should be added and the `-` sign means the codes that need to be removed (there is non in here). so as a result in this patch, you need to look for  `public function clear($cid = NULL, $wildcard = FALSE) {` statement and insert the

```
 function __construct($bin) {
 }

```

above it. clearly this line is in `class CToolsCssCache implements DrupalCacheInterface` class.

If there is any difficulty for you to install the patch, just modify the files as I said and check if the error has gone.
> 3 votes

# Answer
Apply the patch on your local machine using the excellent documentation mentioned above, then FTP the changed files up.

I really hope you are using some sort of versioning system somewhere during all of this. Frankly, I wouldn't accept a server setup where I was still using FTP to move around code files.
> 2 votes

# Answer
Yet another approach is to use the Patch Manager module. Here is an excerpt from its project page:

> ... provides a developer tool for managing patches to core and contributed modules.

As a variation, here are other options to consider (mentioned on the same project page also): Possibly better solution is to use Drush to apply patches (see its make command) or Drush extension Drush Issue Queue Commands because they don't rely on insecure configuration.
> 1 votes

---
Tags: 7, version-control
---