# Question
Title: Exposed form for contextual filters when using non-taxonomy filters?
I have a View with some contextual filters which works great. I also need to provide my users with some way to change the filters once they're on the page.

I've tried using exposed filters but I'd rather use path arguments over query string parameters and there is the conflicting issue between exposed filters and contextual filters which the Views Filter Harmonizer module address but in my case this doesn't work as **I'm using some non-taxonomy filters**.

So basically what I'd like to do is have a form which allows users to select values which could be passed as contextual filters.

Any help/guidance?

# Answer
To find "*... some way to change the filters once they're on the page ...*" (as in your question), it may help if you take a look at the (free) video about Contextual filters with paths. It covers these topics:

* Using contextual filters for filtering Views result.
* Using input from the view path to set contextual filter values.
* Using contextual filter values for changing the view title.

You may also want to watch some (or all?) of these related videos, also about contextual filters, sometimes called "arguments" also (quotes are from the links mentioned):

1. Action if no contextual filter value is present, with these topics:

> * Different views behaviours if no contextual filter value is present.
>     * Some words about why 'provide default value' is a bad concept.
>     * The provide summary option.
2. Contextual filters and menu tabs, with these topics:

> * Using contextual filter values inside a path (instead of at the end of it).
>     * Re-using existing site paths to get contextual filter values.
>     * Creating menu tabs in Views.
>     * Creating a menu tab on user pages, to display all articles created by the user.
3. Default menu tabs, with these topics:

> * How to use the default menu items in Views.
>     * How to create sub tabs.
>     * How to use default menu items together with contextual filters in the path.
4. Validation of contextual filter input, with these topics:

> * How to validate input for contextual filters.
>     * Some options for how to validate the input.
>     * Why it is a good idea to validate contextual filter input.
>     * Views behaviour if the filter input doesn't validate.
>     * Some words about not being able to validate contextual filter input with multiple values.
>     * Perhaps some words on filter validation being able to alter the filter value.
5. Contextual filters and default values, with these topics:

> * What default contextual filter values are.
>     * How to set default contextual filter values.
>     * Some examples of extra settings for default contextual filter value.
>     * Some words about why it is a bad idea to let the view make assumption about the context where it is embedded.
>     * Some more words about why it is a bad idea to let the view make assumption about the context where it is embedded.
>     * Some words about using default contextual filter values when creating Views blocks.
> 0 votes

---
Tags: views
---


# Question
Title: How to find which templates are affecting a display?
spending hours dealing with form\_alter , finally realized that a tpl.php file is overriding the output !!!

now the question is

> what are the ways to understand which template files(or functions) are affecting a display so they can be customized ?

# Answer
> 2 votes
They're called *theme suggestions*. Devel themer module shows all the suggestions in order, including tpl and theme functions, and which one was used, within the rendered page.

Note. It does this by modifying the DOM so it's good to switch it on when you need it then turn it off.

https://www.drupal.org/project/devel\_themer

You'll also need the Devel module and simpledom API.

You can read more about the priority of suggestions here. https://www.drupal.org/node/1089656

As @Gulok mentions, as of Drupal 7.33 you can enable theme debugging in your settings file which puts the theme suggestions in to your HTML as comments. Just add `$conf["theme_debug"] = TRUE;` in your settings.php. Read more about that here https://www.drupal.org/node/223440#theme-debug

You can also get the theme suggestions in code and modify them, injecting your own suggestions, or completely replacing theme.

Get theme suggestions: https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme\_get\_suggestions/7

# Answer
> 4 votes
First, you can easily debug everything with `Devel` module. Another trick that I use to inspect what `tpl` is generating a particular element is by adding `$conf['theme_debug'] = TRUE;` in `settings.php`. After adding that refresh your page (or clear your cache first) then use inspect element. The `tpl` should be visible now in the `HTML source`. See the screenshot below.

Here is a blog that describe on how to theme a field.

Hoe that helps.

# Answer
> 0 votes
rename the templates, or make backup and delete the file or part of the code (functions). Then refresh your page to see what gets affected.

---
Tags: theming
---


# Question
Title: <div> added in views header section is automatically closed: How do I avoid it?
I have added a div in views header (Custom text) section like this

```
 <div class="something">

```

This div's closing tag is added in views footer section. There are some rows in field section as well. The Display output: template is as below

```
<?php
  print $header;
  print $rows;
  print $footer;
 ?>

```

So I am expecting the the result as

```
<div class="something">  /* header*/
    <div>row1</div>      /* In fields */
    <div>row2</div>      /* In fields */
 </div>                  /* In Footer*/

```

But what I am getting is

```
 <div class="something"></div>
       <div>row1</div>
       <div>row2</div>

```

The div in header is automatically closed by drupal 7. How can i avoid that

# Answer
**Method 1: Unfiltered text**

When setting up the header and footer in your view, select *Global: Unfiltered text*. For the header enter `<div class="something">` and for the footer type in `</div>`.

If you then override the default views-view.tpl.php, stripping out everything except

```
<?php print $header; ?>
<?php print $rows; ?>
<?php print $footer; ?>

```

... you should achieve output similar to:

```
<div class="something">
  <div class="views-row views-row-1"></div>
  <div class="views-row views-row-2"></div>
</div>

```

**Method 2: Use attachments**

This might be ideal if editing the header and footer through the Views UI isn't important, but you want some flexibility in the output that wraps around your rows; for example, if you wanted it to be dynamic.

Override the default views-view.tpl.php so that it looks like this:

```
<?php print $attachment_before; ?>
<?php print $rows; ?>
<?php print $attachment_after; ?>

```

In a custom module you would then implement *hook\_views\_pre\_render()*:

```
function MODULENAME_views_pre_render(&$view) {
  $header_str = '<div class="something">';
  $footer_str = '</div>';

  if ($view->name == 'your_view_name' && $view->current_display == 'your_display_name') {
    $view->attachment_before = $header_str;
    $view->attachment_after = $footer_str;
  }
}

```

(Remember to clear the cache after adding the function.)

**Method 3: Simple template override** (simplest but least flexible)

Override the default views-view.tpl.php and simply replace all of the mark-up with

```
<div class="something">
<?php print $rows; ?>
</div>

```

Hope that helps!

A couple of links that might be useful:
> 5 votes

# Answer
One can also use row classes. These can be set on every views row and will wrap all fields inside then.

This is available under the settings link next to the formatting options.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Using Node Limit, Show Role How Many Nodes They Can Still Add
Using Node Limit and have limited roles to be able to add 3, 8 or 20 nodes of one content type depending on what they register with.

I wondered if it's possible to show how many of their limit they have left and then show it on their user page.

So if they have created 3 nodes, they have 5 left (if they had the 8 role allowance).

# Answer
I checked the `node_limit` module and you need to create an `api` to be able to get the remaining limit for a particular `role` or `user`.

1. The number of limit and `limit id` are stored on `node_limit` table.
2. Your `limit id` and `role id` are stored on `node_limit_role` table.

What you need to do next is count the number of nodes the `role` or `user` has created.

Now you need to alter the user profile to print the remaining limit. See the api that you can use here.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: how to provide security to user Profile?
I want to provide security to user profile, so that purpose am adding two check boxes

**Account Settings**

* List item Make my profile only visible to members of my website members only.
* Make my profile private

above two options are check box but how can i apply the functionality to this check boxes otherwise

please suggest me to any module are available

# Answer
> 1 votes
Using profile2 module you can create private profile. This module provides the following items :

> * With profile2 user account settings and user profiles are conceptually different things, e.g. with the "Profile pages" module enabled users get two separate menu links "My account" and "My profile".
> * Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)
> * Profile2 supports private profile fields, which are only shown to the user owning the profile and to administrators.

---
Tags: users, security
---


# Question
Title: Which statistics like page visitors or most visited pages are tracked automatically, or do I need extra modules for that?
I'm using Drupal 7.22. In this version are there any "default" or *simple site statistics* that are tracked automatically? I am looking for the following statistics:

* Page visitors
* Most visited pages
* Most clicks

Do I have to install a module to get statistics?

# Answer
> 5 votes
Everything in Drupal is provided by a module (core, contrib or custom), so one way or another you'll need to enable one to get extra functionality.

Drupal core comes with a Statistics module, you can enable that and see if it has what you want easily. If not, just search around for the different statistics modules there are out there, and install and try them.

If you stick to stable releases, you shouldn't have any trouble removing a module that you find doesn't do what you need, so there's no downside to trying.

# Answer
> 2 votes
Try the Google Analytics Module

> Adds the Google Analytics web statistics tracking system to your website.
>
> The module allows you to add the following statistics features to your site:
>
> * Single/multi/cross domain tracking
> * Selectively track/exclude certain users, roles and pages
> * Monitor what type of links are tracked (downloads, outgoing and mailto)
> * Monitor what files are downloaded from your pages
> * Custom variables support with tokens
> * Custom code snippets
> * Site Search support
> * AdSense support
> * Demographics and Interests support (formerly known as DoubleClick remarketing support)
> * Anonymize visitors IP address
> * DoNotTrack support (non-cached content only)
> * Drupal messages tracking
> * Modal dialog tracking (Colorbox)
> * Access denied (403) and Page not found (404) tracking
> * Cache the Google Analytics code on your local server for improved page loading times
> * Enhanced Link Attribution support
> * UA: User ID tracking across devices
> * UA: Dimensions and metrics support
> * UA: Changing URL fragments can be tracked as pageviews
> * UA: Debug mode with analytics\_debug.js

You'll need a Google Analytics account, but you can Google that.

# Answer
> 2 votes
Apart from the Visitors **(\*)** and Counter modules (already mentioned in another answer), here are some other modules that might be a possible fit (quotes are from their project pages):

* Statistics Advanced **(\*)**.

> Provides a few advanced options to the core Statistics module. Once enabled, these options can be found under "Administer \>\> Reports \>\> Access log settings."
* User Visits (with related User Visits Advanced).

> ... tracks visits and referrer from other users on a user's profile page. It displays the latest visitors on a user's profile page and provides two blocks one with the latest visitors on a user's profile page and one with the latest visitors on own profile page.
>
> See User Visits Advanced for additional functionality.
* Better Statistics.

> ... introduces a Statistics API, allowing developers and contributed modules a way to collect, limit, and route custom access statistics and data.
* Node view count.

> ... allows to count node views. Unlike statistics module, this module records each view of node with user uid and timestamp. So now you can know how many times a user viewed node by day, week, month and etc.
>
> This module is integrated with Views module. You can use it to create different statistics pages, output new not viewed nodes for user and many more.

Disclosure: I'm the maintainer of the modules marked with **(\*)**.

