title: how can I change the site name

text:
# Question
Title: how can I change the site name
For some reason, I'm not able to change the name of this site. I try to change the name to 'Test Name', as shown in this screenprint:

But after I save the page, the name is repopulated with the previous title.

It is an old drupal site with many years of modules and various admins working on it, so anything's possible. It does have Pathauto installed, but I can't see any place where that is overriding the site title.

Any thoughts?

# Answer
> 2 votes
Look in settings.php; I expect someone set $conf\['site\_name'\] = 'Test name'. Anything hard-coded there cannot be overridden.

# Answer
> 2 votes
I suspect that the title is hard coded somewhere in your template or module files. I recommend running the grep command in the command line to find which file(s) have the title hard coded.

```
grep -r "My Title" sites/default

```

# Answer
> 0 votes
According to drupal documentation You can set it in `settings.php` with `$conf['site_name'] = 'Test name'.`

Also in drupal , `site name` registered with `variables` so you can get or set it with variable API

for set it use

```
  variable_set('site_name', 'My New site name');

```

This link can help you if you could'nt set it in your `settings.php`.

---
Tags: 6, path-aliases
---


# Question
Title: How to get row weights from a form before saving?
I have form with an image upload field which saves multiple images. User can reorder and crop images in that form. **Reorder using default drag option**.

My requirement is to create a PDF of images in current order when user clicks on submit button. I am taking the image uri from field values by loading node. So the order will be the saved order. I am creating the PDF inside **hook\_insert**.

**How do I get the row weights before saving the node, so PDF can be created according to current order of images?**

# Answer
> 2 votes
You don't need to do anything special to get the row weights for the images.

The "weight" or list order of the images is stored in the `delta` value.

e.g:

```
$node->field_images[LANGUAGE_NONE][0]['fid'];
$node->field_images[LANGUAGE_NONE][1]['fid'];
$node->field_images[LANGUAGE_NONE][2]['fid'];

```

The `delta` value is 0, 1 & 2 representing the first, second and third images respectively.

Also, if you're using one of the node API hooks, e.g `hook_node_insert`, you won't need to load the node, it should already be passed as a parameter there.

---
Tags: forms
---


# Question
Title: Where does Commerce Stripe store the plans that are created on my stripe account?
I have a stripe account all setup and I have created plans. In Drupal Commerce I have created products, but I realised it should have pulled the "plans" down from stripe. I have also tried the stripe payment module which did pull the plans down, but it would have required a lot of customisation to work well with the roles that we needed to assign per plan.

Where does Commerce Stripe store the plans created on my stripe account?

# Answer
> 0 votes
While I'm not familiar with Stripe, it looks like the `commerce_stripe` stores the details in the remote Stripe system via the stripe-php library

e.g, in `commerce_stripe_submit_form_submit`

```
Stripe_Customer::create
...
Stripe_Customer::retrieve

```

The other place for payment gateway settings will be on the individual payment method configuration form under Rules.

---
Tags: commerce
---


# Question
Title: Sort view items by field collection's field value
I added a field collection to Basic page that contains:

* box title
* box image
* box position on page

You can add 0 or more field collection's items to every basic page. Every node may contain 0 or more boxes. They will be used instead of default teasers. Here is an example:

***Node 1:***

* field collection item: \[Title 1, image1.png, 3\]
* field collection item: \[Title 2, image2.png, 1\]

***Node 2:***

* field collection item: \[Title 3, image3.png, 2\]

**Taxonomy Term View is configured as below:**

Format: unformatted list Show: Fields

***FIELDS***

Field: The field collection

***FILTER CRITERIA***

Content: Published or admin

***SORT CRITERIA***

Field: box position on page (asc) Content: Post date (desc)

***CONTEXTUAL FILTERS***

Content: Has taxonomy term ID (with depth) Content: Has taxonomy term ID depth modifier

However, items are sorted only by post date and "box position on page" field has no impact on sorting. I expect boxes to be sorted in this order:

* field collection item: \[Title 2, image2.png, 1\]
* field collection item: \[Title 3, image3.png, 2\]
* field collection item: \[Title 1, image1.png, 3\]

Note that 2nd box leads to Node 2 and the remaining to Node 1.

How to sort boxes by "box position on page" field that is part of field collection?

# Answer
> 0 votes
You can use field\_collection\_views module which it creates a default View of field collection type. Its address is `/admin/structure/views/view/field_collection_view` and I recommend you clone this View and configure the rest of the options. The *Fields* section contains a few items that are very helpful, like *Host Entity ID*, *Host Entity Type* and ... .

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


title: How to implement RSVP Functionality?

text:
# Question
Title: How to implement RSVP Functionality?
I have created event using Calendar in Drupal Commons. I need to implement RSVP for these events Details like FB event section.

Kindly guide me to create RSVP plugin in Drupal Commons. I just searched the web to get some reference link for RSVP Implementation in Drupal 7. In that link, user *nicoz* commented **"Use the flag module "**.

I just installed flag module and create that flag like **`Participant/Maybe/No`**, but I cannot achieve it, because a flag will only provide *flagged* content and *unflagged* content.

Kindly give me any idea for this type of flag creation or else give me alternative module for RSVP functionality.

# Answer
A flag that is created with the Flag module is indeed a boolean variable (it is "on" of "off"). In this specific case you should implement 3 possible values, i.e.:

* Participant
* Maybe
* No

Here is how you can get that implement by using 3 flags:

* Flag 1, with something like these "Link text" values:
    + (to **Flag**) = Yes I plan to participate.
    + (to **Unflag**) = Please ignore my "Yes I plan to participate" from before.
* Flag 2, with something like these "Link text" values:

+ (to **Flag**) = I'm not sure yet if I'll participate.
    + (to **Unflag**) = Please ignore my "I'm not sure yet if I'll participate" from before.
* Flag 3, with something like these "Link text" values:

+ (to **Flag**) = No I will not participate.
    + (to **Unflag**) = Please ignore my "No I will not participate" from before.

If it fits your requirement, you could "assume" that for somebody who did NOT set Flag1 and did not set Flag 2, the default applies which is something like "user does not want to participate, or didn't bother to let us know about it". That will avoid you need Flag 3.

If you're not familiar enough with the Flag module yet, I strongly recommend watching the set of 8 video tutorials about this module.

For more details, you may also want to refer to my answer to the question about Display unique text and button in nodes in a view in drupal 7. It contains the details about using the Entity Reference module for this, in combination with the Flag module, and possibly also the Rules module.
> 1 votes

---
Tags: flags, 7
---


title: Array Flip Error Message on All blocks

text:
# Question
Title: Array Flip Error Message on All blocks
Edited: I tried a lot to get warning solved, but end up with nothing. Can anyone look into this warning issue. Complete code is shown below:

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', $content_type)
          ->propertyCondition('status',1);
$results = $query->execute();
$node_ids = array_keys($results['node']);
$noddes = node_load_multiple($node_ids);
$fields = array_keys(field_info_instances('node', $content_type));
    foreach ($noddes as $keys => $node) {
            $item = array(
                'nid' => $node->nid,
                'title' => $node->title,
            );
    foreach ($fields as $name => $instance) {
            $items = field_get_items('node', $node, $instance);
            $item['fields'][$instance] = render_fields($items, $node, $instance);
        }

            $output_raw[] = $item;
    }
function render_fields($items, $node, $field_name) {
    $output_raw = field_view_value('node', $node, $field_name, $items[0]);

    return $output_raw;
}

```

The code above is edited code. I'm still facing this warning : **array\_flip.** **How to solve this warning?????**

After quering node ids from database, I am using node\_load\_multiple to load all nodes. `print_r(node_load_multiple($node_id))` gives me

```
Array
(
    [6] => stdClass Object
        (
            [vid] => 6
            [uid] => 1
            [title] => om
            ....
    [7] => stdClass Object
        (
            [vid] => 7
            [uid] => 1
            ...

```

when I use `field_view_value('node', $node, $field_name, $items[0]);` to render content to template file, I get the following error.

> Warning: array\_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController-\>load() (line 173 of /var/../includes/entity.inc).

**line 173 of entity.inc conatins:**

```
$passed_ids = !empty($ids) ? array_flip($ids) : FALSE;

```

It(line 173) says: *Create a new variable which is either a prepared version of the $ids array for later comparison with the entity cache, or FALSE if no $ids were passed. The $ids array is reduced as items are loaded from cache, and we need to know if it's empty for this reason to avoid querying the database when all requested entities are loaded from cache.*

So, according to above line :173 , entity loader can either flip **id** or **string** and i am passing node ids in `$passed_ids = !empty($ids) ? array_flip($ids) : FALSE;` .Then why am getting this warning????

**Warning: array\_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController-\>load() (line 173 of /var/www/html/std-build/httpdocs/includes/entity.inc).**

```
$items = Array
(
    [0] => Array
        (
            [value] => <p>Lorlita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>

            [summary] =>
            [format] => filtered_html
            [safe_value] => <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>

            [safe_summary] =>
        )

)
Array
(
    [0] => Array
        (
            [value] => <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>

            [summary] =>
            [format] => filtered_html
            [safe_value] => <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rctus est Lorem ipsum dolor sit amet.</p>

            [safe_summary] =>
        )

)

 $node = node_load_multiple($node_id);
$field_name = "body";

```

# Answer
The error occurs because you are not passing a string or integer value, you are passing an array.

`node_load_multiple` returns an array of nodes, so `$node_id` is probably an array containing multiple values, in your case.

To get the node object, you can use either `$node = node_load($nid);` or `$node = reset(node_load_multiple(array($nid)));`. The former is easier to load a single node.
> 3 votes

---
Tags: entities, i18n-l10n
---


title: D6: Adding HTML to CCK field data?

text:
# Question
Title: D6: Adding HTML to CCK field data?
In Drupal 6, I want to customise some CCK field data with some added HTML, but am not sure of the best/easiest way to do this. I couldn't find a CCK module to do this.

For example, I want to enter a URL (which is stored in the field), and then when it is displayed, it is embedded in some HTML. eg.

CCK Field data: filename.jpg

Output HTML: \
\\
Picture\

# Answer
Some answers here including:
> 0 votes

---
Tags: entities
---


title: Get the user ID given the comment ID

text:
# Question
Title: Get the user ID given the comment ID
If I have a comment ID, how can I get the user ID?

# Answer
You need to load the comment object:

```
$comment = comment_load($cid);
$uid = $comment->uid;

```
> 3 votes

---
Tags: 7
---


# Question
Title: How to show a title-link in a view for authorized and hide it for unauthorized users?
I have a view with some fields and one of them is the title field. Now i need the feature that when an anonymous user views the view, the title is not linked to it´s content. When the user logs in, then the title should link to its content. How is it possible to realize that? I have more or less no php skills.

# Answer
> 0 votes
You can implement template\_preprocess\_views\_view\_field function in your module and rewrite output for this field for anonymous users.

```
/**
 * Implements hook_preprocess_views_view_field().
 */
 function mymodule_preprocess_views_view_field(&$vars) {
   switch ($vars['view']->name) {
     case 'my_view_name':
       if ($vars['field']->options['id'] == 'my_field_name') {
         if (user_is_anonymous()) {
           $vars['output'] = strip_tags($vars['output']);
         }
       }
       break;
   }
 }

```

---
Tags: views
---


# Question
Title: How to redirect my content type form after submitting in module
How to redirect my content type form after submitting in module.

Code:

```
function message_proposal_form_alter( & $form, & $form_state, $form_id) {
  if ($form['#id'] == "article-node-form") {
    $form['submit'][] = 'my_callback_function';

  }
}

```

And

```
function my_callback_function($form, $form_state) {
  unset($_GET['destination']);
  $form_state['redirect'] = 'node/add/article';
}

```

# Answer
You can use Node Save Redirect module.

> This module provides a method of specifying a location to take the user after saving a piece of content. A set of radios buttons are added to the submission vertical tab on the content type edit form.

The available options are:

Default - Default behaviour

Return to Edit page after saving

Return to content overview page (assuming the user has access permissions

Re-redirect to another location. (any valid drupal path)

Or you may try to add submit function to 'Save' button

```
function mymodule_form_alter (&$form, &$form_state, $form_id) {
  if ($form_id == 'my_node_form_id') {
    $form['actions']['submit']['#submit'][] = 'mymodule_node_form_redirect_submit';
  }
}

function mymodule_node_form_redirect_submit ($form, &$form_state) {
  $form_state['redirect'] = 'node/add/article';
}

```
> 1 votes

---
Tags: 7, uri, redirection, forms
---


# Question
Title: How to add only unrefered node of a content type in an entity reference field of another content type
There are 2(two) Node types

1. A
2. B

**A** has a node reference field to node type **B**.

If a node *x* of **A** type used a node *y* of **B** type as a node-reference then next time node *z* of **A** type will not use the node *y* of **B** type as a node-reference because *x* is already used as node-reference.

# Answer
The Entityreference unique sounds what you're looking:

> This modules adds a checkbox to an entity reference instance to enable a check for unique multiple entity reference fields. With this option enabled it is not possible to add one and the same entity to a multiple entity reference field.
> 1 votes

---
Tags: nodes
---


# Question
Title: SCORM (v 1.2) integration for Quiz module
We are looking for SCORM integration with Drupal's Quiz module.

Essentially we should be able to Import/Export quizzes and questions as SCORM package(s). Ideal if SCORM player can be used for quiz taking and Results/Feedback displaying.

I couldn't find any library or API to ease up the integration work. Wondering if I have to write my own Importer and Exporter to handle this requirements.

# Answer
> 2 votes
Have a look at the Opigno LMS distribution, which is fully compliant with SCORM 2004 v3. Here is a quote from its project page:

> Opigno LMS is a full-fledged Learning Management System based on Drupal.
>
> It allows to:
>
> * Manage training paths organized in courses and lessons.
> * Assess students thanks to varied quizzes.
> * Award certificates to successful students.
> * Sell your trainings online.
> * Facilitate interactions thanks to live meetings, forums and chats.
> * ...

Maybe not to start "using" this distribution, but by reviewing it to get an idea about it's SCORM compliance, and then copy-an-paste whatever fits / makes sense to also include in your own site.

Contributed module SCO Node somehow relates to SCORM and might potentially be of some help to get you going (quote is from its project page):

> The SCO Node module allows nodes to be created that contain SCORM content. The SCO content can then be played and scored on a Drupal 7 site.
>
> The module currently supports SCORM 1.2 and some of SCORM 2004

---
Tags: quiz
---


title: How to add on comment's field in views

text:
# Question
Title: How to add on comment's field in views
In Drupal 7, I've added a field from comment field section *(under manage field)* of a content type. Now I want to add this field in a views.

# Answer
> 0 votes
Go to "manage display" after the tab of "manage field" and set label and format and drag out from hidden that it. If you are talking about views under field section you can click on add and search for the field you definitely find there.

---
Tags: views, comments
---


# Question
Title: What is the difference between the Trigger and Rules modules?
Both the Trigger and the Rules modules provide many event-driven actions, but there are still several difference. What's the major difference between them? When should I pick one module instead of the other one?

# Answer
> 4 votes
Loosely speaking, Rules is much more generic than triggers. As Johan Falk mentions, "you could say Rules is an extended version of Triggers.. it is technically true, but does not really cover at full extent."

# Answer
> 1 votes
Triggers is optional core module that provide basic functionality. Rules provide much more freedom and is more advanced module. But the both of them we can use together.

Here is an example for rules https://www.youtube.com/watch?v=j9SD2S69Fjw

---
Tags: rules
---


# Question
Title: How to change the hyper link to checkbox link?
I'm using Node Compare module to compare products, it showing the **Add to Compare** as link, You can see the DEMO here, but I want to show as **checkbox link**

> .

I have no idea on how to achieve this, any pointer would be helpful!

# Answer
> 0 votes
You can save checkbox image from here.

```
a.compare-toggle {
    background-image: url("/path_to_image/checkboxes.png");
    background-repeat: no-repeat;
    color: #000000;
    height: 16px;
    padding-left: 20px;
    text-decoration: none;
}
a.compare-toggle.add {
    background-position: 0 0;
}
a.compare-toggle.remove {
    background-position: 0 -16px;
}

```

Let me know if you face any further query/concern regarding this.

---
Tags: 7
---


# Question
Title: Does Aegir 3 allow multiple SSL sites on the same IP Address?
On our server some sites use SSL, some don't, some are Drupal sites, some are not. All the sites are served at the same IP address and the non-Drupal sites each use their own certificates (or none) per their Apache configuration.

With Aegir 2 it was only possible to have: one IP Address for non-SSL sites and one IP address per each SSL Drupal site which would exhaust our purchased IP addresses.

Does Aegir 3 allow multiple SSL sites / certificates on the same IP address?

# Answer
> 2 votes
Indeed it does. From the release notes:

> Aegir 3 now supports SNI for SSL.

---
Tags: 7, aegir, ssl
---


# Question
Title: How to record unique hits in node counter stats?
**Is there a way to only count the unique views in the core node counter stats?**

I was using the Statistics Advanced module for Drupal 6 but there is no Drupal 7 solution. The quote below is from the Statistics Advanced module and what I want exactly is that.

> **Only track 'unique' views of content**: If you keep viewing a node over and over again, the "x reads" counter won't increase each time. This is applied on a per-user basis as well as a **per session id for anonymous users**.

The Node View Count module doesn't effect the core statistics, it creates a new table for itself. So this is not an option for me.

What I'm looking for is a solution that effects the **CORE** statistics, nothing else.

# Answer
> 3 votes
# Node view count

You may want to use the Node view count module for this. Here is a quote about it (from its project page, bold markup added here):

> ... 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.

Specific to the D7 version of it, this is what is included also on the project page:

> Also now we count node views for anonymous users.

# Statistics Advanced

Be aware of the Statistics Advanced **(\*)** issue "Port Statistics Advanced Settings to D7", with current status = needs review.

My "recommendation" for anybody looking for a D7 version of it, is to ***review*** what is attached to Comment # 55 in that issue. And report any potential deficiencies in that same issue (confirmations that it works fine would be appreciated too, also via that same issue).

# Other modules to consider

If the Node view count and/or Statistics Advanced **(\*)** module doesn't fit your needs, then you may want to consider reviewing this shortlist of possible alternatives (quotes are from their project pages).

* Visitors **(\*)**:

> Displays information about visitors, and integrates with the WhoIs Lookup module
* Better Statistics:

> introduces a Statistics API, which allows for a way to collect, limit, and route custom access statistics and data.
* Piwik Web Analytics:

> Adds the Piwik web statistics tracking system (free open source) to your website.
>
> Related module: Piwik Reports, which provides graphical reporting of your site's tracking data inside Drupal.
* Chartbeat:

> ... to provide third party integration with Chartbeat, for real-time site monitoring statistics.
* Stat Counter:

> ... provides an integration between Drupal and StatCounter web statistics.

Enough options to "explore"?

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

# Answer
> 2 votes
You can try the **Better Statistics** module.

On the module page it says:

> This module introduces a Statistics API, allowing developers and contributed modules a way to collect, limit, and route custom access statistics and data.
>
> **For Administrators and Site Builders**
>
> * Customize what data is collected on each page visit
> * Limit where and for whom data is collected
> * Use Views (of type "access log") to generate custom reports using your custom data
> * Download modules that add and extend the above functionality

---
Tags: 7, nodes
---


# Question
Title: How to list out Flag content User in event page in Drupal Commons
I tried to create the equivalent of the RSVP module (for which no D7 version exists ...) in combination with Drupal commons. But I didn't succeed in that.

So I then decided to use the Flag module, and created a flag for Participant Flag **`(Participant/Maybe/No)`** using the answer to my question about "How to implement RSVP Functionality?".

The implementation of the Flag for this is OK, but my next question now is "How to get the exact list of Participants, with some User details?". Some of the User details I want to get included in the list are:

* User Name
* User Picture

Assume that user A **will attended** a "Sample event" and user C **will not attended** that event. Also assume that user B **will maybe attended** that event.

How to create these 3 lists, for each of the 3 flags I am using (1 flag for each of these lists):

* Participant List
* Not attended List
* Maybe Attended list

Anybody any suggestions?

# Answer
> 1 votes
# Create a head count for each flag

Refer to listing flagged content with Views for a tutorial about creating a view with flagged content.

Starting from around 6:55 (and up to around 12:05) it explains *How to create a view showing flagged content*. Before 6:55 it mostly shows how to create that "Sidebar" flag (skip that part if you know that already). Here are the relevant steps in it (that you want to pay special attention to):

* Even though the video uses a "global flag", your case is NOT a global flag (i.e. each user can flag/unflag, not just a restricted list of users, such as those with "administrators" or "content editors" role).
* The tutorial creates a view of type "block", but you probably want to create a view of type "page" (though a "block" might be sufficient also if you prefer).
* Within the "Advanced" link of the Views UI, you must add a "relationship" (think of an SQL "join" if you're not familiar with Views). To add such relationship, enter "Flag" as the "filter" on the popup window (as shown in the video around 8:25). You'll then get a shortlist of about 7 possible relationships to select from. Your question doesn't say (yet) if the flags you use apply to "nodes" or to "users", but I'm about sure (and going to assume) you'll be using "nodes". So use `Flags: node flag counter` as relationship. You might possibly also be able to use the `Flags: node flag` relationship instead (which is NOT shown in the video here), because the `Flags: node flag` relationship brings in more data about the flagging event, such as "who flagged it, when, etc".
* As shown/mentioned from around 10:20 in the video, this video is about a "global flag". If it would have been about a none-global flag, then it would count the people who have used the "flag". So with only that, you already have like a "head count" of people who have "set the flag". Something like "number of attendees" already?
* After you finish the first view for (say) the first flag, then repeat what is above by cloning that first view into a 2nd (and 3rd) view, and then adapt the 2nd view to use the 2nd (and 3rd) flag, to build a similar list.
* As shown/mentioned from around 11:00 in the video (up to around 12:05), if you've selected to create a view of type "block" (not a "page"), then you still have to position the block (created by the view(s)) in an appropriate theme region.

# Add more details about the flagging user

Refer to Getting the flagging user into Views for a tutorial about how to add more details about the flagging user (starting from around 2:00, though the real "Views" related part starts from about 4:00). Here are the relevant steps in it (that you want to pay special attention to):

* This is about creating a view op type "page" (not block), which is also what you probably want, in the format of a simple tabular display.
* The "path" where this view will be shown (around 4:40), like `user/%/friends`, which in your case I'd suggest something to become like `user/%/events`.
* The "menu tab" that will be created (around 5:10), like `Friends`, which in your case I'd suggest something to become like `Events`.
* The 2 (not just one ...) relationships that get added here, i.e.: `Flags: User Flag` (around 5:40) and `Flags: User`, which is *The user that flagged an item* (around 6:55)
* Note the "contextual filter" that gets added (around 7:40, up to around 9:00), i.e.: `User: Uid`. It's to answer questions like "what are the events that this user confirmed to be attending so far".
* Starting from about 9:10, the actual user details (such as `User: Name`) get added.

Starting from around 9:45, you get like a summary of it all, i.e.:

* Start from a user profile (such as user/1) and use the (new) tab ***Friends***.
* A recap of the "crucial part" of this view, i.e. the 2 relationships that this view is using.

---
Tags: flags, 7, log-messages
---


# Question
Title: Unable to render posted date in node--article.tpl.php
I'm attempting to render the posted date of an article in a specific way. I understand that there is a

```
Display author and date information.

```

Checkbox in the content type editor. However I don't believe that would resolve my issue. I'm using the domain access module and the articles on the domains using a different theme cannot be altered. Certainly not how they're displayed anyway.

Is there a way to programmatically grab the posted date from within the template? Is there something similar to

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

```

That I can use to render that information? Or is there a function I can call that contains that information?

# Answer
> 0 votes
I was able to render the date by performing

```
print format_date($node->created, 'article');

```

---
Tags: theming
---


# Question
Title: Drupal Multisite Creation using the same code base with multiple content databases
I am trying to create a multisite Drupal install which uses the same code base and a unique database for each site. I'm attempting to use the multisite wizard module to do this.

After completing the above steps, when I select site 1 as 'From site' and site 2 as 'To site', the site 1 database is empty and its tables are inside the database for site 2. How can i have separate databases for my sites?

# Answer
Looks like your using the drupal module Multisite wizard

This module doesn't seem to support one core multiple databases, only one core one database with multiple table prefixes. So all your data will be in the same Database in different prefixed tables.
> 1 votes

---
Tags: commerce, multi-sites
---


# Question
Title: How to create a Webform pre-build option list via a query to an external database?
I'm trying in Webform (version 4.9) to create a *pre-build option list* with data from an external database. A *pre-build option list* is an available list you get when creating a "select options" field in Webform (like list of countries, state, ...).

I didn't find an existing module that allows me to add such pre-build list to Webform.

So, first I added my external database information to the `setting.php` file.

To test it, I build a simple php page containing this:

```
db_set_active('external_db');
$query = db_query("SELECT id, name FROM TABLE")->fetchAllKeyed();
db_set_active();
Print_r($query);

```

And, it's working (= I got a correct result of my request).

So then I added this to my `.module` file:

```
function webform_pre_build_list_db_webform_select_options_info() {
    $items = array();
    $items['modeles_db'] = array(
        'title' => t('Modeles_db'),
        'options callback' => 'webform_pre_build_list_db'
    );

   return $items;
}

function webform_pre_build_list_db() {

db_set_active('external_db');

return db_query('SELECT id, name FROM table')->fetchAllKeyed();

db_set_active('default');

}

```

And, it's **not** working (= my list is empty).

If I try with a request to the Drupal DB, then, it's working. For example:

```
function webform_pre_build_list_db() {
return db_query('SELECT cid, recipients FROM contact')->fetchAllKeyed();
}

```

Is working well, I got recipients form drupal table "contact" in my list...

What am I missing?

Any help will be appreciated!

# Answer
> 1 votes
I changed this:

```
function webform_pre_build_list_db() {
db_set_active('external_db');
return db_query('SELECT id, name FROM table')->fetchAllKeyed();
db_set_active('default');
}

```

to this

```
function webform_pre_build_list_db() {
  db_set_active('external_db');
  $options = db_query('SELECT id, name FROM table')->fetchAllKeyed();
  db_set_active('default');
  return $options;
}

```

And it's working!

(Explanation: *return* immediately ends the execution of a function, in this case before `db_set_active()` could be called.)

Thanks to Nevets

---
Tags: webforms, database
---


# Question
Title: Can both my flag as well as unflag text have different background images?
I am using the Flag module to flag content and users on my site. In one of the nodes, i have attached a background image to the flag link. On clicking the link, the users also have the ability to unflag it. So on the unflag link i want another background image. Is it possible?

# Answer
You can use a preprocess function to override the output as a span with classes.

```
function MYMODULE_preprocess_flag(&$variables) {
  $flag = &$variables['flag'];
  $action = $variables['action'];
  if ($flag->name == 'drupal_like') {
    if ($action == 'flag') {
      $variables['link_text'] = '<span class="flag flag-heart-light"></span>';
    }
    else{
      $variables['link_text'] = '<span class="flag flag-heart-dark"></span>';
    }
  }
}

```

Then you can target these classes to write your css as David mentioned.

```
.flag-heart-dark{
  background: transparent url('images/flag.png') no-repeat;
}

.flag-heart-light{
  background: transparent url('images/unflag.png') no-repeat;
}

```
> 3 votes

# Answer
If the unflag link has a different CSS class, which it presumably does, you could set the background image with CSS

e.g, in style.css:

```
.unflag{
  background: transparent url('images/unflag.png') no-repeat;
}

```
> 1 votes

---
Tags: 7, flags
---


# Question
Title: How can I allow users to add a reason for a flag?
I have the Flag module installed on my Drupal 7.8 site, but I can't figure out how to allow users to submit a reason for a flag along with the flag. I've tried looking this up, but the only thing I could find was the Flag Note module, which is only compatible with earlier versions of Drupal. What I want to have happen is:

1. User goes to a node, and notices it's not accurate
2. User clicks the "Report inaccuracy" button, and some sort of text field pops down below it
3. User fills out reason it's inaccurate, and submits it
4. Then I can have it be displayed in some stylized div at the top of the page when anybody visits it, similar to the Wikipedia sort of tagging wiki pages thing.

Does anyone know how I could do this? If there's a module that will let me implement the Wikipedia page tagging style of thing without needing a "flag note", that would work perfectly too.

Thanks!

# Answer
There is a really good discussion about something like this at http://drupal.org/node/871064. It will take some patching and such but there seems to be a semi-working version available.

Other than that, it doesn't look like there is anything else readily available for Drupal 7 at the moment.
> 6 votes

# Answer
Check out Flag Note Module

> Extends the Flag Module to allow users to enter a note when they flag a piece of content and eventually build a flag history.
>
> Usage examples:
>
> * flag nodes or comments for abuse providing a descriptive reason
> * flag users as friends leaving a hint
> 0 votes

---
Tags: 7, nodes, entities, flags
---


# Question
Title: How can I submit a list of flagged nodes to the admin user?
I'm using the Flag module to make a list of items that a user would like more information on. The user flags each node and those are added to a flag list. I would like to allow the user to submit this list to the admin user somehow but have not yet found a way of doing so. I'm using Drupal 7.

Thanks kindly in advance!

# Answer
> 2 votes
I actually think you are trying to make this too complicated based on your feedback. The simplest way in my mind would be to have a view (using current userid as a contextual filter) that displays the items the user has flagged. This opens up a lot of nice possibilities such as being able to remove flags before submitting, sort, filter, table view etc etc. Then quite simply have a button in the view header/footer that "submits/emails" the view url and user id to the admin. The admin can have the same view just with an extra box for userid (or exposed filter or whatever you want).

# Answer
> 1 votes
I have a custom solution I'd be filling to share, basically an anonymous wishlist. Using views, flag, webform, and the following hook in a little custom module.

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

```

Alternatively, there's also this solution: http://drupalsteve.com/node/57, which I'm working on implementing for myself.

# Answer
> 0 votes
This will almost definitely require the use of the Rules module.

Using Rules, you can set up an event to fire after a user Flags an item. You can also set a condition to not do anything further until a certain count has been reached, like 5 flags for example.

Using that event and condition, you can then set an action to send an email to users in the Admin role notifying them of the list of Flags. Perhaps you can create a special page with Views, which displays the list of items which has been flagged, for easy viewing by your admins.

# Answer
> 0 votes
I think it would be better to let the users to Bookmark nodes and add them to folders. Then they can share the folder with the admin. You can use Bookmark Organizer Module for this.

> Bookmark Organizer extends Flag module by providing functionality to
>
> 1. arrange bookmarks by drag and drop them
> 2. create folders and place bookmarks into them
> 3. rename bookmarks and folders
> 4. show previews about bookmarks and contents of a folder
> 5. publish bookmarks stored in a folder to others
>
> Bookmarks are always user related. However, a user who has access to 'administer users' can edit other users' bookmarks as well.

---
Tags: 7, flags
---


# Question
Title: Why making a Views page instead of Views block?
In most of my projects views are displayed in a block instead of a page, eventhough it would be perfectly possible to make a views page in these cases.

The reasons why I do this:

* If the client wants to add some content on top of the view, he can easily do so by clicking the "edit" tab of the page the block is nested in. This is more accessible and easier to understand than creating/positioning blocks and setup their visibility, or even worse: use the header field feature of Views (which the client has no access to in normal cases).
* It's cleaner to manage the translated menu items to that page (taking in account that the menu items are manually grouped by language)
* If the client needs to, he can easily translate the page, and alter the visibility settings of the block so it would appear on the translated page as well. This makes more sense to clients than to fiddle around with translated alias urls.

Ofcourse, there must some downsides to this approach. One I believe is that it may increase the loading time of pages when there are a lot of other blocks in use (is that true?), but one should be able to counter this with the Context module I believe.

I'm bringing up this question to check this approach with other dev's to figure out if I should maintain this, or if I should reconsider it.

I live in Belgium, a country with two language communities (Dutch and French), so almost every project is multilingual, which is is also an important factor in the motivation above.

# Answer
Blocks are appropriate to display piece of content but a Page is for displaying the whole content.

If you create a block of a View, using admin UI you can easily place it in any region (or panels) and reorder it but this option is not available if you use Page.

In Panels, if you use `Place In-Editor` option to build the pages (like the following image) pages will not be available. This is a very powerful tool in Drupal so if you don't use the appropriate structure you will miss it.

So as a result, by using blocks even a regular user can also easily change the structure of the site and no coding is necessary.

If you create a Page display of a View, to display it's result in some section of the page you must use `views_embed_view` (or similar ones) function to load that View. This function doesn't load the View title, widgets and ... .

You can use 30 variables to store 30 numbers but you can also use an array with 30 cells. Both approaches work but you should use the reasonable one. It is like your question. you can build your site using both display modes but you should use each one in it's right position.
> 1 votes

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


# Question
Title: Configuring a basic multisite development environment in Linux
While installing Multisite devlopment i followed below instructions https://www.drupal.org/node/823990#comment-10184088

When i trying to call http://testsite.localhost/install.php throwing error Forrbidden Access to Page and in apache2/errorlog its showing AH01276: Cannot serve directory /var/www/html/drupal/sites/testsite.localhost/: No matching DirectoryIndex (index.php,index.html,index.htm) found, and server-generated directory index forbidden by Options directive, referer:

# Answer
If you followed the exact instructions and you did not change any paths, then you have a typo: /var/www/**html**/drupal/sites/testsite.localhost/ See the extra 'html' directory? Make sure the paths in the apache config (step#3) match the actual paths in your file system.
> 1 votes

---
Tags: 7, commerce, multi-sites
---


# Question
Title: How do I enable fuzzy search for Search APi solr search?
What I want to do is make it so that when I type "awe" i get results for "awesome." This is what fuzzy search is, right? It uses ngrams to match parts of a word?

I'm trying to follow the directions here but I'm not sure I'm doing it correctly.

In both the folders search\_api\_solr/solr-conf/5.x and solr-5.2.1/server/solr/drupal/conf, I have the files schema\_extra\_types modified to contain the following:

```
<fields>

<fieldType name="text_gramgram" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <!-- in this example, we will only use synonyms at query time
    <filter class="solr.SynonymFilterFactory" synonyms="index_synonyms.txt" ignoreCase="true" expand="false"/>
    -->
    <!-- Case insensitive stop word removal. -->
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords.txt"
            />
    <filter class="solr.WordDelimiterFilterFactory"
            protected="protwords.txt"
            generateWordParts="1"
            generateNumberParts="1"
            catenateWords="1"
            catenateNumbers="1"
            catenateAll="0"
            splitOnCaseChange="0"
            preserveOriginal="1"/>
    <filter class="solr.LengthFilterFactory" min="2" max="100" />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
    <filter class="solr.EdgeNGramFilterFactory" minGramSize="2" maxGramSize="25" />
    <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
  </analyzer>
  <analyzer type="query">
    <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords.txt"
            />
    <filter class="solr.WordDelimiterFilterFactory"
            protected="protwords.txt"
            generateWordParts="1"
            generateNumberParts="1"
            catenateWords="0"
            catenateNumbers="0"
            catenateAll="0"
            splitOnCaseChange="0"
            preserveOriginal="1"/>
    <filter class="solr.LengthFilterFactory" min="2" max="100" />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
    <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
  </analyzer>
  <analyzer type="multiterm">
    <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>
    <tokenizer class="solr.WhitespaceTokenizerFactory"/>
    <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="true"/>
    <filter class="solr.StopFilterFactory"
            ignoreCase="true"
            words="stopwords.txt"
            />
    <filter class="solr.WordDelimiterFilterFactory"
            protected="protwords.txt"
            generateWordParts="1"
            generateNumberParts="1"
            catenateWords="0"
            catenateNumbers="0"
            catenateAll="0"
            splitOnCaseChange="1"
            preserveOriginal="1"/>
    <filter class="solr.LengthFilterFactory" min="2" max="100" />
    <filter class="solr.LowerCaseFilterFactory"/>
    <filter class="solr.SnowballPorterFilterFactory" language="English" protected="protwords.txt"/>
    <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
  </analyzer>
</fieldType>

</fields>

```

I also tried doing what sg88 stated here and added the two lines where he stated in the schema.xml file, but that broke my solr.

# Answer
This didn't work for me the first time around, but with a fresh drupal installation, this link worked.
> 1 votes

---
Tags: search
---


# Question
Title: Pass node id to custom access denied panel page and/or view pane
Rather than display an "access denied" page, I want to over-ride the standard 403 with a panel page that contains several views which take the original node id as a contextual filter.

I can create a view which handles contextual filters easily. I can create a panel which over-rides the standard 403 with custom message.

However, there is no panels context that allows me to pass the original node id into the view, and the view doesn't get the "Content ID from URL" because the url passed to the view is "access-denied". PHP code in the panel confirms that when outputting $\_GET\['q'\] and arg() using a custom content with PHP filter.

$\_SERVER\['REQUEST\_URI'\] DOES return the original path with the node ID, which I can parse, but I still don't know how I could pass that as a context to the view.

What is the best way to I pass the originally requested node id to the panel, and how do I pass that as context to the view? Alternatively, how can I directly pass it to the view, if doing through panels is not possible.

# Answer
> 0 votes
I found a solution that works.

I've just changed the default value of the view's contextual filter to PHP code and added this:

```
$node_path = explode('/', drupal_get_normal_path(trim($_SERVER['REQUEST_URI'], '/') ));
return $node_path[1];

```

# Answer
> 0 votes
The above solution ended up causing errors in some cases. I decided to implement a ctools plugin to provide a context for the panel.

`$plugin = array(
 'title' => t("Original Node"),
 'description' => t('Provide token for original node on a 403 page.'),
 'context' => 'ctools_plugin_originalnode_context',
 'context name' => 'originalnode_context',
 'keyword' => 'originalnode_context', // Provides a list of items which are exposed as keywords.
 'convert list' => 'originalnode_context_convert_list', // Convert keywords into data.
 'convert' => 'originalnode_context_convert',
);

function ctools_plugin_originalnode_context($empty, $data = NULL, $conf = FALSE) {

$context = new ctools_context('originalnode_context');
 $context->plugin = 'originalnode_context';
 $context->data = $data;
 $context->title = 'Original node';

$path = drupal_get_normal_path(trim($_SERVER['REQUEST_URI'], '/'));

$router_item = menu_get_item($path);

if(isset($router_item['original_map'][1])){
$context->data['nid'] = $router_item['original_map'][1];
 }

return $context;

}

function originalnode_context_convert_list() {
 return array(
 'originalnode_nid' => t('Original node on 403 page'),
 );
}

function originalnode_context_convert($context, $type) {
 // switch is used in case of expansion (ctools plugin standard)
 switch ($type) {
 case 'originalnode_nid':
 return $context->data['nid'];
 }
}`

Works beautifully.

---
Tags: panels, views
---


# Question
Title: How to assign certain themes to certain to Content Types?
I am trying to assign certain themes to certain content types. Is there any way to do this in the admin configurations? I don't particularly want to use a module or modify php code for this.

# Answer
> 2 votes
I know you said that you don't want to use a module, but ThemeKey does exactly what you need. There is no Drupal core functionality that provides this functionality.

# Answer
> 1 votes
You may use Content Theme module.

The Content Theme module is a simple and easy module to use which allows to use different themes than the site default on content creating, editing, and viewing pages.

**Features**

Assign a theme to all content. (This overrides the system default theme)

Assign a theme to a content type. (This overrides content wide themes and system default)

Assign a theme to a content node. (This overrides content type themes, content wide themes, and system default)

Allow to use different themes on content creating/editing pages than on viewing pages.

Fine-grained permission control.

Drupal novice friendly.

# Answer
> 0 votes
If the views and panels modules are installed, you can create a view, hide or show the fields you want to show, create a panel to display the view.

---
Tags: theming, nodes
---


# Question
Title: Add html5 placeholders to node_add inputs
I'd like to add placeholders to node\_add field inputs. I'm trying to use dpm($form) but am not sure where to put it. I couldn't get node-add.tpl to work with this

```
 function MYTHEME_theme() {

  $items = array();

  $items['node_add'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'MYTHEME') . '/templates',
    'template' => 'node-add',
    'preprocess functions' => array(
      'MYTHEME_bootstrap_preprocess_node_add'
    ),
  );

  return $items;

}

```

The only template I got to work was page--node--add.tpl but $form shows a blank krumo.

# Answer
To add placeholders, or any custom attributes, you need to dig deeper: implement appropriate `hook_form_FORM_ID_alter`. For node add/edit form, it will be `mymodule_form_node_form_alter`. First parameter is `&$form` \- as you can see, it is taken by reference, so changes made to it are carried outside the function. Use `dpm($form)` to find appropriate element. Once you do, use `#attributes` to add attributes you want.
> 1 votes

# Answer
For adding placeholders you could use the #attributes property of the form elements. I'd suggest using a form\_alter-hook for that. You can put the code into the template.php of your theme (or into it's own module). It would look something like:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYTHEME_form_node_form_alter(&$form, &$form_state) {
  $form['title']['#attributes']['placeholder'] = t('Title placeholder');
}

```
> 0 votes

---
Tags: forms
---


# Question
Title: How to customize permissions for a custom module
I created a custom module that hides a field in a content type editing screen from the user and simultaneously auto-selects a value for that field for the user. It works great for the admin role but for some reason my other user's who are able to login and who have permission to edit the content type don't get this functionality applied. They still see the field and can still select a value for it.

Anyone know how to make the permissions for a custom module apply to ALL users?

Here's my module code:

```
/**
 * @file
 * Auto saving to a term reference field.
 */
 /**
  * Implementation of hook_form_alter().
  */
function seven_form_resource_node_form_alter(&$form, &$form_state, $form_id) {
    hide($form['field_icon']);
}
/**
 * Implementation of hook_node_presave().
 */
function grouphideandselect_node_presave($node){
  //Condition for particular content type
  if($node->type == 'resource'){
    $icon_ary = array();
    //Array to map category with icon given as Category=>Icon
    $field_type_to_icon = array(1 => 1,2 => 1,3 => 1,4 => 2,5 =>
2,6 => 2,7 => 2,8 => 6,9 => 6,97=>6,98 => 6);
    $category = $node->field_type['und'];
    foreach($category as $k=>$c){
      $icon = $field_type_to_icon[$c['value']];
      if(!in_array($icon, $icon_ary)){
        $icon_ary[] = $icon;
        $node->field_icon['und'][$k]['tid'] = $icon;
      }
    }
  }
}

```

# Answer
> 1 votes
Add the Field Permissions module, this gives you control over every field in the content type. You edit the permissions on a field by field basis in the content type editing area. This gives you control over editing, and viewing the field.

https://www.drupal.org/project/field\_permissions

---
Tags: 7
---


# Question
Title: How do I store large volumes or data points (temperature and humidity points)?
I'm trying to use Drupal as a headless API, and so far I'm having good results. One of the things I'm collecting is a Temperature and Humidity data. Thus far I've created an entity that can hold the data points, but now that I'm really thinking about it, this is not the most efficient way of doing this, a new entity has to be created for each datapoint. I've contemplated separating off this part of the api, but then I loose all of the Drupal functionality.

Is there a better way to store large sets of data points using Drupal?
Perhaps I can group the data points within a single field as a JSON string.

# Answer
This is a large topic, so I will just mention some points and you can make the rest.

You will need a module, so you must have a `.info`, `.module` and in your case a `.install` file.

In the `.module` file:

* Implement hook\_field\_info to tell Drupal about your custom field. Here is an example of how to use hook\_field\_info.
* You must also introduce a widget and a formatter for your field. The widget is what appears in forms when you want to get data from user, and the formatter outputs data in proper way in view modes.
* You need to notify Drupal about these items existence, hook\_field\_widget\_info and hook\_field\_formatter\_info will do the job for you.
* After that you must make your widget, hook\_field\_widget\_form is the proper hook here and hook\_field\_formatter\_view will handle your field view.
* Another thing is a zero function for your field - this function tells Drupal if the user has not filled or passed any data to your widget, hook\_field\_is\_empty is implemented for that and it is required, else after form submission your users will face an error.
* hook\_field\_validate can also be used to validate the data which is entered.

At this point we are done with the `.module` file, but we still have on more step to go: the `.install` file.

* Here we define a place for data to be stored in DB, hook\_field\_schema will do the job for you.

After this point you are all done.
> 0 votes

# Answer
I've found that Drupal is not that great at this sort of task. The right approach depends a lot on what other parts of the Drupal ecosystem you need the data to interact with.

* How do you need to query the data? (single field with JSON string is not going to be conducive to this!)
* Do you need Views integration?
* Do you want to use any of the various input widgets or field formatters?
* Will other content in Drupal need to relate to this data?

Anyhow, even without answers to those questions, I would point you in the direction of the Data module as a possible solution https://www.drupal.org/project/data

It will let you store your data in straightforward tables but provide you with some nice Drupal conveniences.
> 0 votes

---
Tags: 7, database
---


# Question
Title: How to render a static html from a drupal module
I need to call a static html page and display the content of it when calling it from the module function , i tried to call from the form api but its just rendering the full markup ,please help

here is the try :

```
$items['mailusers/staticpage'] = array(
    'title' => t('My Static Page'),
    'page callback' => 'my_static_page',
    'access arguments' => array('access GASF admin menus'),
    'access callback' => TRUE,
  );

  return $items;

```

and the function

```
function my_static_page() {
     $form['html'] =  array(
    '#type' => 'markup',
    '#markup' => //'<h2>My Heading</h2>'
         file_get_contents(drupal_get_path('module', 'mailusers') .'/mailuser.tpl.php'),
  );
 return drupal_render($form);
}

```

# Answer
The easiest way is to create a template file and use hook\_theme

1. Put your html in a html-page.tpl.php in your module directory.
2. Use following code to render the html template in your page.

After adding the code make sure you clear your Drupal cache.

```
function my_static_page() {
  $html = theme('html_page');
  return $html;
}

/**
 * Implements hook_theme().
 */
function your_module_theme($existing, $type, $theme, $path) {
  return array(
    'html_page' => array(
      'template' => 'html-page',
    ),
  );
}

```
> 3 votes

# Answer
Go for a template file. For any page on Drupal you can use template file. You need to place this file in your sites/all/customtheme/templates folder. Include your markup in the template file for the page n things should start working.

Refer the following link for more details https://www.drupal.org/node/104316&ei=jfCdIMSx&lc=en-IN&s=1&m=114&ts=1438714151&sig=AKQ9UO-epAwDkA\_VPfbLQHFr5Xq9KbiCtQ
> 0 votes

---
Tags: 6, forms
---


# Question
Title: How can I display nodes in a view both by title and by a short title
I am building a site where I need to display a list of diseases in a view, and I need to be able to display them both by their titles and by another field (an abbreviated title). The two fields need to display as if they were two separate nodes both linking back to the same node though.

For example: My users need to be able to find the "Immunosuppressive Drugs - Organ Transplantation" disease in my view under "Immunosuppressive Drugs - Organ Transplantation" and under "Organ Transplantation - Immunosuppressive Drugs".

When I have tried to just show the abbreviated\_title field as well, I get the title and the abbreviated\_title showing together when I need them to display as two separate nodes. Does anyone know how I could do that?

Here are pics: I need this node  To show up here and here when I click on the appropriate letters in this search box. So it is the same node, but needs to show up two separate times in the view

# Answer
The only way to do this is going to be to create either a custom entity or at least a custom table with Views integration. Views is designed to list one record per entity (or "row" of data).

## Custom code solution:

Create a table that actually has multiple rows per node. It would need at least 2 fields: nid and title, and you'd have to maintain the data in that table by implementing hook\_node\_update, hook\_node\_insert, and hook\_node\_delete. Then you'd need to expose that data to views either by defining a custom entity type based on that table, or by writing the Views integration directly.

## Field Collection Approach:

You could store your titles on another entity in the system. A Field Collection is probably the best due to the fact that it won't clutter up any other parts of the interface.

The general idea would be to add a Field Collection field (field\_alternate\_titles?) to your disease entity. The Field Collection itself really only needs a single field (field\_alternate\_titles\_title?) with cardinality equal to 1. You're not using Field Collection because of its ability to let you group fields together, but rather because it creates separate entities for each of your values that you can use Views to query against. You can set the cardinality for the Field Collection field (field\_alternate\_titles) to 2 or, if you want to allow an arbitrary number of alternate titles, unlimited.

You could stop now and keep things really simple. Your users would have to enter all of the titles that they'd possibly want for the disease in this field. This would require them to re-enter the node title as an additional entry in the Field Collection field, but it would save you from writing any code.

If you want a slicker user experience then you would probably want to do the following:

1. Hide the Field Collection field on the disease node edit form by using the available widget type of "hidden" (rather than "embedded"). You don't want your users seeing or touching the field in the edit form as you'll be maintaining the values for them.
2. Maintain the values in that field by implementing hook\_node\_presave and creating and relating your node to Field Collection entities according to the values entered for the node title and short title.

Whether you write the code to auto-populate the Field Collection values or not, you'll now need to build your view based on Field Collection as the base table rather than the Content (node) table. You can add a relationship to the host node entity so that you can grab whatever info you need from the node.

## Search Index Approach:

Another possible approach would be to use something like Search API which maintains a separate index of your content which you can muck about with when content is sent to the index. So you could create separate index entries for every title you want to be able to search/list by. You may find it helpful to use this module as a starting point as it does denormalization, which is what you're after: https://www.drupal.org/project/search\_api\_grouping
> 2 votes

# Answer
Check out this Acquia tutorial out on creating a view.
> 0 votes

# Answer
You could add another field title, then you would have one long title field and one short one, then in your View options , add the long and short field titles.
> 0 votes

---
Tags: views
---


# Question
Title: How do I create a node using web services and Anonymous user?
I have successfully installed the Services module and created a service with which I can retrieve a node or even several nodes (using Views Services) I've now configured an endpoint, whose purpose is to allow an application to create nodes through a JSON call.

After much messing about I finally configured the following JSON call:

```
{
"type":"demande-de-rdv",
"uid":"0",
"language":"und",
"status":"1",
"promote":"0",
"sticky":"0",
"title":"JSON Post using http_request",
"body":"Morbi sit amet leo molestie, luctus metus aliquet, pellentesque lacus! Suspendisse at laoreet nulla. Nunc sed tincidunt dolor. Donec condimentum     odio non nisl condimentum, id euismod arcu rhoncus? Nullam sit amet ante convallis, viverra nulla in, laoreet leo. Fusce vitae iaculis libero. Phasellus scelerisque varius augue, quis vulputate sapien vehicula vel. Sed at est at felis dignissim rutrum. Sed porta tristique sapien et viverra. Nunc ac elit tristique, laoreet lacus at, pharetra elit. Morbi sit amet commodo dolor? Donec consectetur justo vel fringilla rutrum"
}

```

However, when I post the call I get the reply "403 : Access denied for user anonymous", this despite the fact that I have configured the content type to be creatable by Anonymous (and have created a node for the content type in question to test it). I also gave Anonymous all the permissions on the Services module just in case, but it made no difference.

Where i am going wrong?

# Answer
> 0 votes
I have posted to /node and it works for anonymous after granted that permission and cleared cache by the way you don't have to set the field uid and it's not necessary if you set

> $request\_url = 'domain/endpoint/node';

```
// Node data
$node_data = array(
  'title' => 'product testing',
  'type' => 'product',
    "uid" => 0,
    "language" => "en",
    "sticky" => 0
);
//$node_data = http_build_query($node_data);
$data = json_encode($node_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json')
);
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);