# Answer
> 1 votes
You mentioned in comments that you need simple stats statistics like page visitors, most visited pages, most clicks So check out these modules.

Visitors

> This module used for displaying a visitors info.

Counter

> Counter module counts how many visitors on your website. This module provides real time counting. All data saved to database.

# Answer
> 0 votes
If your question is *Do I have to install a module to get statistics?*, the answer is no. If you have a Google account, you can simply copy and paste a Google Analytics code snippet into your theme's html.tpl.php.

However the Google Analytics module is generally the preferred option since it provides robust configuration options for site administrators via the administration UI.

More information on overriding template files can be found here:

---
Tags: 7, nodes
---


title: Blocks is not showing up

text:
# Question
Title: Blocks is not showing up
I am facing trouble while configuring a block. The block I configure is not showing up onmy website. I am using drupal 7 and the Touch theme. Here are the steps I do:
\- in REGION SETTINGS i have selected "Highlighted"
\- Visibility settings is:
\- pages (Only the listed pages) \[http://example.com/news\]
\- Content types
\- Show block for specific content types\> \[Publish A News\]
\- Roles
\- I have made no changes here
\- Users have not been set
Any ideas why the block is not showing up?

# Answer
> 1 votes
You need to specify your node name. for example: you want to display your block on www.yoursitename/news page. Then you need to specify only **news** in that box. Hope this will work.

# Answer
> 0 votes
I know this is old but use node/11 - or what ever the node is of that page.

# Answer
> 0 votes
You need to specify the pages that block want to show in "pages (Only the listed pages" without any quote or using absolute path. for example: you want to display your block on `www.yoursitename.com/news` page just need enter `news` in that box without any quote and absolute URL.

---
Tags: 7, blocks
---


# Question
Title: Views PHP: Getting "Available Variables"
I am using Views PHP and having problem in doing a very basic thing.

In my view I added a field which I have to "Exclude from display" and show it only when there is a specific content type being called on Page.

So I used `Views PHP`, which checks the content type. The only problem is that I don't know how to output this field.

I used

```
$row -> myfield_name;

```

but that doesn't work.

So basically, I just need to use "Available Variables". But the `$row->myfield_name` doesn't work.

I can't use the following as this gives raw field. I only want to use how this is intercepted in my view and how my view shows it. This is because this field is a video and my view is formatting it with JWplayer and hence calling it will call it as JWPlayer.

```
$value-> _field_data["body"] ["entity"] -> myfield_name ["und"][0]["value"];

```

Thanks

# Answer
The variables (or field) that you need to use as *Available Variables* must be **before** the *Views PHP* variable. Besides that install Devel module and use `kpr($row)` or `kpr($view)` or `kpr($data)` to get the available properties of these variables.
Also in "Output" section you can use `var_dump` or `print_r` to print available variables.
> 3 votes

---
Tags: views
---


# Question
Title: Only show field type content added by user
On my website I allow companies to add jobs, I allow a user to create one or more companies. When the user goes to add a job I have a drop down which lists all of the companies on the site, I want this drop down to only list the companies added by the user so they can choose which company they want to attach to the job. I can't find a way to do this via the manage fields screen. Below is a screenshot of my manage fields screen. Any help would be much appreciated!

# Answer
I suggest you use views entity reference this link is good tutorial about it .

So first create a views that show the current user company items ( the companies that the author (creator) of them is current user) then add "Entity reference" display to it , then in your field settings in "Entity Selection" instead simple mode use "Views :Filter by entity reference" Then select your created views entity reference then enjoy it ;)
> 0 votes

# Answer
From what I understand you need to filter content created by current user. To do so you need to create a View of what you want. Then in *Relationships* add

```
Content: Author

```

and in *Filter Criteria* add `User: Current` I mean this :

By doing this contents available in Views are filtered by the ones that current user has created them.
> 0 votes

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


# Question
Title: Google Store locator Store Phone and Store Web not visible
I am using Google Store locator module for my Drupal 7 website.

I have used version 7.x-1.1. But when I test my page the *Phone number* and *website* are not visible on the frontend?

If you can see there `http://litebook.eu/store-locator/json` in the browser you can see the data is added (*store phone* and *store web*).

Why are those fields not visible on the frontend?

Thanks

# Answer
There is a patch you can apply that should fix your issue.

Check out the thread here https://www.drupal.org/node/2383773 and the related thread here https://www.drupal.org/node/2528458

This one https://www.drupal.org/node/2528458#comment-10125006 will take you straight to grabbing the patch, the top two will give you the context of what happened.
> 0 votes

---
Tags: google-maps
---


title: View in a Colorbox

text:
# Question
Title: View in a Colorbox
Can I display a view page within a Colorbox popup ? ( in the same way as a node can be displayed with in a colorbox popup) If yes , then how?

# Answer
Put your view into a div with a wrapper that is hidden (ie, display:none;). Then you can use the following javascript:

```
$.colorbox({
    'inline' : true,
    'href' : $('.views-view-my-view'),
});

```

You must replace the 'href' attribute with the appropriate jQuery collection representing your view.

If you need some advice on placing a view on your page, here is a clean implementation:

```
function MODULE_preprocess_page(&$vars) {
  $vars['page']['bottom']['my_view'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'my-view-container',
    ),
    'children' => array(
      '#markup' => views_embed_view(...),
    ),
  );
}

```

In this case your selector for colorbox would be #my-view-container .view

**2. Using** Colorbox Node **Module :**

***Section One:Building views slideshow***

* Add a View
* Change format to "Slideshow"
* Add required fields.
* Change Path to: whatever/%
* click on Advanced link top right: add a "Contextual Filter" -\>Content:Nid -\>WHEN THE FILTER VALUE IS NOT IN THE URL Display all results for the specified field Provide default value: Content ID from URL
* format-\>slideshow-\>settings:at the end of settings activate Pager and Controls

**Section Two: setup play slideshow button**

* add another view: no pager, no path
* add a field: (this can be any field we want to rewrite the result so it doesn't matter that much for example add "node title")
* click on field important: disable Link this field to the original piece of content -\> REWRITE RESULTS:

+ Rewrite the output of this field -\> Play Slideshow
    + Output this field as a link -\>Link path: whatever/!1?width=500&height=500&iframe=true

***Note:*** !1 is for adding "node id" from URL to the link. width=500&height=500&iframe=true you can change the width an height numbers to change the size of colorbox frame.

Link class:colorbox-node

***Section Three: play the slideshow*** \- Click on play slideshow link in the page and you have your slideshow in a nice colorbox overlay.

**Notes:**

* you can add colorbox-load instead of colorbox-node to load the whole node in colorbox.
* Don't forget to Enable Colorbox load:admin-\>config-\>media-\>colorbox you can change the colorbox settings to styles-\>plain and theme your slideshow or View the way you like by CSS.

A little long but hope this helps someone :)
> 0 votes

# Answer
1. You can show a View Page in a color box. To do this, you have to enable colorbox and in View Format settings, you have to select Slideshow Format. It will show all the contents of your view in the slideshow.
2. You can also display a node page content in the color box slideshow. To do this, Follow these steps :

* Go to the settings of the field
    * Then go to `Rewrite Results` -\> `Rewrite the output of this field` and add this link to this : `<a class="colorbox-load" href="[path]?template=colorbox&width=700&height=700" >field_replacement_pattern</a>`
    * After that go to theme folder -\> templates and write a new file named `page--colorbox.tpl.php`
    * And the following code in it : `print render($page['content']);`
> 1 votes

---
Tags: views, javascript
---


title: How to remove markup from file field

text:
# Question
Title: How to remove markup from file field
I have added a file field in views and when displaying it has some markup like this

```
 <div id="file-218" class="file file-image file-image-jpeg
contextual-links-region">
<a href="#">

    </a>
       <h2 class="element-invisible">
  <a href="#"></a>
 <a href="/mdm.dev/file/218">6783c11f-0b05-49e3-a494-ca68d2e6c23b-2060x1366.jpeg</a></h2>
 <div class="contextual-links-wrapper contextual-links-processed">
<a class="contextual-links-trigger contextual-links-trigger-active" href="#">
Configure</a>
 <ul class="contextual-links">
 <li class="file-edit first">
  <a href="/mdm.dev/file/218/edit?destination=gallery-page">Edit</a> </li>
  <li class="file-delete last">
 <a href="/mdm.dev/file/218/delete?    destination=gallery-page">Delete</a></li>
 </ul></div>

<div class="content">
<img typeof="foaf:Image"
src="http://10.200.1.10/mdm.dev/sites/default/files/
  styles/w206xh154/public/6783c11f-0b05-49e3-a494-ca68d2e6c23b-2060x1366.jpeg?itok=bk_SdoJ3" alt="">
</div>

 </div>

```

While all I need is

```
<img typeof="foaf:Image" src="http://10.200.1.10/mdm.dev/sites/default/files/
  styles/w206xh154/public/6783c11f-0b05-49e3-a494-ca68d2e6c23b-2060x1366.jpeg?itok=bk_SdoJ3" alt="">

```

How can I remove this markup. Can I use views-view-field-field\_name.tpl.php. Only line this file contains is print $output. How can i use this file to remove markup. Or does any preprocess hook helps

# Answer
> 0 votes
You can use theme layer to override the views output , if you want only theme a certain field you can use this template file :`views-view-field.tpl.php`

for more information check this tutorial : Theming a single field in a Views

# Answer
> 0 votes
You can use Semantic Views module, it is good module that can help you get rid of unwanted Drupal wrappers.

Here are some more details about this module(quotes from its page):

> This Views plugin makes unformatted styles, field row styles and other output more readily configurable without needing to override template files. Instead of overriding row style templates for views where you want to specify different HTML elements (tags) and class attributes, you can specify these inside the Views UI and avoid overriding templates for each view.
>
> Some of Semantics Views functionality can be done in Views, but Views is restricted to use only predefined HTML element and can only style each Field but not wrap rows with any HTML you like.

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


# Question
Title: Can I create a block that shows custom node types but in a specific order?
For example, I have custom block made with Views that shows some block icons that are links to modules.

I would like to rearrange them.

For example, I would like to say "Put node 3 first, then node 5, then node 1".

Thanks!

# Answer
You can use Node Queue module, it may solve your problem.

> The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:
>
> * A block listing teasers for the five top news stories on a site
> * A user’s favorite music albums
> * A group of favorite from which one is randomly displayed
>
> Nodequeue provides a simple drag-and-drop interface to manually order any queue. Additionally, it allows nodes to be added and removed from queues without needing edit permissions to the node. Nodes can be added to queues either from a queue management tab or by links on the node teaser.
> 1 votes

# Answer
If you are using views then DraggableViews is the module you are looking for , this is the description from its project page :