```

---
Tags: services
---


# Question
Title: What does 'Drupal-friendly' hosting mean?
I'm new to Drupal and web-hosting generally. My question is what constitutes a totally Drupal-friendly host? I know that the installation is made easier by the host provider letting you have SSH access and the ability to extract compressed files on the server.

What else should I look for in a Drupal-friendly host?

# Answer
There are some things you may want to look into:

Drupal Requirements:

* PHP 5.2+ (Drupal 7)
* MySQL Database
* 128mb Memory Limit (For Heavy Imagecache processing)

Not Requirements but perks:

* SSH
* Drush
* Git (Latest)
* Crontabs
* Curl
> 6 votes

# Answer
Continuing F1234k's list:

4) **Drupal fanatic:**

* APC cache for better PHP performance
* Varnish proxy cache for faster content delivery
* Memcache for faster storage of temporary data
* Apache Solr for far better search functionality
* Fully managed hosting infrastructure
* Support staff with actual Drupal experience
> 4 votes

# Answer
"Drupal-friendly" hosting is a term that can be interpreted in many different ways depending on what kind of site you are planning to build and what kind of user you are. If I had to break it down to "levels of friendliness" I would say the following:

1) **Drupal tolerant:**

* PHP 5.2.5,
* MySQL,
* Apache (preferrably)

2) **Drupal friendly**:

* ability to change your PHP memory allocation to 96MB or more (Views is a common example that needs lots of memory)
* ability to change your PHP max execution time (30+ seconds)
* php safe mode: off
* enabled pdo (more info here)
* php register globals: off

(almost all of the above are met, if you can customize your php.ini file)

3) **Drupal loving**:

* SSH
* Drush installable (even better: through GUI)
* crontab access (there is an alternative for drupal 6, poormanscron, but comes with performance penalties if my memory serves well)
> 2 votes

# Answer
Personally I think that friendly Drupal hosting is not just a hosting providing you the basic set of Apache + PHP + MySQL. Because you still have to configure all dependencies to make it work reliable and fast.

And every Drupal expert knows that if you want your Drupal website work fast, you have to use fast cache storages like Redis/Memcahe and reverse cache proxy Varnish.

There are few hosting providers who provides out of the box this infrastructure configured specifically for Drupal:

* Acquia Cloud \- Mostly for enterprise. Built on top of Amazon Web Services
* Pantheon.io - Built on top of Rackspace
* Platform.sh - Built on top of Amazon Web Services

The last two is very similar and use container virtualization, but they aren't cheap.

As an alternative, you can try Wodby. It's not a hosting provider, but a cloud infrastructure service that will bring features similar to Pantheon.io/Platform.sh on any server, i.e. makes your own server Drupal friendly. It's built on top of Docker.
> 1 votes

---
Tags: 7
---


title: How to hide edit tab on entity form

text:
# Question
Title: How to hide edit tab on entity form
I'd like to remove the ability to edit/update an entity form once it was been completed and submitted correctly.

I thought there might be a way to lock an entity form? Or remove access? or hide the edit tab. Any suggestions on how to accomplish this?

Thanks

# Answer
> 0 votes
You could look into hiding the tab using hook\_menu\_alter. If you set access callback to FALSE then it will be hidden.

---
Tags: entities
---


# Question
Title: Javascript related problems when using old versions of IE and a proxy server
I have a site that is fairly javascript heavy.

It uses the edit module with some custom javascript overrides, some other plugins like fancy scrollbars, flexslider, image cropping, etc. as well as a bunch of custom js that does alot of ajax loading of content.

The homepage is basically a solr+facetapi search page that returns a huge grid of images, which are effectively cropped & positioned with js after they load (using imagesLoaded to wait before processing).

In all modern browsers everything works fine. In IE when not using a proxy, everything works fine. In IE \<= 10 strange things happen.

Normally what happens is the page starts loading and the images start appearing individually as they have loaded.

With IE + proxy the page starts loading and then seems to stop, while all the js & images are loading in the background, then after about 30 seconds (much, much longer than the page would take to fully load normally) all of the images appear at once.

Also, normally as images load in the are visibility: hidden, cropped & positioned and then are visibility: visible, but in this case not all of the images end up with visibility: visible, but the images have loaded in, you can see them with developer tools tweaking of css.

Enabling or disabling of js/css aggregation doesn't make a difference, nor does cache clearing. After a little debugging I noticed that the imagesLoaded plugin was not firing at all until the end and then was firing for all images at once, instead of normally it firing as each image loads, but there didn't seem to be any reason for this.

Setting the proxy server to "cache deny all" seemed to help the problem but it wasn't as good as it is normally in non-IE browsers (IE11 seems fine too).

Has anyone seen behaviour like this before or does anyone have any ideas of things to investigate?

**TL;DR:**
I have a site where everything loads normally except for users running IE \<= 10 and a proxy, in which case the page loads extremely slowly and javascript doesn't run as expected.

Has anyone seen anything similar or have any ideas on what it might be.

# Answer
> 1 votes
This was seemingly a server specific issue regarding a server I am not the maintainer of so I never got to the bottom of the exact cause (which is annoying because I like to know), however I eventually got around it by using the jQuery Lazy Load plugin to load the images.

---
Tags: 7, javascript, caching
---


# Question
Title: Set image format of field_view_field image field
I'm using a function to place an image from a user field into nodes that the user creates. The display is set to thumbnail in default, user account and tokens, but it shows up as original in the node. Is there a way I can set the format in the function I'm using somehow?

```
function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];
  $user = user_load($node->uid);

  $logo_var = field_view_field('user', $user, 'field_business_logo');
  $logo_print_var = drupal_render($logo_var[0]);
  $vars['logo_print_var'] = $logo_print_var;
}

```

# Answer
> 2 votes
Yes, you can set the field value display settings as a parameter to `field_view_field`

e.g:

```
// Customize field display settings.
$display_settings = array(
  'label' => 'hidden',
  'settings' => array(
    'field_multiple_limit' => '1',
    'field_multiple_limit_offset' => '0',
    'image_link' => 'content',
    'image_style' => 'thumbnail',
  ),
  'type' => 'image',
  'weight' => 0,
);
// Get field value
$logo_var = field_view_field('user', $user, 'field_business_logo', $display_settings);

```

---
Tags: nodes, entities, hooks, users, theming
---


# Question
Title: Pager extention not working in dynamic database query
I am trying to create a page which shows all the nodes created by the currently logged in user. To do this I am using a dynamic query to fetch the relevant nodes. However, for some reason the pager is not working. Instead it lists all of the nodes. I have not been able to work out why this is occurring as I have successfully used pagination previously with other less complex queries. The following is from the page callback function:

```
function playground_page() {
  $build = array();

  $build['intro'] = array(
    '#markup' => 'This is a testing ground for Drupal concepts.',
  );

  // Example of table join. Display content created by current user.

  // Construct base query.
  global $user;
  $query = db_select('users', 'u');
  $node_table_alias = $query->join('node', 'n', 'n.uid = u.uid');
  $query
    ->fields($node_table_alias, array('nid'))
    ->condition('u.uid', $user->uid);

  // Add pager and node_access options.
  $query
    ->addTag('node_access')
    ->extend('PagerDefault')
    ->limit(5);

  $nids = $query->execute()->fetchCol();
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    $key = 'node_' . $node->nid;
    $build[$key] = node_view($node, 'teaser');
  }

  $pager_args = array('tags' => array('<<', '<', NULL, '>', '>>'));
  $build['pager'] = array(
    '#markup' => theme('pager', $pager_args),
  );

  return $build;
}