> DraggableViews makes rows of a view "draggable" which means that they can be rearranged by Drag'n'Drop.
>
> Have you ever rearranged Blocks?, sorted Taxonomy terms? or reordered Menu items at the Drupal administration pages? All these pages use the tabledrag.js javascript that enables Drag'n Drop on HTML-tables.
>
> With DraggableViews you can apply this tabledrag.js to any Views-generated table.
> 0 votes

# Answer
Node Queue module let you specified a cusomize order of sorting nodes,install `Nodequeue` module then got `admin/structure/nodequeue` create new nodequeue and name it as you want, then in the blow of it add nodes you want then reorder them with which sort you want.

(You can use nodequeue API to load them OR )Then in your views create a views that want add relation to `nodequeue` the in sorting section select "queue) Nodequeue: Position (asc)". and now you have a views with node that sorted by what order you want.

> The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:
>
> * A block listing teasers for the five top news stories on a site
> * A user’s favorite music albums
> * A group of favorite from which one is randomly displayed
>
> Nodequeue provides a simple drag-and-drop interface to manually order any queue. Additionally, it allows nodes to be added and removed from queues without needing edit permissions to the node. Nodes can be added to queues either from a queue management tab or by links on the node teaser.
> 0 votes

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


# Question
Title: How to handle a post request from an external application in Drupal?
I am integrating with the Stripe payment gateway and I need to be able to handle a post from their server to authenticate a standalone account. I am trying to follow the instructions at https://stripe.com/docs/connect/standalone-accounts

Namely, I need to provide a callback URL which will receive the data I need through request parameters.

https://mydrupalsite.com/callback?scope=read\_write&code=AUTHORIZATION\_CODE

I need to be able to get the scope and the code value.

Once I have that, I will need to then redirect based on their values to certain pages.

I tried creating a MENU\_CALLBACK type menu item with a page callback to handle the parameters, but what I tried didn't work. Below is the code I tried.

```
function bh_commerce_stripe_oauth_menu() {
  $items = array();
  $items['bh_commerce_stripe_oauth/callback/%'] = array(
        'title' => 'bh_commerce_stripe_oauth_callback',
        'page callback' => '_bh_commerce_stripe_oauth_handle_callback',
        'page arguments' => array(2),
        'type' => MENU_CALLBACK
  );
  return $items;
}

function _bh_commerce_stripe_oauth_handle_callback($post_parm_args) {
  drupal_set_message(t('_commerce_stripe_oauth_handle_callback: called'));
  drupal_goto('<front>');
}

```

# Answer
Your path is wrong I think. You should be able to access that callback here.

https://mydrupalsite.com/bh\_commerce\_stripe\_oauth/callback/randomstring

So actually your `hook_menu` should look like this.

```
/* Implements hook_menu */
function bh_commerce_stripe_oauth_menu() {
  $items = array();
  $items['callback'] = array(
    'title' => 'bh_commerce_stripe_oauth_callback',
    'page callback' => '_bh_commerce_stripe_oauth_handle_callback',
    'type' => MENU_CALLBACK
  );
  return $items;
}

```

Note: You don't have any path wildcards (represented by `%` in your array key) in the callback you are getting that are useful. Therefore you don't need any `page arguments`. The interesting things are in the `$_GET` (or `$_REQUEST`).

And then to access the results something like:

```
function _bh_commerce_stripe_oauth_handle_callback() {
  $scope = $_GET['scope'];
  $code = $_GET['code'];
  drupal_set_message(t('_commerce_stripe_oauth_handle_callback: called'));
  drupal_goto('<front>');
}

```
> 1 votes

---
Tags: routes
---


# Question
Title: Ordering results for form autocomplete fields
I've done the cursory googling, but so far I haven't found anything close to an answer for this.

I'm using the Masquerade module with a custom module on top to extend it and make its searching algorithms a bit more "clever" (Soundexes, custom fields and such), and it returns the results in a certain order, passed through to `drupal_json_output()`. However, because JSON isn't exactly indexed, it means that when the autocomplete text field picks it up, it's in a slightly screwy order based on its keys (which are the users' usernames). I can forcibly send a `array_values()` to the JSON output, but it breaks Masquerade's functionality as it requires the username to be the key. I'd imagine this would be a problem with other autocompletion stuff in Drupal that uses JSON loads.

Can anyone suggest a way of doing this please? I'm not sure whether it's a matter of Masquerade or of D7's textfield autocompletion.

Thanks

# Answer
> 0 votes
I would think its the query that handles the ordering. You can alter the query that fetches the results for the autocomplete field. Find the query in the module code and it should have a tag associated with it. You can then alter the query by implementing hook\_query\_TAG\_alter

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_query\_TAG\_alter/7

This will allow you to change the orderby for the query

EDIT: Looking at the masquerade module I don't think it adds tags to the queries which means you cant mess with the ordering.

# Answer
> 0 votes
I figured out a workaround. I used a unique string for the ID column of my entity table.

I don't think there is a way to have a numerical value as the index that gets used by drupal\_json\_output(), even if the data type for the column in the database is varchar.

---
Tags: 7, ajax
---


# Question
Title: Suggestions for settings.php - Local dev, Development server, Live server
Basically, one of the greatest questions of all time: What are some ways you're using settings.php in your development/staging workflow?

Right now, I have my settings.php file set up like the following, and I base my development on the server's $HOST directive—meaning I can work on dev.example.com for the development (shared) server, local.example.com for my local computer (and other dev's local code checkouts), and www.example.com (or just example.com) for the live site.

(This code is in the 'Database settings' section of settings.php):

```
$host = $_SERVER['HTTP_HOST'];
$base_url = 'http://'.$host;
$cookie_domain = $host;

switch($host) {
  case 'example.com': # Production server
    $db_url = 'mysqli://prod_sql_user:password@127.0.0.1/prod_db';
    $update_free_access = FALSE;
    $conf = array (
      // Set production config options here...
      'example_setting' => 0,
    );
    break;

  case 'dev.example.com': # Development server
    $db_url = 'mysqli://dev_sql_user:password@127.0.0.1/dev_db';
    $update_free_access = FALSE;
    $conf = array (
      // Set production config options here...
      'example_setting' => 0,
    );
    break;

  case 'local.example.com': # Local server
    $db_url = 'mysqli://local_sql_user:password@127.0.0.1/local_db';
    $update_free_access = FALSE;
    $conf = array (
      // Set production config options here...
      'example_setting' => 0,
      // Turn off most core caching.
      'cache_inc' => 'includes/cache.inc',
      'cache' => CACHE_DISABLED,
    );
    break;

}
?>

```

This works pretty well for most purposes, but it means we have a lot of extraneous code sitting around in our shared settings.php file... is there a better way?

# Answer
What I do is separating that file into a settings.php and a local.settings.php.

At the end of settings.php is the following code:

```
if (file_exists(dirname(__FILE__) . '/local.settings.php')) {
  include dirname(__FILE__) . '/local.settings.php';
}

```

The local file is then excluded from whatever VCS you are using. The advantage is that you can put settings which are common over all instances in settings.php and have that versioned/distributed automatically and keep the local stuff in local.settings.php.
> 66 votes

# Answer
This seems like you're reinventing Drupal's built in multisite functionality.

Personally, I keep all standard themes and modules for the site in `sites/all`, and then have `sites/dev.example.com` and `sites/example.com`.

As an added bonus you can then have different `files` folders for each site, and you can add any development modules to `sites/dev.example.com/modules` as well.
> 25 votes

# Answer
I prefer to ignore the file locally (using a `.gitignore` file in git) and then keep separate versions if the file on each host.
> 11 votes

# Answer
I tend to always set up DNS or host file entries and use

```
dev.example.com
staging.example.com

```

and

```
example.com

```

Then I have completely separate settings file directories with differing files directories. For instance ./sites/dev.example.com/files
> 6 votes

# Answer
Why not have a few folders based on the development host name?

Example

* sites/dev1.domain.com
* sites/dev2.domain.com
* sites/dev3.domain.com
* sites/www.domain.com

Each with their own settings file and db\_url.
> 5 votes

# Answer
If the only things changing are the database credentials, then you can set environment variables in your local (and staging/production) virtual host config or in a .htaccess a folder above your web root. Here's a simple example:

`/var/www/example.com/drupal-resides-here`

I can then create a .htaccess file here:

`/var/www/example.com/.htaccess`

which has the following code:

```
SetEnv DB1_USER my_local_user
SetEnv DB1_PASS my_local_pass
SetEnv DB1_HOST my_local_host
SetEnv DB1_NAME my_local_dbname

```

Then in `/var/www/example.com/drupal-resides-here/sites/default/settings.php` (or whatever) you can grab the db credentials like:

`$db_url = "mysql://{$_SERVER['DB1_USER']}:{$_SERVER['DB1_PASS']}@{$_SERVER['DB1_HOST']}:{$_SERVER['DB1_PORT']}/{$_SERVER['DB1_NAME']}";`

This lets multiple developers run things locally and you can push to staging / production while still tracking settings.php (there are more things in there than just the database credentials...). You also wouldn't have to keep track of multiple settings.php files.
> 2 votes

# Answer
Simplest and most efficient solution that is just one line is the following. Just include it in the last line of your settings.php file:

```
@include('settings.local.php');

```

The @ symbol in the front just means don't display any error even if it doesnt find that file. Typical setup's like this involve a conditional to check if the file is there. This accomplishes it in one line without it.

http://php.net/manual/en/language.operators.errorcontrol.php

Also known as the **STFU PHP operator**.
> 0 votes

---
Tags: workflows, configuration, staging
---


# Question
Title: Overriding permissions of existing page blocks all users
**Problem**

I'm trying to block access to Drupal's taxonomy pages for anonymous users.

I'm using the solution set out in this answer, but for Drupal 7 rather than 6.

I'm using `hook_menu_alter` and `hook_permission` to create a new access argument for taxonomy pages. The permission is successfully created, but no matter what roles I tick the pages remain blocked. Any ideas what I'm doing wrong?

**Example Code**

```
function custom_module_menu_alter(&$items) {
  $items['taxonomy/term/%']['access arguments'] = array('access taxonomy permission');
}

function custom_module_permission() {
  return array(
    'access taxonomy permission' => array(
        'title' => t('Access taxonomy pages'),
    )
  );
}

```

# Answer
Is there any special reason that you're using 'taxonomy/term/%' instead of 'taxonomy/term/%taxonomy\_term' in your implementation of `hook_menu_alter()`? If not, I would change that and clear the cache, see if it helps.

*Edit*...Here's a code example from the **Term Per Role** module:

```
function term_per_role_menu_alter(&$items) {
  $path = 'taxonomy/term/%taxonomy_term';
  if (isset($items[$path])) {
    $items[$path]['page arguments'] = array_merge($items[$path]['page arguments'], array($items[$path]['page callback']));
    $items[$path]['page callback'] = 'term_per_role_taxonomy_term_page';
  }
}

```

(A module which I would have recommended but the last commit on the project was over 3 years ago.)
> 0 votes

---
Tags: 7, taxonomy-terms, users
---


title: How to embed and render an entityform

text:
# Question
Title: How to embed and render an entityform
I have an entityform called 'foia\_generator' and I'm trying to embed it as a contact form on a page (the tutorial I used is for embedding entityforms in blocks) ... hence my problem...

```
function foiagen_form($form, &$form_state) {
    module_load_include('inc', 'entityform', 'entityform.admin');
    $entity_form_name = 'foia_generator';
    $render_estimate_form =
    entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
    echo drupal_render($render_estimate_form);
    return $form;
}

```

This displays the form but it's not 'inside' the normal bounds of the site (using bootstrap subtheme) i.e. it's not rendered properly - it appears before the regular divs like the navbar etc... and spans the entire width of my screen.

If I can't do it this way can I programattically embed the 'entityform' on my 'contact page' as an entityreference field, (rendered)?

Thanks

# Answer
> 2 votes
Here's a function I made to embed any entityform:

```
function my_module_entityform_form($form, &$form_state, $entityform_name) {
  form_load_include($form_state, 'inc', 'entityform', 'entityform.admin');
  $entityform = entityform_create(array('type' => $entityform_name));

  return entityform_edit_form($form, $form_state, $entityform, 'submit', 'embed');
}

```

And then you can call it using your specific entityform name as a Drupal form:

```
$form = drupal_get_form('my_module_entityform_form', 'entityform_name');

```

This is good because it uses form\_load\_include instead of module\_load\_include, so the validate and submit functions will also have access to entityform.admin.inc.

# Answer
> 2 votes
Seems like a odd piece of code you've got there, for instance this will render your form randomly in the page:

```
    echo drupal_render($render_estimate_form);

```

Which is probably what you're noticing already, that example you're linking is for render that piece of code inside a template but for what you describe you're rendering it in a form inside a block, I'd try something like this instead (untested):

```
function foiagen_form($form, &$form_state) {
    module_load_include('inc', 'entityform', 'entityform.admin');
    $entity_form_name = 'foia_generator';
    $render_estimate_form =
    entityform_form_wrapper(entityform_empty_load($entity_form_name), 'submit', 'embedded');
    $form['foiagen'] = $render_estimate_form;
    return $form;
}

```

---
Tags: entities
---


# Question
Title: Restore with backup & migrate module does not work with Acquia Dev Desktop
Having messed up my dev site (running on Win 7 using Acquia Dev Desktop), I restored a backup I took a few hours ago with the Backup & Migrate module. Now when I click the local site name in Acquia Dev Desktop I get a Choose Language message from Drupal instead of my site. I'm certain I had this problem a few months ago, but I apparently did not make good notes because I don't know where I found the instructions to fix this problem. My guess is that the $database parameters are wrong in settings.php or maybe there's some other problem.

Help is appreciated!

# Answer
> 0 votes
There could be many reasons for this not working for you but as long as you've got the database backup and a copy of your existing codebase, you should be fine. Fixing DevDesktop database issues is a little tricky but the easiest way is to just create a new instance with the correct settings. Quick steps to do this:

* We're going to be deleting the whole site instance using DevDesktop so you should make a backup of the folder and your database backup or at least move it outside of the DevDesktop folder.
* Now from the DevDesktop application, delete your site and then create another one with the same name, etc. This will create a new database and a new settings.php file that is connected to it.
* Finally, you'll want to copy your codebase back into this directory (making sure not to overwrite the settings.php or sites.php files that DevDesktop created) and then try the restore again using backup & migrate.

---
Tags: backups
---


# Question
Title: How do I create multiple nodes on the same page?
Im on d7. I am trying to create node submission process where I can create multiple nodes on the same submit page and have them all reference a single separate node on the site. any suggestions?

# Answer
You could create multiple nodes by creating node objects and using node\_save() function to save the node.

```
      $node = new stdClass();
      $node->nid = NULL;
      $node->nid = NULL;
      $node->is_new=TRUE;
      $node->type = "CONTENT_TYPE_NAME";

      node_object_prepare($node);

      $node->created = strtotime("now");
      $node->changed = strtotime("now");

      $node->uid = 1;
      $node->promote = 1;
      $node->format = 1;
      $node->language = 'en';
      $node->title = '"TITLE" ';

      $node->field_DATA['und'][0]['value']= "VALUE";
      $node->field_DATA['und'][0]['value']= "VALUE";

     // Prepare node for saving
      node_save($node);

```

you can create multiple objects like this on submit handler and save it. Each node will be assigned with new node id.

I hope this helps you.
> 1 votes

# Answer
Maybe field collection module is not a bad alternative, but it's not as perfect as node.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Unable to contact the Apache Solr server
I followed README.txt and installed these : apache solr 1.4.1 (Out side WWW Directory) Apache Solr Drupal modules SolrPHPClient r22 (placed inside module) I copied over xml files(as mentioned in readme) to example folder And after starting up SOLR as java -jar start.jar I am able to access localhost:8983/solr/admin, But still i get

```
Apache Solr: Your site was unable to contact the Apache Solr server.

```