```

# Answer
This issue is related to the use of extenders. When using an extender it is important to note that $query is not altered in place. A new query object is returned from extend(), and if it is not saved to a variable it will be lost. See Extenders documentation for more info.

To achieve this with the OP code, one would need to modify the following section:

```
  // Add pager and node_access options.
  $query = $query
    ->addTag('node_access')
    ->extend('PagerDefault')
    ->limit(5);

```

Full working code is as follows:

```
function playground_page() {
  $build = array();

  $build['intro'] = array(
    '#markup' => 'This is a testing ground for Drupal concepts.',
  );

  // Example of table join. Display content created by current user.

  // Construct base query.
  global $user;
  $query = db_select('users', 'u');
  $node_table_alias = $query->join('node', 'n', 'n.uid = u.uid');
  $query
    ->fields($node_table_alias, array('nid'))
    ->condition('u.uid', $user->uid);

  // Add pager and node_access options.
  $query = $query
    ->addTag('node_access')
    ->extend('PagerDefault')
    ->limit(5);

  $nids = $query->execute()->fetchCol();
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    $key = 'node_' . $node->nid;
    $build[$key] = node_view($node, 'teaser');
  }

  $pager_args = array('tags' => array('<<', '<', NULL, '>', '>>'));
  $build['pager'] = array(
    '#markup' => theme('pager', $pager_args),
  );

  return $build;
}