I am using windows :(

# Answer
> 1 votes
Since you're able to connect to ApacheSolr I am keen to know if you set the credentials correctly on Drupal side. Make sure that you added the local server correctly here `admin/config/search/apachesolr/settings/add`. After that use the `Test connection` button to verify that you are able to contact the ApacheSolr server.

---
Tags: search
---


title: no changes in bg color

text:
# Question
Title: no changes in bg color
have inspected element for this site and try as I might changing bg color in body for style.css makes no difference no matter how much caches are cleared.

I want to leave the tiled background and just change the inset white to another color. I didn't see background color in LAYOUT REGION sorry..this has been solved now.

# Answer
> 2 votes
The reason why the color is not showing is because you have this already:

```
body {
    background: url(images/body.png) fixed;
}

```

from `my_elegant.css`.

You have a background image already set. If you want to use a css color then you need to tweak the css for body to something like this:

```
body {
  background-color: #000;
}

```

or you can have an image background and a color at the same time:

```
body {
  background: #fff url(images/body.png) no-repeat center top;
}

```

If you are using `style.css` make sure that the file is properly added otherwise it could result to `404` and all the css in that file will not get applied. You can use `drupal_add_css()` api to add new css file or in the `.info` of your theme.

# Answer
> 1 votes
It's not Drupal issue, it's a CSS issue; looks like your site doesn't load style.css but it using my\_elegant.css file"http://krom.club/sites/all/themes/my\_elegant/my\_elegant.css?nssjk2". Also you need to remove the background image and apply your desired background color

```
body {
background-image: none;
background-color: #FFF; /* yout color */
}

```

---
Tags: theming
---


# Question
Title: override date module function for label strings changes
I configured a exposed filter for a shipping date field on myview with operator "Is between". I saw two labels,"Start date" and "End date" in myview form. I wanna change these strings to "From Date: " and "To Date: ".

I have checked the file `sites/all/modules/date/date_views/includes/date_views_filter_handler_simple.inc` This file includes the

```
function date_parts_form()

```

that includes the codes:

```
$label = t('Start date');

```

and

```
$label = t('End date');

```

But I don't want to modify this file directly for further maintenance. I am not certain how to override this function with keeping an original module file. Please show me the way with circumstantial directory path and file name.

# Answer
> 1 votes
Now I use an Omega sub theme, mytheme. I added to a CSS file, mytheme-alpha-default.css, some styles such as the following:

```
label {display:none;}
div.some:before {content:"To Date: "; display:block; margin-left: 2.0em;}

```

# Answer
> 1 votes
You can override the handler used by the Date module using code similar to the following one.

### mymodule.module

```
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule') . '/includes',
  );
}

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'views_field_views_data_alter') {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

function mymodule_views_field_views_data_alter(&$result, $field, $module) {
  if ($module == 'date') {
    foreach ($result as $table => $data) {
      $additional = array();
      $field_name = $field['field_name'];
      foreach ($data as $column => $value) {
        // For filters, arguments, and sorts, determine if this column is for
        // the start date ('value') or the end date ('value2').
        $this_column = NULL;
        foreach (array_keys($field['columns']) as $candidate_column) {
          if ($column == $field['field_name'] . '_' . $candidate_column) {
            $this_column = $candidate_column;
            break;
          }
        }

        // Only alter the date fields, not timezone, rrule, offset, etc.
        if ($this_column != 'value' && $this_column != 'value2') {
          continue;
        }

        // Replace the handler used by the Date module.
        if (array_key_exists('filter', $value)) {
          $result[$table][$column]['filter']['handler'] = 'mymodule_filter_handler_simple';
        }
      }
    }
  }
}

```

### includes/mymodule\_filter\_handler\_simple.inc

```
class mymodule_filter_handler_simple extends date_views_filter_handler_simple {
  function date_parts_form($form_state, $prefix, $source, $which, $operator_values, $identifier, $relative_id) {
    module_load_include('inc', 'date_api', 'date_api_elements');
    switch ($prefix) {
      case 'min':
        $label = t('From date');
        $relative_label = t('Relative start date');
        break;
      case 'max':
        $label = t('To date');
        $relative_label = t('Relative end date');
        break;
      default:
        $label = '';
        $relative_label = t('Relative date');
        break;
    }

    $type = $this->options['form_type'];
    if ($type == 'date_popup' && !module_exists('date_popup')) {
      $type = 'date_text';
    }

    $format = $this->date_handler->views_formats($this->options['granularity'], 'sql');
    $granularity = array_keys($this->date_handler->date_parts($this->options['granularity']));
    $relative_value = ($prefix == 'max' ? $this->options['default_to_date'] : $this->options['default_date']);

    if (!empty($form_state['exposed'])) {
      // UI when the date selector is exposed.
      $default_date = $this->date_default_value($prefix);
      $id = 'edit-' . str_replace('_', '-', $this->field) . '-' . $prefix;
      $form[$prefix] = array(
        '#title' => check_plain($label),
        '#type' => $type,
        '#size' => 20,
        '#default_value' => !empty($this->value[$prefix]) ? $this->value[$prefix] : $default_date,
        '#date_format' => date_limit_format($format, $granularity),
        '#date_label_position' => 'within',
        '#date_year_range' => $this->options['year_range'],
        '#process' => array($type . '_element_process'),
        '#prefix' => '<div id="' . $id . '-wrapper"><div id="' . $id . '">',
        '#suffix' => '</div></div>',
      );
      if ($which == 'all') {
        $form[$prefix]['#pre_render'][] = 'ctools_dependent_pre_render';
        $form[$prefix]['#dependency'] = array($source => $operator_values);
      }
      if (!isset($form_state['input'][$identifier][$prefix])) {
        $form_state['input'][$identifier][$prefix] = $this->value[$prefix];
      }
    }
    else {
      // UI when the date selector is on the views configuration screen.
      $default_date = '';
      $id = 'edit-options-value-' . $prefix;
      $form[$prefix . '_group'] = array(
        '#type' => 'fieldset',
        '#attributes' => array('class' => array('date-views-filter-fieldset')),
      );
      $form[$prefix . '_group'][$prefix . '_choose_input_type'] = array(
        '#title' => check_plain($label),
        '#type' => 'select',
        '#options' => array('date' => t('Select a date'), 'relative' => ('Enter a relative date')),
        '#attributes' => array('class' => array($prefix . '-choose-input-type')),
        '#default_value' => !empty($relative_value) ? 'relative' : 'date',
      );
      $form[$prefix . '_group'][$prefix] = array(
        '#title' => t('Select a date'),
        '#type' => $type,
        '#size' => 20,
        '#default_value' => !empty($this->value[$prefix]) ? $this->value[$prefix] : $default_date,
        '#date_format' => date_limit_format($format, $granularity),
        '#date_label_position' => 'within',
        '#date_year_range' => $this->options['year_range'],
        '#process' => array($type . '_element_process'),
        '#prefix' => '<div id="' . $id . '-wrapper"><div id="' . $id . '">',
        '#suffix' => '</div></div>',
        '#states' => array(
          'visible' => array(
            ":input.{$prefix}-choose-input-type" => array('value' => 'date'),
          ),
        ),
      );
      $form[$prefix . '_group'][$relative_id] = array(
        '#type' => 'textfield',
        '#title' => check_plain($relative_label),
        '#default_value' => $relative_value,
        '#description' => t("Relative dates are computed when the view is displayed. Examples: now, now +1 day, 12AM today, Monday next week. <a href=\"@relative_format\">More examples of relative date formats in the PHP documentation</a>.", array('@relative_format' => 'http://www.php.net/manual/en/datetime.formats.relative.php')),
        '#states' => array(
          'visible' => array(
            ":input.{$prefix}-choose-input-type" => array('value' => 'relative'),
          ),
        ),
      );
      if ($which == 'all') {
        $form[$prefix . '_group']['#pre_render'][] = 'ctools_dependent_pre_render';
        $form[$prefix . '_group']['#dependency'] = array($source => $operator_values);
      }
    }
    return $form;
  }
}

```

# Answer
> 0 votes
The @kiamlaluno solution is good but I think this tiny problem not need this code you can handle and solve it with some jquery. it just need provide (or add to exists `js` file). in your `js` file do something like below

```
 $('.views-widget .form-item-created-min label').text("My min label text");
 $('.views-widget .form-item-created-max label').text("My max  ");

```

**This is just example and you should get the class of your end and start form element(you can try it in console of your firebug first then if you see that work put it in scripts.js(or any js file you want))**

---
Tags: 7, datetime
---


# Question
Title: How do I add class "caption" into image?
I using image field with insert module to upload image. After select an image and upload, I press "insert". The image appears in body but the script of image doesn't have class "caption".

```
<img src="/sites/default/files/apple.jpg" title="Some description image here" height="260" width="500">

```

How do I add class "caption" into image?

# Answer
There is an option in the Insert section of the field to add classes. See the screenshot below.
> 3 votes

# Answer
For adding caption to image there is some module

Image Caption

> DESCRIPTION:
>
> This module uses JQuery to dynamically add captions to images. The image title attribute is used to create the caption. It basically wraps the image in an html container div, takes the image title text and appends that in a child div underneath the image. Technically, it works by implementing Drupal's hook\_nodeapi to add one small snippet of captioner jquery to the head section of the page when a node of the configured type is viewed.

Image Field Caption

> Description: Adds an extra text area for captions on image fields.
>
> Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

JCaption

> Description: This is a simple module for Drupal 7.x that uses jQuery to transform the TITLE or ALT attribute of a image to a image caption. There is a settings page with lot's of possible configuration. The image caption won't show in the WYSIWYG-editor, but will be visible when you view the node.
>
> The module differs in several ways from similar modules.
> -1 votes

---
Tags: media
---


# Question
Title: How to add a description to an image field?
I have a content type which has a **field** of the **image field** type.

When editing this field I see that I can:

```
Enable Alt field

```

and also can:

```
Enable Title field

```

Is there any way to **Add a Description field** to be shown under each image.

# Answer
One other option to consider and may not work for you is to use the EXIF module and have it automatically grab the EXIF caption and then you are good to go with bulk upload using something like: Multiupload Imagefield Widget You then simply add in an EXIF field that grabs the image data and run drush exif-update but I am not sure if this fits your use case, it's purely dependent on the images having embedded EXIF data (i.e. from Adobe Lightroom or iPhoto).

It's primarily how I built my new site, High Rock Photo but only with single images in my case but I think it would be extendible with the Multiupload Imagefield Widget. Just thought I would throw it out there.

Here is my recipe:

* Title Module (converts the traditional Title to a field so you can do stuff with it).
* Token
* Automatic Nodetitles
* Exif
* You would add Multiupload Imagefield Widget as mentioned above. I have used this module but not within this exact recipe.

Essentially what I did was use The Title module and replace the traditional title so you can then set it to not required. Use Auto Nodetitles to grab a token from Exif data from the image and use it as an automatic title. Note you can really use Exif data for any field to display so you may not even need to do the whole replace Title nonsense. If I have some time I will run a test with this using the Multi upload widget. For my image description, I use the Exif `iptc_caption` from my image.

Note there is a bug (not fixed yet or responded to by maintainer) for Exif that makes you run drush exif-update every time you resave a node. Not ideal.
> 3 votes

# Answer
To do that you'd need to add another column to the field type, which there's no native support for currently.

You're not alone in wanting this functionality (I'd definitely like it) and there is a patch that adds a `hook_field_schema_alter()` function to the field module, which you can use to add extra columns. I haven't tried it but the comments and tests on the above link seem to suggest it does work.

Bear in mind if you go down that route you'll also have to implement a few other alter hooks (`hook_field_widget_form_alter()` for example) so it's not a quick-fix.

If you're not up for patching core you might just want to use the Field Collection module to accomplish something similar. You can add a collection item containing an image widget and textarea widget to basically achieve the same effect (although there is some very slight impact on performance).
> 3 votes

# Answer
This issue inspired me to build the Image Field Caption module for Drupal 7.

The module adds an extra text area, similar to the alt/title text fields, for image fields. The caption text area can be used to add plain text or an html description to an image field.

1. Download the module
2. Enable the module
3. Add a content type with an image field, or use an existing content type with an image field
4. Add or edit a node with an image field
5. Enter text or html into the image field caption text area
6. Save the node and view it to see the caption displayed below the image field

To customize the caption display, take a copy of the image\_field\_caption.tpl.php file and place it in your theme's directory, for example:

```
sites/all/themes/MY_THEME/image_field_caption.tpl.php

```

Now you can modify the html to meet your needs.
> 3 votes

# Answer
Also For adding caption to image there is some module

Image Caption

> DESCRIPTION:
>
> This module uses JQuery to dynamically add captions to images. The image title attribute is used to create the caption. It basically wraps the image in an html container div, takes the image title text and appends that in a child div underneath the image. Technically, it works by implementing Drupal's hook\_nodeapi to add one small snippet of captioner jquery to the head section of the page when a node of the configured type is viewed.

Image Field Caption

> Description: Adds an extra text area for captions on image fields.
>
> Similar to the alt and title text fields available with an image field, the caption text area can be used to enter text or html descriptions of an image.

JCaption

> Description: This is a simple module for Drupal 7.x that uses jQuery to transform the TITLE or ALT attribute of a image to a image caption. There is a settings page with lot's of possible configuration. The image caption won't show in the WYSIWYG-editor, but will be visible when you view the node.
>
> The module differs in several ways from similar modules.
> 1 votes

# Answer
If you are willing to use the title field as description, you can use the Image Caption or Image Caption Formattermodule. There is a request to get something like this included in core for D8. It would be based on the html5 caption tag.
> 0 votes

---
Tags: entities, media
---


title: Keep Alive in .htaccess

text:
# Question
Title: Keep Alive in .htaccess
Any potential issues with enabling keep alive in the .htaccess file for my Drupal 7 websites? Header set Connection keep-alive

# Answer
I can't see any potential issue with using `Keep-Alive` unless it is not properly configured. e.g

1. `KeepAliveTimeout` value is not ideal. For example, if the site is high traffic the value should be higher to make sure there is no frequent tcp connection re-initiated.
2. `MaxKeepAliveRequests` should be tweak according to number of assets the server is serving.

It is recommended to use this feature to:

1. Reduce latency
2. Reduce the use of server resources such as CPU and memory

For HTTPS you might want to check SPDY.

> SPDY is a protocol developed by Google to increase the speed and efficiency of delivering web content. SPDY modifies parts of the HyperText Transfer Protocol (HTTP) to improve web performance.
> 1 votes

---
Tags: .htaccess
---


# Question
Title: How to limit access to a meeting content type to only the participants specified via Entity Reference?
I have a content type that contains information about meetings. One field of this content type is 'members', which is of type Entity reference (a field type provided by the Entity Reference module). It specifies the included users in the meeting (using a multiple select list).

I want the content to be accessible only by these specified users.

Is it right to use the Node access user reference module for this purpose? If so how?

# Answer
> 3 votes
Use the Node access user reference module. Since you're already using Entity reference, it should fit. Some more details about this module (from its project page):

> Gives content access permissions to users for content that references the users with User reference or Entity reference.
>
> This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.

You should configure the module similar to the settings shown in the screenshot on its project page, which is like so:

Though I would uncheck the `Grant for all users` option (= view).

That way the users who can create such *meetings* (nodes) have all permissions they need (since they'll be the author). And the "specified users" will be able to *view* it, which appears to be exactly what you want.

To actually configure these settings, refer to the module's README.txt, which includes these instructions:

> Create a field to reference users in a content type using the Field UI. The field's configuration page will contain the settings for Node access user reference. For detailed instructions on using the Field UI see: https://www.drupal.org/documentation/modules/field-ui

---
Tags: 7, entities, users
---


# Question
Title: How do I include a script in a node body?
I am trying to include JavaScript code in a node body, when I am editing the node.

>

The purpose of that code is hiding a `<div>` tag whose ID is *test*.

The code was added to the node, but the `<div>` tag is still visible.

I added `scripts[] = js/test.js` to the .info file. I then put the *test.js* file inside the *mytheme/js* directory and I cleared the cache from Drupal side. Still, nothing happens.

I have also installed jQuery release 1.10, but this didn't change the outcome.

It seems like the *JQuery.js* file is not loaded.

How can I load it?
Do I also need to add the *jquery.min.js* in the .info file and the *js* directory?

When I put thIS code in a block, it works.

```
(function($) {
  $('#wrap').hide();
})(jQuery);

```

Doing the same with the file I am using doesn't work.

# Answer
> 2 votes
As @Gulok and @Drupalist said it is not good that add your js in content,the simple way to add js with one of below solutions (it is seems you are newbie to drupal I suggest if you want use learn and use drupal use is correct,I can suggest a solution that you can add js in body(content) but I prefer guide you in correct way ;) )

> The PHP function `drupal_add_js()` lets you add a JavaScript file, setting or inline code to the page and it takes 5 parameters (see the api reference).
>
> The first parameter is always going to be a path to a js file, an array, or a piece of JavaScript code. If the second parameter is 'module' (the default), 'theme', or 'core', then the first parameter must be a path and the only difference between these three is the order in which the script tag will be placed relative to other scripts, i.e. core scripts first, then module scripts and finally theme scripts.
>
> If the second parameter is 'setting', then the first parameter must be an array of settings. This is very handy for telling JavaScript about the configuration settings for your module, for example, and is explained in more detail in the next section.
>
> The final possibility for the second parameter is "inline" and this means you are passing in straight JavaScript code as your first parameter, which you want written directly to your page between script tags, rather than a call to a file.
>
> These two are the most important parameters for this function - indeed you may never even use the second one if all you ever want to do is add a js file for your module - but you can learn about the other parameters by reading this function's documentation at api.drupal.org. Adding JavaScript from within a module
>
> So, let's say you have written some jQuery code that targets some of the elements that are output by your module or theme. You simply need to save your jQuery code as a JavaScript file (i.e. with the .js extension) and place it in your module or theme's directory. If it's for a module, you then need to make the call to drupal\_add\_js() as above, from wherever the module is about to output content (e.g. in hook\_block or hook\_nodeapi), or if the JS is not acting on content output by your own module you can call it from hook\_menu or hook\_init. Note, that putting this file into hook\_init means it will run on every page request, whether needed or not. Here is how you would ensure the file gets added:
>
> The jquery.js file is included automatically so you don't need to worry about adding it.
>
> To add JS (or CSS) file from form builder function the recommended way is to use Form API #attached property as below,
>
> See Form API reference for more details. Adding JavaScript from within a theme
>
> Adding JavaScript to a Drupal 8 theme With drupal\_add\_js (Drupal 6 & 7)
>
> (drupal\_add\_js is deprecated in Drupal 8; use '#attached' instead.) If you are adding your .js file from within a theme, then you simply need to make the call from within template.php, you need to add the second parameter this time as 'theme' so that Drupal knows this script should be loaded after all core and module scripts are loaded:
>
> ```
>   <?php drupal_add_js(drupal_get_path('theme', 'mytheme')   .'/mytheme.js'); ?>
>
> ```
>
> Using the theme's .info file (Drupal 6 & 7)
>
> You can add your script path in the .info file of your theme and Drupal will include them automatically. name = My theme description = Theme developed by me. core = 7.x engine = phptemplate
>
> ```
>      scripts[] = mytheme.js Using a preprocess_page function
>
> ```
>
> To conditionally add js to the theme, you can use a process\_page function:

```
 <?php function mytheme_preprocess_page(&$vars, $hook) {   if (true) {
     drupal_add_js(drupal_get_path('theme', 'mytheme') . '/mytheme.js');
     $vars['scripts'] = drupal_get_js(); // necessary in D7?   } } ?>

```

and according you comment your js will be something like

I try to include a jQuery in the body of a content type, as shown in the image below:

enter image description here

The purpose of this jQuery is to hide a div with id="test", so that the text aaaaaaaaaaaaaaaaaaaa in it is not shown.

The jQuery was added to the content (saved in it), but yet I still can see the aaaaaaaaaaaaaaaaaaaa and my js did not run.

Seems like Drupal JQuery.js file is not loaded, so how can I get it loaded?

```
(function($) {
$(document).ready(function(){
$('#wrap').hide();
});
})(jQuery);

```

# Answer
> 1 votes
For your specific need, if you really need code to belong to node, I suggest Code per Node. OK, it's still no good on production server, but sometimes one needs an easy to use test field, or just one page for some very specific purpose.

> Code per Node makes it possible to add custom CSS and Javascript per **node**, per **content type**, per **block**, and globally. The code is stored in the database, but served from the file system. It also supports syntax highlighting with CodeMirror.

Serving from filesystem means that if you `grep` your site for code you don't like, you will find it. And it's fast. There are other problems with content containing code, and CPN at least tries to address them. Still no go on important sites, but way better than having the same on your own.

# Answer
> 0 votes
Add a `.js` file in your theme directory and declare its existence in the `.info` file of the theme, In this file write the above code to see if it works.

Besides that you should never call Javascript functions in that way. you must either place it in the theme folder (as I said) or load it via drupal\_add\_js.

---
Tags: 7, javascript
---


title: access $node in form breaks ajax call

text:
# Question
Title: access $node in form breaks ajax call
I built a custom form that works well, however I updated my custom module to create a custom content type and add the form via `hook_node_view()`.

Everything works, until I access the `$node` object in the form (e.g. to set default values).

**Scenario 1**: The node is created but we **do not** access `$node` object to set default values. In this case everything works.

**Scenario 2**: The node is created and we **do** access `$node` object to set values in the `$form`. In this case ajax breaks.

See below for code:

```
function quickform_node_info(){
    $t = get_t();
    $items = array(
        'quickform' => array(
            'name' => $t('MAGNIFI QuickForms'),
            'base' => 'quickform',
            'description' => $t('Create Artist, Photo, Music, and Record Label Forms'),
            'help' => '',
            'has_title' => 1,
            'title_label' => $t('Record Label Name'),
            'locked' => 0,
        )
    );
    drupal_alter('node_info', $items);
    return $items;
}

function quickform_node_view($node, $view_mode, $langcode){
    $form = drupal_get_form('quickmulti_form', $node);
    $node->content['quickmulti_form'] = array(
        $form
    );
}

function quickmulti_form($form, &$form_state, $this_node = false) {
    #$this_nod

    $form = array();
    #include this entire file whenever this form is included
    #form_load_include($form_state, '.php',        'quickform','quickform.module');
    $form['#tree'] = TRUE;
    $_SESSION["anonymous-tracker"]=time();
    $form['#attributes']['enctype'] = 'multipart/form-data';

    $form['headingtext1'] = array(
        '#markup' => t('PROMOTE ON MAGNIFI'),
        '#prefix' => '<h1>',
        '#suffix' => '</h1>',
    );

    $form['headingtext2'] = array(
        '#markup' => t('Join over 17,000 artists that are leveraging the MAGNIFI platform to connect with concert-going fans. MAGNIFI is 100% focused on connecting music to concert dates and sales! '),
        '#prefix' => '<p>',
        '#suffix' => '</p>',
    );

    $form['headingtext3'] = array(
        '#markup' => t('Fill out the below form to get started.'),
        '#prefix' => '<p>',
        '#suffix' => '</p>',
    );

    $form['contact_info']=array(
        '#type'=>'fieldset',
        '#title'=>t('Contact Info'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE
        );

    $form['contact_info']['first_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First Name'),
        '#size' => 255,
        '#maxlength' => 255,
        #'#required' => TRUE,
    );

    $form['contact_info']['last_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Last Name'),
        '#size' => 255,
        '#maxlength' => 255,
        #'#required' => TRUE,
    );

    $form['contact_info']['email1'] = array(
        '#type' => 'textfield',
        '#title' => t('Email'),
        '#size' => 255,
        '#maxlength' => 255,
        #'#required' => TRUE,
    );

    $form['artist_info']=array(
        '#type'=>'fieldset',
        '#title'=>t('Your Artists'),
        '#description'=>t('All fields are required'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#prefix' => '<div id="artists-wrapper">',
        '#suffix' => '</div>',
        '#tree' => TRUE,
    );

    $form['artist_info']['tos_c'] = array(
        '#type' => 'checkbox',
        '#title' => t('I Accept'),
        '#size' => 255,
        '#maxlength' => 255,
        #'#required' => TRUE,
    );

    $form['artist_info']['tos_p'] = array(
        '#markup' => t("I certify that (1) I am authorized to submit this webform as the Artist named herein or on behalf of this Artist; (2) this Artist controls all rights in the compositions, recordings and images authorized in this webform for MAGNIFI's service, or this Artist has the necessary permissions from all rightsholders to so authorize; (3) I understand and agree as this Artist or on behalf of this Artist to the MAGNIFI Artist Terms of Use Agreement, and warrant that the compositions, recordings, images and other content & information provided in this webform are not in violation of the MAGNIFI Artist Terms of Use Agreement."),
        '#prefix' => '<p>',
        '#suffix' => '</p>',
    );

    // artists_count =  added by internal user, defaults to 1
    // next_artists = for end user to add more
     if(!empty($this_node->field_artist_names['und'][0])){
        $form_state['artists_count'] = count($this_node->field_artist_names['und']);
        $form_state['next_artists'] = $form_state['artists_count'] + 1;
    }elseif (empty($form_state['artists_count'])){
        $form_state['artists_count'] = 1;
        $form_state['next_artists'] = $form_state['artists_count'] + 1;
    }

    $total_artists = $form_state['artists_count'];

    for ($x = 0; $x < $total_artists; $x++){
        // Grab node information
        if(!empty($this_node->field_artist_names['und'][$x])){
                $this_artist = $this_node->field_artist_names['und'][$x];
            }
        $form['artist_info'][$x] = array(
            '#type' => 'container',
            '#prefix' => "<div id='artist{$x}'>", #should be different for each artist
            '#suffix' => '</div>',
            '#tree' => TRUE,
        );

        $form['artist_info'][$x]['artist'] = array(
            '#type'=>'fieldset',
            '#title'=>t('Artist @num', array('@num' => $x+1)),
            #'#description'=>t('All fields are required'),
            '#collapsible' => TRUE,
            '#collapsed' => FALSE,
        );

        $form['artist_info'][$x]['artist']['account_name'] = array(
            '#type' => 'textfield',
            '#title' => t('Artist @num Name', array('@num' => $x+1)),
            '#size' => 255,
            '#maxlength' => 255,
            #'#required' => TRUE,
            '#default_value' => (!empty($this_artist) ? $this_artist : ''),

        );

        $form['artist_info'][$x]['artist']['music_text'] = array(
            '#markup' => t('List titles in the same order as music files, one per line.'),
            '#prefix' => '<p>',
            '#suffix' => '</p>',
        );

        $form['artist_info'][$x]['artist']['titles'] = array(
            '#type' => 'textarea',
            '#title' => t('Album/Track Titles'),
            #'#size' => 255,
            #'#maxlength' => 255,
            #'#required' => TRUE,
        );

        $form['artist_info'][$x]['artist']['music'] = array(
            '#type' => 'plupload',
            #'#title' => t('Upload files'),
            '#name' => 'music[]',
            '#description' => t('Submit high-quality music files.'),
            '#autoupload' => FALSE,
            '#autosubmit' => FALSE,
            '#submit_element' => '#submit',
            '#upload_validators' => array(
                'file_validate_extensions' => array('mp3 wav aiff aac m4a ogg flac'),
                'plupoad_validator' => array(),
            ),
            '#plupload_settings' => array(
                'runtimes' => 'html5, html4',
                'chunk_size' => '20mb',
                'unique_names' => TRUE,
                'max_file_size' => file_upload_max_size() . '100000000',
                'prevent_duplicates' => TRUE,

            ),
            '#event_callbacks' => array(
                #'FilesAdded' => 'Drupal.mymodule.filesAddedCallback',
                'UploadComplete' => 'quickjoin_form_submit',
            ),
        );

        $form['artist_info'][$x]['artist']['photos'] = array(
            '#type' => 'plupload',
            #'#title' => t('Upload files'),
            '#name' => 'photos[]',
            '#description' => t('Submit high-quality photos.'),
            '#autoupload' => FALSE,
            '#autosubmit' => FALSE,
            '#submit_element' => '#submit',
            '#upload_validators' => array(
                'file_validate_extensions' => array('png jpg jpeg'),
                'plupoad_validator' => array(),
            ),
            '#plupload_settings' => array(
                'runtimes' => 'html5, html4',
                'chunk_size' => '20mb',
                'unique_names' => TRUE,
                'max_file_size' => file_upload_max_size() . '100000000',
                'prevent_duplicates' => TRUE,

            ),
            '#event_callbacks' => array(
                #'FilesAdded' => 'Drupal.mymodule.filesAddedCallback',
                'UploadComplete' => 'quickjoin_form_submit',
            ),
        );

    }#end artist_count loop

    $next_artist = $form_state['artists_count'];

    $form['artist_info'][$next_artist] = array(
        '#type' => 'hidden',
        '#title' => "add another artist",
        '#name' => "artist{$next_artist}",
        '#prefix' => "<div id='artist{$next_artist}'>", #should be different for each artist
        '#suffix' => '</div>',
    );

    if($form_state['next_artists'] == $form_state['artists_count']){
        $x = $form_state['next_artists'];
        $form_state['next_artists']++;

        $form['artist_info'][$x] = array(
            '#type' => 'container',
            '#prefix' => "<div id='artist{$x}'>", #should be different for each artist
            '#suffix' => '</div>',
            '#tree' => TRUE,
        );

        $form['artist_info'][$x]['artist'] = array(
            '#type'=>'fieldset',
            '#title'=>t('Artist @num', array('@num' => $x)),
            #'#description'=>t('All fields are required'),
            '#collapsible' => TRUE,
            '#collapsed' => FALSE,
        );

        $form['artist_info'][$x]['artist']['account_name'] = array(
            '#type' => 'textfield',
            '#title' => t('Artist @num Name', array('@num' => $x)),
            '#size' => 255,
            '#maxlength' => 255,
            #'#required' => TRUE,
        );

        $form['artist_info'][$x]['artist']['music_text'] = array(
            '#markup' => t('List titles in the same order as music files, one per line.'),
            '#prefix' => '<p>',
            '#suffix' => '</p>',
        );

        $form['artist_info'][$x]['artist']['titles'] = array(
            '#type' => 'textarea',
            '#title' => t('Album/Track Titles'),
            #'#size' => 255,
            #'#maxlength' => 255,
            #'#required' => TRUE,
        );

        $form['artist_info'][$x]['artist']['music'] = array(
            '#type' => 'plupload',
            #'#title' => t('Upload files'),
            '#name' => 'music[]',
            '#description' => t('Submit high-quality music files.'),
            '#autoupload' => FALSE,
            '#autosubmit' => FALSE,
            '#submit_element' => '#submit',
            '#upload_validators' => array(
                'file_validate_extensions' => array('mp3 wav aiff aac m4a ogg flac'),
                'plupoad_validator' => array(),
            ),
            '#plupload_settings' => array(
                'runtimes' => 'html5, html4',
                'chunk_size' => '20mb',
                'unique_names' => TRUE,
                'max_file_size' => file_upload_max_size() . '100000000',
                'prevent_duplicates' => TRUE,

            ),
            '#event_callbacks' => array(
                #'FilesAdded' => 'Drupal.mymodule.filesAddedCallback',
                'UploadComplete' => 'quickjoin_form_submit',
            ),
        );

        $form['artist_info'][$x]['artist']['photos'] = array(
            '#type' => 'plupload',
            #'#title' => t('Upload files'),
            '#name' => 'photos[]',
            '#description' => t('Submit high-quality photos.'),
            '#autoupload' => FALSE,
            '#autosubmit' => FALSE,
            '#submit_element' => '#submit',
            '#upload_validators' => array(
                'file_validate_extensions' => array('png jpg jpeg'),
                'plupoad_validator' => array(),
            ),
            '#plupload_settings' => array(
                'runtimes' => 'html5, html4',
                'chunk_size' => '20mb',
                'unique_names' => TRUE,
                'max_file_size' => file_upload_max_size() . '100000000',
                'prevent_duplicates' => TRUE,

            ),
            '#event_callbacks' => array(
                #'FilesAdded' => 'Drupal.mymodule.filesAddedCallback',
                'UploadComplete' => 'quickjoin_form_submit',
            ),
        );

    }

    //Add another file button
    $form['artist_info']['add_more_artists'] = array(
        '#type' => 'submit',
        '#name' => "add_more_artists{$next_artist}",
        '#value' => t('Add Another Artist'),
        '#submit' => array('artists_add_more'), #increment $form_state['artists_count']
        '#ajax' => array(
            'callback' => 'artists_add_more_callback', #function that returns elements
            'wrapper' => "artist{$next_artist}", #replace this wrapper with the returned elements
            'method' => 'append',
        ),
    );

    $form['submit'][] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );

    $form['#submit'][] = 'quickjoin_form_submit';
    return $form;
}

function artists_add_more($form, &$form_state) {
    $form_state['artists_count']++;
    $form_state['rebuild'] = TRUE;
}

function artists_add_more_callback($form, &$form_state) {
    $this_artist = $form_state['artists_count'];
    $form_state['rebuild'] = TRUE;
    return $form['artist_info'][$this_artist];
}

```

# Answer
> 0 votes
**I found the error :** I was accessing `$this_node->field_artist_names['und'][$x]` instead of `$this_node->field_artist_names['und'][$x]['value']`.

---
Tags: forms, hooks
---


# Question
Title: How to force drupal 7 to load HTTPS assets?
Environment: apache + ssl + domain access

Our drupal 7 site uses domain access multiple sub domains our server is SSL enabled

if I do not set $base\_url in settings.php then all of our assets our loaded via HTTP and the user receives a mixed content error

If I DO set $base\_url users are redirected to the default subdomain (e.g. foo.blah.com) instead of their current domain (e.g. bar.blah.com)

My question is, how do I force drupal to load all assets via HTTPS?

That way I can uncomment the #base\_url

# Answer
I updated settings.php with: $base\_url = 'https://'.$\_SERVER\['SERVER\_NAME'\];
> 5 votes

# Answer
if everything(SERVER AND HOST SETTINGS) is ok just `$conf['https'] = TRUE;` in your `settings.php`.

According to Enabling HTTP Secure (HTTPS)

> Drupal configuration :
>
> If you want to support mixed-mode HTTPS and HTTP sessions open up sites/default/settings.php and add $conf\['https'\] = TRUE;. This enables you use the same session over HTTP and HTTPS both -- but with two cookies where the HTTPS cookie is sent over HTTPS only. You will need to use contributed modules like securepages to do anything useful with this mode, like submitting forms over HTTPS and so on. While your HTTP cookie is still vulnerable to all usual attacks, a hijacked insecure session cookie can only be used to gain authenticated access to the HTTP site. It will not be valid on the HTTPS site. Whether this is a problem or not depends on the needs of your site and the various module configurations. For example, if all forms are set to go through HTTPS and your visitors can see the same information as logged in users then this is not a problem.
>
> For even better security, leave $conf\['https'\] at the default value (FALSE) and send all authenticated traffic through HTTPS and use HTTP for anonymous sessions. Once again contributed modules like Secure Login or 443 Session can help you here. Drupal 7 automatically enables the session.cookie\_secure PHP configuration on HTTPS sites, which causes SSL-only secure session cookies to be issued to the browser. For best-possible security, set up your site to only use HTTPS, and respond to all HTTP requests with a redirect to your HTTPS site. $conf\['https'\] can be left at its default value (FALSE) on pure-HTTPS sites. Even then, HTTPS is vulnerable to man-in-the-middle attacks if the connection starts out as a HTTP connection before being redirected to HTTPS. Use the HSTS module or set the Strict-Transport-Security header in your webserver to help prevent users from accessing the site without HTTPS.

also you can use Secure Pages module

**Description of module :**

> A small process which will redirect the required pages to a SSL version of the page.

**Update** also you can in `settings.php` do: `$base_url = 'https://'.$_SERVER['SERVER_NAME'];`.
> 1 votes

# Answer
The Secure Pages module does this.

> A small process which will redirect the required pages to a SSL version of the page.
> 0 votes

---
Tags: ssl
---


title: How to put db_merge into a try catch?

text:
# Question
Title: How to put db_merge into a try catch?
in my code i need to use db\_merge , that works well, but I'm looking for a way to show message when db\_merge do not insert a record (to avoid duplication) the message would be : "you can't add this record because it exists in the db". The best way is try/catch, but it seems to work for db\_selct,db\_insert,db\_update but not for db\_merge.

# Answer
> 2 votes
A merge query does this:

1. Does a record with the provided keys already exist in the database?
2. If no, add it with the provided field values
3. If yes, update the existing record with the provided field values.