```
> 0 votes

---
Tags: 7, paging, database
---


title: D7 conditional field option?

text:
# Question
Title: D7 conditional field option?
I have a content type that has a taxonomy field with two options. If Option A is selected, I want a further taxonomy field with items from Taxonomy X. If Option B is selected, I want another taxonomy field, but with items from Taxonomy Y.

In Drupal 6 I used Conditional Fields, which was great. However, there exists no stable D7 version yet, and I need this functionality for a project due this week. **The project page even says: "Drupal 7 version (3.x): 7.x-3.x is currently in development. It is a complete rewrite of the module that leverages the new entities system and the States API. Not ready for use on production sites yet."** So I feel like I'd be really dumb if I put this on a production site and something broke, when the module project page itself specifically tells me not to.

The other option seems to be Field Conditional State, but that's used on a total of 274 sites (compared to the ~18,000 of Conditional Fields).

1. Are there any other D7-compatible modules that allow forking of field display based on the value of another field?
2. If not, how stable is Field Conditional State?
3. Should I just suck it up and write a module that does what I'm wanting?

Many thanks.

# Answer
> 4 votes
Against my better judgement, I've used Conditional Fields to control field display. I'll post back here if I have any issues.

To anyone who arrives at this answer from Google, I made at my decision after looking at the module's usage stats, which paints it almost at parity with the stable D6 version:

It's worth checking out http://drupal.org/node/1551504, which is intended to spur a D7 stable release (The author looks a bit overwhelmed by it all, truth to be told.). I've closed any similar questions and pointed them to that, which seems to have the most traffic.

*That all said, it's kinda hard to contribute to a project when the maintainer is MIA...*

# Answer
> 2 votes
My personal current assessment of this is that there are still 3 main options:

I have used conditional fields a lot over a number of years and I find myself more and more frustrated with the number of bugs in it, especially if you have more than basic requirements.

That combined with the lack of movement in the issue queue means I no longer use it on new projects.

That is by no means a jab at the maintainers, I completely understand how hard it is to make time to do unpaid work maintaining Drupal modules, that is just how it is currently in this case.

So I currently prefer the field conditional states module. The reasons for that are:

* It is more actively maintained.
* It is less buggy (at least from my experience).
* From a technical point of view I prefer how it has been coded. It is simpler and relies more on the existing Drupal states API.

Where the Field Conditional States module has fallen down a little in the past has been its lack of support for different field types.
Support of different fields has greatly improved more recently though and I have found the maintainers have been quite fast to add support for fields on request (even without anyone providing a patch).

So I think that is less of an issue now but if you do have to support less common field types I recommend checking all the options to see whether any of them support those field types. That may make your decision a little easier.

I also think that custom code using the states API is a good solution in a lot of cases if you don't mind writing code. You can end up with a much simpler, more lightweight solution and can more easily handle complex scenarios.

# Answer
> 0 votes
conditional\_fields works better in D7. compared to field-conditional-state. When I used field-conditional-state + Jquery update module It did n't work. Refer http://drupal.org/node/1720120

---
Tags: entities
---


# Question
Title: How to add a term ALIAS(!) to content URL pattern?
I have latest Panopoly distribution installed (with Drupal 7).

What I need:

* my content items of a certain content type to have the f-g URL:

"vocab term URL alias"/"Node-title"

(first part of the URL should be term alias(!), not the term name as I have my term names in Cyrillic).

What I did:

* created the vocabulary with Terms
* added the term field to the content type

What I managed to get:

* I have a nice URL of that type: "term name"/"node-title". But I need the term alias instead of term name.

I have looked for the answer but no dice so far.

Thank you in advance.

# Answer
Did you try using the \[term:url:path\] token? This should grab the aliased path, there is also the \[term:url:unaliased:path\] token for getting the unaliased path.
> 0 votes

# Answer
You can use pathauto module module, it is exactly do what you want, look at the pathauto token exists there something like `[term:url:path]` can help you.

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: Warning: Cannot modify header information - headers already sent by
I am getting this Error

> Warning: Cannot modify header information - headers already sent by (output started at /home/aigair1/public\_html/site1/sites/default/settings.php:1) in drupal\_send\_headers() (line 1236 of /home/aigair1/public\_html/site1/includes/bootstrap.inc).
>
> Warning: Cannot modify header information - headers already sent by (output started at /home/aigair1/public\_html/site1/sites/default/settings.php:1) in drupal\_send\_headers() (line 1236 of /home/aigair1/public\_html/site1/includes/bootstrap.inc).
>
> Warning: Cannot modify header information - headers already sent by (output started at /home/aigair1/public\_html/site1/sites/default/settings.php:1) in drupal\_send\_headers() (line 1236 of /home/aigair1/public\_html/site1/includes/bootstrap.inc).
>
> Warning: Cannot modify header information - headers already sent by (output started at /home/aigair1/public\_html/site1/sites/default/settings.php:1) in drupal\_send\_headers() (line 1236 of /home/aigair1/public\_html/site1/includes/bootstrap.inc).

I don't get this when my website in Localhost(Xampp), But When I upload site to web I get this. What's problem ?

Here is the Setting.php file as txt

# Answer
> 2 votes
There is an output in your settings.php file. Maybe a whitespace before `<?php`, maybe you closed PHP tag at the end of your file, can't know without seeing it. Inspect your file carefully.

Be sure to transfer your files in binary mode, and disable all automated conversions your FTP software may offer. Save files as utf8 without BOM, Linux line endings. That's the safest way. If your editor can't do that, use another.

As Daniel Tome correctly pointed out, it may be case of warning turned off on your localhost, not a transfer issue. But the things you need to check are the same either way.

---
Tags: debugging
---


# Question
Title: schema_fields_sql empty on entity_get_info
I'm trying to debug why Drupal Commerce License Billing isn't working on existing install but works fine on fresh install.

The difference I can see between the two when adding a new billing type is after entity\_get\_info is ran (after saving a new type) the clean install has two array elements complete the existing install does not.

Those two elements are "base table field types" and "schema\_fields\_sql".

So for some reason those elements aren't set in the existing install.

Any ideas why those elements wouldn't be populated or where they are set so I can further debug?

Thanks

# Answer
My first guess would be that the cache is somehow corrupted. To fix that you'll need to clear the drupal caches

If that doesn't help you'll need some more in-depth debugging.

For further debugging you'll need some easy way to execute code in your drupal environment. I'd suggest to use `drush ev` or `drush php-script` for that. -- Here is some information on how to install drush if you don't have it installed already.

At this point I think there are only two causes left:

1. entity\_get\_info() only populates `schema_fields_sql` if the `base table` key is present. So it might by that somehow the `base table` is not set. To check that take a look at the return value of `module_invoke_all('entity_info')`. For debugging you'll need to take a look at all modules in `module_implements('entity_info')`.
2. If the original data in `module_invoke_all('entity_info')` includes a `base table` the only other way to corrupt the information is some implementation of `hook_entity_info_alter()`. Use `module_implements('entity_info_alter')` to find all modules you need to check.

If you need further help please provide at least the dump of `entity_get_info()` and `module_invoke_all('entity_info')`.
> 0 votes

---
Tags: commerce, entities
---


# Question
Title: Email notification or several reminders at different time points
I have content where in I have to send the email notification or several reminders at different time points: Ex: After saving content, email should send after 1month. then after 6 months for the same content. then once every 5 years. I have tried with node expiry module but it displays content expiry, and when we run the cron at that time only its able to send the mail,user cant run the cron every time sometime he may forget though.

Also I tried with rules schedule but I am not getting exactly what I want like i cant send the email according to time interval, also how to send mail without running the cron. can any one know how to resolve this issue.please help me.

# Answer
You need to use rules and scheduler module which is work with rule to send mail at period of time.
> 0 votes

---
Tags: rules
---


# Question
Title: Views data export remove tags from xml output
I want to remove `<no-name>` tag generated by views data export on xml output Any ideas please?

I have already tried to override template output for the field but no results :(

# Answer
> 1 votes
I have found the problem, i was overriding the template but with a the wrong code, i was using the alternative style template with these variables:

```
<?php print $header ?>
<?php print $body ?>
<?php print $footer ?>