Finding a duplicate isn't considered an exceptional circumstance, because that's what the query is designed to do; so no exception will be thrown.

If your aim is to support this statement:

```
"you can't add this record because it exists in the db"

```

Then a merge query might not be the right tool. `db_insert()` in a `try...catch` might make more sense in that case.

If you just want to know whether a record was added or updated, check the return value from `MergeQuery::execute()`:

```
$result = $query->execute();
switch ($result) {
  case MergeQuery::STATUS_INSERT:
    // New record was added
    break;
  case MergeQuery::STATUS_UPDATE:
    // Existing record was updated
    break;
}

```

---
Tags: database
---


# Question
Title: How to add call a js file in custom module that are added in libraries folder in drupal 7?
I am creating a custom module in drupal 7 and adding a js file in sites/all/libraries folder but its not working.Please check my code

```
function mymodule_library(){
$libraries['mymodule'] = array(
    'title' => 'My custom',
    'website' => 'http://www.test.com/test',
    'version' => '1.7.14',
    'js' => array(
      'sites/all/libraries/mymod/custom.js' => array(),
    ),
);
return $libraries;

```

}

# Answer
That code just registers the library with the system. To use it, you need to add it to the page with either

```
drupal_add_library('mymodule', 'mymodule');

```

or as part of a render array:

```
$build['#attached']['library'][] = array('mymodule', 'mymodule');

```
> 2 votes

# Answer
use drupal\_add\_js()

for calling a file ,, your code should be somehting like this:

```
drupal_add_js('sites/all/libraries/mymod/custom.js','file');

```
> 0 votes

---
Tags: hooks
---


# Question
Title: Problem with adding checkbox to a view of flags with webform view
So, I've been trying to implement a 'sample request' type webform using Flag, Webform, and Webform Views. The idea is to have a webform with a select list made from a view of Flags as implemented here through a custom moduleProgrammatic Sample Request, Drupal Steve.

The issue I'm having is that I can't seem to get a checkbox to show up in the view. I have followed the instructions at the webform views documentationWebform Views Docs by creating a boolean field with a checkbox widget. I'm Flagging Commerce products. I have even tried to add a boolean on Flags and add that into the view, but that didn't work either. Not sure is this is a Flags, Commerce, or Webform Views issue, but I wanted to report this here and see if anyone had any ideas.

# Answer
> 2 votes
Using drupal commerce (irrelevant), **session\_api**, flags, views, webform4, custom content type (product display in my example), custom module.

Works even under ***anonymouse*** user

I think it's in select field settings.

**Called "Multiple":**

**webform\_flags.module:**

```
    <?php
 /**
 * Implements hook_webform_select_options_info().
 */
 function webform_flags_webform_select_options_info() {
    $items = array();
     if (function_exists('webform_flags_user_flag_sample_requests')) {
         $items['webform_flags_user_flag_sample_requests'] = array(
         'title' => t("User's flagged products"),
         'options callback' => 'webform_flags_user_flag_sample_requests',
         );
     }

    return $items;
 }

 function webform_flags_user_flag_sample_requests() {
     $view = views_get_view('user_flagged_products', TRUE);
     $options = array();
     if(isset($view)){
         $view->set_display('webform_options');
         $view->execute();

         if ($view->result) {
             //$row_class = $view->style_options['row_class'];
             //$attributes = $row_class ? " class='$row_class'" : '';
             foreach($view->result as $item) {
                //dpm($item->field_field_image);
                $options[$item->nid] = '<a>' . render($item->field_field_image[0]['rendered']) . $item->node_title .  '</a>';
         }
         }
         else {
            $options[0] = t("Nothing");
         }
     }

    return $options;
 }

```

**View's settings:**

---
Tags: views, webforms, flags
---


# Question
Title: How to add phone number field to simplereservation/add page
I have installed the simplereservation module. I can add a reservation by visiting xxx.com/simplereservation/add page. I do not see phone number field on that page. How to add phone number field to the add page?

---

I think comment field is needed. I copied the comment form and pasted there. Then I edited the form for phone number as below:

```
  $form['phone'] = array(
    '#type' => 'textfield',
    '#size' => 50,
    '#title' => t('phone'),
    '#default_value' => $reservation["rcomment"],
    '#description' => t('You can add a phone for your reservation.'),
  );

```

When I go to simplereservation/add page, I do see the comment, phone number field plus other fields. However, after I enter the reservation info plus the phone number, I click Save this reservation. On the reservation page, I see other info except the 'phone number' + 'this reservation is for'. How can I see the phone number on the reservation page?

---

I have not learned how to use hook yet.

I did look at the simplereservation.install file and i saw how comment filed is defined in simplereservation\_schema(). I simply copied the comment code and modified for phone field as below:

```
 'rcomment' => array(
    'description' => 'Text comment that accompanies the reservation',
    'type' => 'varchar',
    'length' => 255,
    'not null' => TRUE,
    'default' => '',
  ),
    'phone' => array(
    'description' => 'phone no of customer',
    'type' => 'varchar',
    'length' => 25,
    'not null' => TRUE,
    'default' => '',
  ),

```

I still see the phone field add page not on the reservation page.

---

1. In sr.module \> i have added

```
$form['phone'] = array(
'#type' => 'textfield',
'#size' => 50,
'#title' => t('phone'),
'#default_value' => $reservation["myphone"],
'#description' => t('You can add a phone for your reservation.'),

```

);
2. In sr.install

```
'phone' => array(
'description' => 'phone no of customer',
'type' => 'varchar',
'length' => 25,
'not null' => TRUE,
'default' => '',

```

),
3. Disabled the module \> Uninstalled the module \> Cleared the cachse \> Enabled the module \> Created 2 items bc items were gone.
4. xxx.com/sr/add

Error: Notice: Undefined index: myphone in simplereservation\_add\_edit\_form() (line 545 of ..../sites/all/modules/simple\_reservation/simplereservation.module).

line 545:

```
   '#default_value' => $reservation["myphone"],

```

Please advise.

# Answer
I think if you don't want to edit module, you may use comment field for telephone number. It's much easier to customize comment label and change it to phone number, than to edit module's code for additional field to store in database and display in form. Anyway it will be your preference.

UPD: tried to do something. If you don't need user comment, you can change Comment label, make it required field, and change description. (better solution is to try alter form)

**Result**:

Where to replace code in ***sites/all/modules/simple\_reservation/simplereservation.module***:

You just can compare lines from original and my example.
> 0 votes

---
Tags: entities
---


# Question
Title: View displays no results for roles without Bypass Content Access
For some reason one of my Views displays no results when I use my moderator role, but it does when I use the administrator role. The role permissions are **exactly the same**, except for the "Bypass Content Access" permission.

When I display content of type A everything is displayed like it should. But as soon as I add a "referenced entity" relationship from A to type B, nothing is displayed and the view uses the "No results behaviour".

When I create a view displaying only type B, both roles can see everything just fine.

I'm using Content Access and Organic Groups. I granted the roles the same permissions. I also set the View permissions to None.

Does anyone have a clue why this could be?

# Answer
Based on my experience user1 (admin) bypasses everything , no matter what permissions the role administrator has granted (check to believe) , so just because you can see something in a view as admin and having same permissions for administrator and another role does not permits users in that role to access what admin can.

so check to see what what permissions may lead to accessing this view , this permission might be unchecked for admin but still bypassing it.
> 0 votes

---
Tags: views, users, entities, organic-groups
---


# Question
Title: CKEditor crashes when switching text format for specific content types
drupal 7.38

wysiwyg 7.x-2.2+63-dev

CKEditor 4.5.1.a513a92

If I create an article, switch text formats, everything is fine.

If I create a basic page, switch text formats, the ckeditor toolbar crashes and none of the buttons are clickable.

The crash also occurs if I create a new content type.

Here is a copy of the console log:

> Uncaught TypeError: Cannot read property 'sas' of undefined js\_ALIKtebL-PsIulJhUegpZmaxTRnPdAyakIc8kMeoL-4.js:382 Uncaught TypeError: Cannot read property 'sas' of undefinedDrupal.wysiwyg.plugins.sas.attach @ js\_ALIKtebL-PsIulJhUegpZmaxTRnPdAyakIc8kMeoL-4.js:382(anonymous function) @ js\_ALIKtebL-PsIulJhUegpZmaxTRnPdAyakIc8kMeoL-4.js:103CKEDITOR.tools.createClass.proto.setData @ ckeditor.js?nstvdm:780(anonymous function) @ ckeditor.js?nstvdm:349j @ ckeditor.js?nstvdm:10CKEDITOR.event.CKEDITOR.event.fire @ ckeditor.js?nstvdm:12CKEDITOR.editor.CKEDITOR.editor.fire @ ckeditor.js?nstvdm:13CKEDITOR.tools.extend.setData @ ckeditor.js?nstvdm:251b @ ckeditor.js?nstvdm:775(anonymous function) @ ckeditor.js?nstvdm:777CKEDITOR.editor.setMode @ ckeditor.js?nstvdm:328(anonymous function) @ ckeditor.js?nstvdm:323j @ ckeditor.js?nstvdm:10CKEDITOR.event.CKEDITOR.event.fire @ ckeditor.js?nstvdm:12CKEDITOR.editor.CKEDITOR.editor.fire @ ckeditor.js?nstvdm:13CKEDITOR.event.CKEDITOR.event.fireOnce @ ckeditor.js?nstvdm:12CKEDITOR.editor.CKEDITOR.editor.fireOnce @ ckeditor.js?nstvdm:13(anonymous function) @ ckeditor.js?nstvdm:246CKEDITOR.scriptLoader.load.g @ ckeditor.js?nstvdm:226CKEDITOR.scriptLoader.load @ ckeditor.js?nstvdm:226(anonymous function) @ ckeditor.js?nstvdm:245(anonymous function) @ ckeditor.js?nstvdm:233(anonymous function) @ ckeditor.js?nstvdm:231CKEDITOR.scriptLoader.load.g @ ckeditor.js?nstvdm:226CKEDITOR.scriptLoader.load.B @ ckeditor.js?nstvdm:226CKEDITOR.scriptLoader.load.s @ ckeditor.js?nstvdm:226(anonymous function) @ ckeditor.js?nstvdm:227

# Answer
> 0 votes
I would "downgrade" to the stable WYSIWYG 7.x-2.2 version of the WYSIWYG module, and to the 3.6.x version of CKEditor (such as CKEditor version 3.6.6.1.7696), since the WYSIWYG module does not support the 4.x version yet ...).

Another option is to switch to the CKeditor module (which is in core in D8 now ...), and no longer use the WYSIWYG module in combination with the CKEditor library.

---
Tags: wysiwyg
---