```

Instead these should be used :

```
// Short tags act bad below in the html so we print it here.
print '<?xml version="1.0" encoding="UTF-8" ?>';
?>

<<?php print $root_node; ?>>

<?php
/**
 * @file views-view-table.tpl.php
 * Template to display a view as a table.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $rows: An array of row items. Each row is an array of content
 *   keyed by field ID.
 * - $header: an array of headers(labels) for fields.
 * - $themed_rows: a array of rows with themed fields.
 * @ingroup views_templates
 */
?>
<?php foreach ($themed_rows as $count => $row): ?>
  <<?php print $item_node; ?>>
<?php foreach ($row as $field => $content): ?>
    <<?php print $xml_tag[$field]; ?>><?php print $content; ?></<?php print $xml_tag[$field]; ?>>
<?php endforeach; ?>
  </<?php print $item_node; ?>>
<?php endforeach; ?>

</<?php print $root_node; ?>>

```

I'm posting so maybe it will be helpful for someone else.

---
Tags: views, importing-exporting
---


# Question
Title: How do I add watermark to the image with insert module
I use the combination of Wysiwyg and Insert modules to insert image.

How do add watermark while upload the image?

Can the watermark selected in certain taxanomy?

# Answer
Your question is threefold:

# Adding a watermark

For this, I suggest using ImageCache Actions module. Of the effects it provides, first one is:

> * Watermarking - a much requested addition that enables you to place any image anywhere over a source picture, with alpha transparency

# Selecting watermark

Image field does not know about taxonomy field when it decides how to render it's content. You could hack it together in your template. I would rather go for Formatter Field \- not exactly what you described, but use case on module page seems to fit your needs:

> For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.

# Preventing original image from being downloaded

Drupal modifies user-provided content on display, not on save. This means your original image will be up there, without watermark. Image Style Access claims to be the solution:

> This module provides access control for image files. Each access configuration can be set to allow or deny access to images and their derivatives by:

Disclaimer: I never used this one .
> 1 votes

---
Tags: media
---


# Question
Title: How to bind javascript to ctools modal load
I have a ctools modal popup that has no Drupal generated form but an external iframe that loads a form into ctools modal. I have some jQuery codes to be invoked when the iframe gets reloaded (ie. to assume external form gets submitted).

This jquery code initiated and works fine with a normal page(without ctools) while javascript has been added by `drupal_add_js()`.

How can I do the same with cTools?

```
// MENU
function dw_common_menu() {
  $items['download/%ctools_js/register'] = array(
    'title' => 'Register',
    'page callback' => 'dw_common_ajax_download_register_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}
// Page callback
function dw_common_ajax_download_register_page($js = NULL) {
  /*
   * $sess_key : create a unique session key if not exists;
   * @TODO : instead of md5(REQUEST_TIME) use some other random function as multiple users
   * might access at a same time.
   */
  $output = "";
  $iframe_source = 'http://example.com/cn/iframe.form.php';
  $output .= '<iframe id="site-contact-us" src="' . $iframe_source . '" frameborder="0" scrolling="no" width="232" height="378"></iframe>';
  // Attaching jquery iframe event load in the ctools output itself.
  // The script from files are not invoking as window.load() doesn't takes effect in ctools window.
  $jsscript = "";
  $jsscript = 'jQuery(document).ready(function() {
    (function is_key_authorized(){
      alert(\'sd\');
    }
      });
    })();
    is_key_authorized();
    });';
  $output .= '<script language="javascript" type="text/javascript">' . $jsscript . '</script>';
  // Fall back if $js is not set.
  if (!$js) {
    return $output;
  }
  ctools_include('modal');
  ctools_include('ajax');
  return ctools_modal_render('Register', $output);
  exit;
}

```

Here I am trying to concatenate `<script>` to ctools modal output as `drupal_add_js` not helping to load.

# Answer
> 1 votes
I know this is an old question, but maybe this answer can help someone - I know I searched for an answer for a while.

I had a similar issue, I wanted to execute some javascript when a specific page of mine was rendered by ctools modal.

I found the answer in the help folder of the ctools module ctools/help/modal.html :

> If you need to do more than just render your modal, you can use a CTools $commands array. See the function ctools\_modal\_render() for more information on what you need to do here.

How to apply that to this situation: you need to grab the contents of the very small `ctools_modal_render()` function and use it to add commands to the array of commands that is executed in the function. This is the function:

```
function ctools_modal_render($title, $output) {
    $commands = array();
    $commands[] = ctools_modal_command_display($title, $output);
    print ajax_render($commands);
}

```

This is what my snippet looks like in my page - I wanted to add a body class among other things, so I could style the `#modalBackdrop` for the modal overlay based on context, so here's my modified page function:

```
function gc_alterations_modal_page($js=null){

    $page = array();

    $page['search-results'] = array(
        '#markup' => '<p>My Markup</p>'
    );

    if( $js ) {
        // Required includes for ctools to work:
        ctools_include('modal');
        ctools_include('ajax');

        // alternate to using: ctools_modal_render('Search', $page);
        $commands = array();
        $commands[] = ajax_command_invoke('body', 'addClass', array('myclass-modal'));
        $commands[] = ctools_modal_command_display('Search', $page);
        print ajax_render($commands);
        return;
    }

    return $page;
}

```

---
Tags: 7, ajax, chaos-tool-suite
---


# Question
Title: Can we use Deployment Module with multi DB Drupal Site or Cross DB Connection Drupal Site?
I have scenario in which I am using Cross DB connection on my Drupal 7 Site, I specified my DB connection in settings.php file. Second DB is used as a source db.

Can I use Deployment Module to deploy updates on my default drupal DB only or can also deploy updates on second DB too?

# Answer
> 0 votes
I tried and got this solution, sharing with you all

While using hook\_update\_N() in your deployment module - .install file, you have to active the DB for which you want to deploy the changes. I tried it on my server and it works, I am sharing a piece of code, have a look:

```
function hook_update_N(&$sandbox){
db_set_active('dbsourcekey');
variable_set('clean_url', 0);
variable_set('site_403', 'access-denied');
db_set_active('default');
}

```

---
Tags: 7, hooks
---


# Question
Title: One click upload setting not able to save
I want upload file enable to upload image from my system for that i have installed ONE CLICK UPLOAD plugin for drupal and using Ck editor. now i have to change preference setting for upload button but when i changed toolbar buttons its not saving my changes and i am not able to add that upload button to my editor. please guide if anybody has any solution. my setting path for drupal ch editor is:: module \> ck editor \> edit/config \> **Editor appearance**

# Answer
why don't you use drupal image field for this. You can use add multiple image with drupal core cck image or you can install contrib module multiple image widget. You can be use to display on page or using views can be display.
> 0 votes

---
Tags: 7, commerce, wysiwyg, views
---


# Question
Title: integer field select list with min and max value
I would like to have integer field that ranges from 0 to lets say 100000 with "select list" widget. It doesn't have to have keys i just don't want to type 10000 numbers in field settings of "List integer" field. If I select integer field type it offers min and max but there is no option to have "select list" widget. Am I missing something obvious?

# Answer
I went with creating these options in Excel with simple `B1=A1+1` and then copy and paste that column - works well
> 0 votes

# Answer
It may not be the best way to do this, but it might work for you... you can set up the field as a list and leave it empty, then use a PHP script to populate it, EXAMPLE being your field name:

```
for ($i=0; $i<100000; $i++) {
      // Get the field info
      $info = field_info_field('field_EXAMPLE');
      // Get a reference to the values
      $values = &$info['settings']['allowed_values'];
      // Manipulate the values in some way, e.g.
      $values[$i] =  $i;
      // Save the field
      field_update_field($info);
}

```

Then you should be able to see the value listed under your field's values (under admin/structure/content/types/YOURAPGETYPE/fields). You can also use this in the future if you need to add more values, just remove/modify the for loop. I can't take credit for this code, I found it here on SE but just can't remember where.
> 1 votes

# Answer
Where can I put that code? Is it in hook\_form\_alter?

This is for to turn a text field into a drop down on view.

Can be seen here for the ages from and to:

age to and from drop down needed: can be seen at www.vuxi.com
> 0 votes

---
Tags: 7, entities
---


# Question
Title: What hook_form_alter code do I need to change an exposed filter from a text field to a select box search?
I have a view that has an age to and and from fields, and others also that I want TO and FROM.

These are integer fields, so drop down select doesn't work, better exposed filters is also not an option.

What CSS, or Java script can I put in the Hook\_form\_alter to make this work?

Website that has the form is www.vuxi.com

# Answer
If you would like to go for specific implementation using hook alter this would be great option.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
      // alter your exposed form here
      $addition[$field_name] = array(
        '#attributes' => array(
          'class' => array(
            // you can define you class overhere
          ),
        ),
      ),
    }
  }
}

```
> 0 votes

# Answer
You can change textfield to select box using following code

```
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "your view name"  ){
    $options = array('your options');
    $form['your field name']['#type'] ='select';
    $form['your field name']['#size'] = null;
    $form['your field name']['#default_value'] = '';
    $form['your field name']['#options'] = $options;
  }
}

```

Change the field attributes as your field attributes.

Hope this will help you...
> -1 votes

---
Tags: javascript, theming, views
---


# Question
Title: How do I display a search result message that includes filter criteria?
I have a view to display nodes, with many filters and sorting conditions; that it gets confusing. I want to display the effective filters somewhere, for example *refined by X* or *sorted by Y*. is there any way to print the active filters?

for instance consider I have mobile shop, with a view to list phones.there are lots of fields that user can refine using exposed filters. I want at top of page print a message like:

*showing phones with X Gb ram and Y screen size and Price Z.*

# Answer
I'm not sure I understand your question. You may have a look at :

> This module provides a themed function called `get_exposed_filter_output()` which print out the values of the exposed filter used in a view.
> 1 votes

---
Tags: 7, views
---