# Question
Title: Drupal commerce change quantity textfield in cart view to selectbox
Is there a way to change the quantity widget in the Drupal Commerce cart view from a textfield to a selectbox? And then refresh the page when the selectbox is changed without making the user press the **Update cart** button?

# Answer
> 1 votes
```
<?php
/**
 * Implements hook_form_alter().
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
 if (strpos($form_id, 'commerce_cart_add_to_cart_form_') === 0) {
   if (isset($form['quantity']) && ($form['quantity']['#type'] == 'textfield')) {
     $form['quantity']['#type'] = 'select';
     $form['quantity']['#options'] = drupal_map_assoc(range(1,10));
     $form['quantity']'#default_value' => 1,
   }
 }
}

```

?\>

---
Tags: entities, commerce
---


# Question
Title: Rule for allowing purchases based on country
I'm running a commerce shop where we're gonna sell stuff we don't have worldwide rights to.

By using the countries module I've ticked of which countries we can sell each product in by having a countries field on products. (see screenshot below).

I'm thinking it must be possible to make a rule banning to sell a product in a territory that hasn't been ticket of. It should be the billing country of the customer that needs to be validated against what countries the product is sellable in.

Any ideas on how to configure a rule (or another solution) that does this check?

Cheers

# Answer
> 1 votes
You can use Smart IP to determine the location of the user and with the help of drupal views, you can filter the products not available for sale on that country.

That means only the products which are OK for sale in that country will be displayed to the user..

---
Tags: commerce, rules
---


# Question
Title: In a drupal commerce, how to use the same picture for every size attribute
I have a dresses drupal commerce. I have 45 dresses in différents colors and size.

My problem is that I have the same picture for every size.

My product variation is composed of a sku,price,color,size,image.

As You can see , I have the image in the product variation. Mean that I need to reselect the image for every color,size variations.

Any Idea on how could I do this?

Thanks

# Answer
> 0 votes
If you're using commerce feeds, just use the same url to the same image on your server; or manually upload the same image for each!

# Answer
> 0 votes
Take a look at Commerce Option and Commerce Product Attributes

---
Tags: commerce
---


# Question
Title: not able to map all my product Attributes in commerce feeds
I'm using Feeds commerce to import all my product variation.

Here is my product variation definition

1. SKU
2. Price
3. Color
4. Size
5. Images

In the Feed Importer, I'm not able to map the Color,Size and Images. Anybody know why theses fields attribute is not showing up in the mapping dropdown.

Thanks

# Answer
> 0 votes
https://www.drupal.org/node/1031064 Try the dev version.

I had the same problem and after updating to the dev version all the missing fields were back. Seems there was a bug

---
Tags: commerce, feeds
---


# Question
Title: dblog not working, page shows a 500 Internal server error
My problem starts in a contact form with an upload box, it does everything right and sends the email, except that, on upload it shows:

> Warning: strtr() \[function.strtr\]: The second argument is not an array in syslog\_watchdog() (line 105 of syslog/syslog.module)

So I found this post to resolve my problem above, but it just showed me another problem, a problem with dblog, the page shows me a 500 error, I can't access it.

I couldn't find any help to solve this matter so if anyone knows some way to figure out what is causing this, I would appreciate it.

# Answer
This sounds like the incorrect watchdog data was saved to the database. Truncate the 'watchdog' table that contains your dblog messages in your database and you should be good.
> 1 votes

---
Tags: log-messages
---


# Question
Title: How can I make a Menu Block not auto-expand the current page's menu links?
I want my menu block to decide whether to show link children based *only* on whether the menu link (or the entire menu block) is set to "Expanded", *not* whether you're currently on the same page as the link that has children. What's the best way to do this?

# Answer
I'm currently doing this with `hook_menu_block_alter()` *calling itself recursively:*

```
function THEME_NAME_menu_block_tree_alter(&$tree, &$config) {
    if($config['expanded']) {
        return;
    }

    foreach($tree as $link_key => &$link) {
        if(!empty($link['below'])) {
            if(!$link['link']['expanded']) {
                $link['below'] = array();
            } else {
                THEME_NAME_menu_block_tree_alter($link['below'], $config);
            }
        }
    }

    unset($link);
}

```

But this feels super sketchy and I'm not at all confident that it's the best solution. I could break the `foreach()` into a separate recursive function, but that hardly seems different, other than my general icky feeling which I'm not sure there's even a logical reason for me to have.
> 0 votes

---
Tags: routes, blocks
---


# Question
Title: Add unique class to each link outputted by views
I'm using views to output a list of links (fields). I can type in an url and a text and the text becomes the link text that goes to the url. Now I want to be able to add a unique class to the link when I add it from the backend. Or have a unique class/ID added to it by default, that is also fine.

How can I do this?

# Answer
Go to Theme information link in your view, create a new

```
 views-view-fields.tpl.php

```

http://api.drupal.org/api/views/theme!views-view-fields.tpl.php/7

there you could assign a dynamic value from your query result to $field-\>class or add another custom wrapper to each field or use http://api.drupal.org/api/views/theme!views-view-field.tpl.php/7

for this field only
> 1 votes

# Answer
According to this post, it is a good idea not to use templates for individual fields for performance reasons. I also found this very helpful post on how to change the output of a views field dynamically. These posts are older, but I think they are still valid.

Now for the problem at hand. I was able to change the class(es) used on a view link field as follows (with help from the above post):

```
function mytheme_views_view_field__myview__mydisplay__myfield(&$vars) {

    $path = parse_url($vars['field']->last_tokens['[field_foo]'])['path'];
    $path = drupal_get_normal_path(substr($path, 1));

    if ($path == $_GET ['q']) {

        $vars['field']->options['alter']['link_class'] = 'foo_1_class';

    } else {

        $vars['field']->options['alter']['link_class'] = 'foo_2_class';

    }

    return $vars['field']->advanced_render($vars['row']);
}

```
> 1 votes

# Answer
If you click on the Field (in the view), go to STYLE SETTINGS. Here you can add classes and all that good stuff.
> 0 votes

# Answer
This can be done by providing a custom theme function for theming all links. In your theme's `template.php` file, create this custom theme (don't forget to update the function name):

```
/**
 * Overrides theme_link() to custom classes.
 */
function arch_link($vars) {
  // static counter to track the number of links on the page
  $counter = &drupal_static(__FUNCTION__);
  if (is_null($counter)) {
    $counter = 0;
  }

  // get a backtrace of all function calls leading to this point
  $bt = debug_backtrace();

  // try to identify a views file in the backtrace
  $is_views = FALSE;
  foreach ($bt as &$item) {
    if (isset($item['file']) && strpos($item['file'], 'views/views.module') !== FALSE) {
      $is_views = TRUE;
      $counter++;
      break;
    }
  }

  // add our unique class
  if ($is_views) {
    $vars['options']['attributes']['class'][] = 'views-' . $counter;
  }
}

```

Reliably identifying a link that's generated by the Views module is very hard. The only immediate thing I can think of is checking for a Views file in the backtrace callback, which is what the code above does. This does not guarantee that the link is from Views, but it does mean that Views was at least involved in the process of getting to that link. Also, `theme_link()` gets called for every link that passed through Drupal's `l()` function so you want to be really careful about not doing any slow operations here. Doing the check for the Views file above is a bad idea (performance-wise). I would remove that entire chunk of code, and just go with a unique class for every link on the page - I think that should work for your needs.
> 0 votes

---
Tags: views, theming, navigation
---


# Question
Title: Devel themer not working (cant see the checkbox)
I want to see from where different elements are coming from. Theme Developer module does this, but I cannot see the checkbox in the lower left of the page. It was working earlier but it isnt now, i am using drupal 7.

Anyone seen this issue?

# Answer
Setting Javascript Aggregation in performance options solved the problem for me. Found the solution on this thread - http://drupal.org/node/1790402
> 2 votes

# Answer
1. Check to see if the module is still enabled.
2. Clear the cache.
3. Check to see if the currently logged-in user has appropriate permissions to see devel\_themer info.

It's likely #3.
> 2 votes

# Answer
It seems that devel\_themer module is not compatible with the latest version of simplehtmldom API.

On the drupal devel\_themer project page is announced:

**NOTE**: Currently, Theme Developer does not work with the latest version of simplehtmldom API. You must use simplehtml API version 7.x-1.12 if you want Theme Developer to function properly.

You can download version 7.x-1.12 on the drupal simplehtmldom API project page
> 1 votes

# Answer
In my case, this link works for me.

It's because the logo path is not found and there are error script in my js.
> 0 votes

---
Tags: theming
---


# Question
Title: I only want to modify one tpl.php for a theme, do I need to copy the base theme?
I only need to have one tpl.php added to a theme,but the theme I am using is not my own. If I still want to have this theme as my "base" and then create my own theme with the tpl.php using a theme suggestion I want, how do I get this to work.

I have tried setting the base theme as the default and then creating my own theme with the tpl.php I want and enabling it, but it isn't working. If this is the correct way to do this, what is the minumum needed in the `.info` file and the folder for this to work?

# Answer
> 1 votes
The minimalist amount you need for a subtheme info file are the 2 required keys, `name` & `core`, plus the declared base theme key, `base theme`.

If you a create info file with those keys, copy over the tpl.php (e.g. **page.tpl.php**) from the base theme, modify it, flush caches (to rebuild the theme registry), and use the ***Enable and set default*** from the theme administration page, you should have a working subtheme.

See the d.o. docs on creating a subtheme for more info.

---
Tags: theming
---


title: Creating Omega sub theme manually

text:
# Question
Title: Creating Omega sub theme manually
I'm trying to create a functioning sub theme of Omega 4.4. I've worked with Drush before with it, but the site is on a host that I'm not administrator of. I've tried the Drush Webservice module but not succeeded in executing the Omega Wizard. In short, the Omega Wizard may be extremely helpful, but I can't get it to work.

Next, I've tried to manually create a sub theme using the instructions here. However, the results of this is a theme catalogue in the Themes-folder, but the theme not showing up in Drupal. Perhaps I'm using the wrong instructions for the wrong version of Omega?

Anyhow, does anyone have instructions for how to install an Omega 4.4 sub theme manually for Drupal 7?

# Answer
This documents manually copying the default starterkit subtheme in Omega 4.4. The instructions are similar for both "dusty" and "default" starter kits. Note that the "default" theme has libsass, and has less files then "dusty."

* **Dusty:** the original omega front-end set up, which is becoming increasingly outdated.
* **Default:** a more contemporary subtheme, front-end development wise. This is the better option.

Note: since I use a simple, one-word theme name in this example I can replace THEME-placeholders with one value. If you wish to have a more complex subtheme name, consider this array from the drush omega subtheme function:

```
'/{{ THEME }}/' => $machine_name,
'/{{ THEME NAME }}/' => $name,
'/{{ THEME SANITIZED }}/' => str_replace('_', '-', $machine_name),
'/{{ THEME CAMELCASE }}/' => $camel,
'/{{ THEME CAMELCASE LOWER }}/' => lcfirst($camel),

```

Prerequisite: Your theme's name. I'm using "mytheme" Substitute mytheme with your theme name.

1. Copy `themes/omega/omega/starterkits/default` (or `dusty`) to `themes/mytheme`
2. Copy `default.starterkit.inc` to `mytheme/mytheme.info`
3. Changes to `mytheme.info`
    * Change the `name` value to `'mytheme'`
    * Insert `base theme = omega` to line 3
    * Change the theme file names from `{{ THEME SANITIZED }}` to `mytheme`
    For example - from:
    `stylesheets[all][] = css/{{ THEME SANITIZED }}.reset.css`
    To:
    `stylesheets[all][] = css/mytheme.reset.css`
    * Change the scripts name to css/mytheme.behaviors.js
    * Add regions info:
    ; ========================================
    ; Regions
    ; ========================================
    regions\[branding\] = Branding
    regions\[header\] = Header
    regions\[navigation\] = Navigation
    regions\[highlighted\] = Highlighted
    regions\[help\] = Help
    regions\[content\] = Content
    regions\[sidebar\_first\] = First Sidebar
    regions\[sidebar\_second\] = Second Sidebar
    regions\[footer\] = Footer
4. Update theme name in files:
    * package.json: `{{ THEME }}` to `mytheme`
    * template.php: `{{ theme name }}` to `mytheme`
    * theme-settings.php: `{{ THEME }}` and `{{ theme name }}` to `mytheme`
    * preprocess/page.preprocess.inc: `{{ THEME }}` to `mytheme`
    * process/page.process.inc: `{{ THEME }}` to `mytheme`
    * sass/README.md `{{ THEME SANITIZED }}` to `mytheme`
    * The following renames are in `dusty` only:
        + `.ruby-gemset`
        + `bower.json`
        + `libraries.make`
5. Rename files as necessary:
    * Rename css files to `css/mytheme.reset.css` (default subtheme only) and `css/mytheme.styles.css`
    * Rename scss files to `sass/mytheme.reset.scss` (default subtheme only) and `sass/mytheme.styles.scss`
    * The following file-renames are in `dusty` only:
        + Rename css files to `css/mytheme.hacks.css`, `css/mytheme.no-query.css` and `css/mytheme.normalize.css`
        + Rename scss files to `sass/mytheme.hacks.css`, `sass/mytheme.no-query.scss` and `sass/mytheme.normalize.scss`

And there it is:

I've created a github of that shows the comparitive starterkit to wizard-created subthemes. Using this link, you can see all the necessary modifications you'll need to make, for dusty here or for default, here

I've updated this document out of pure curiosity. If I were in your situation, however, I would simply run the omega-wizard on my local dev environment, and push the theme to my server.
> 1 votes

---
Tags: drush, theming
---


# Question
Title: Configure Australian GST Taxes on Commerce Kickstart 7.x-2.14
I would **like step-by-step instructions as to how to configure Australian GST Tax on a Commerce Kickstart site,** if possible using configuration only.

The business rules are:

**Primary Objevctives**

* Australian GST tax is 10%.
* It has to be included in the quoted price. So an item that is quoted as $11 would contain $1 of GST.
* The amount of contained GST has to be displayed as a separate item in the bill.
* It is only applied to orders being sent to an Australian shipping address. This includes the shipping cost itself, which is GST-free for orders going overseas.
* There can be GST-free items, which don't incur GST whether they are sent overseas or not.

**Secondary Objectives**

* Related to the third item above, technically one is not meant to show separate "(tax-free) Subtotal" and "Included GST" rows but for the time being I'm willing to ignore this legal requirement.
* Somewhat related, instead of just removing the GST for overseas orders I would prefer to still show the contained GST amount but have the line item as something like "GST (removed)" and then not have it included in the calculation. My gut feeling is that these two secondary objectives are related.
* There seems to be an issue that sometimes crops up if I'm testing within the one browser and it remembers my previous shipping address, so that when I change to an overseas shipping address between orders it doesn't update as I would have expected. Might be a bug in Commerce though, and I'm expecting this to be an edge case.

My basic strategy so far has been:

* Do a clean install of the latest Commerce Kickstart via Aquia Desktop
* Write out a strategy of how I'm going to implement the tax
* Implement using a combination of things based on Randy Fay's Conditional Tax video, commerce\_australia module, various other patches/tax removal modules/etc that are buried in drupal.org
* tweak until I realise that I'm no closer. Pull out hair. Take a walk and try to come up with another strategy. Rinse and repeat.

Also, is anyone able to give me a clear answer to **what the difference is between how the tax is applied in Rules as opposed to if I access it from Taxes--\>Configure Components?**

Apologies for the long post but I'm honestly at my wits end here. I can give more information on what I have tried so far but I'm worried I may pollute the responses.

# Answer
> 0 votes
Here is a module maybe is useful.

> The Commerce Australia module provides a number of customisations for Drupal Commerce (http://drupal.org/project/commerce) that allow it to be better suited for deployment in Australia.
>
> Most notably, these include basic currency formatting for Australia and workable GST (Goods and Services Tax) rules.

https://www.drupal.org/project/commerce\_australia

---
Tags: commerce
---


# Question
Title: Exposed filters drop down select translated but not displaying on view
The field items are properly translated but they don't show up in the views exposed filters.

Can be seen over here on the French page:

can be seen here: http://sandbox.vuxi.com/fr/node?qt-qt\_index\_search\_b\_a\_u=1#qt-qt\_index\_search\_b\_a\_u

# Answer
> 0 votes
For translating exposed filters, you need to enable all translation modules FIRST. And THEN create your views.

Because there is a multilingual option to pick filters, the translatable one.

User: Example (field\_example:language) (translated) Language - Appears in: user:user.

So if you want a multilingual site, install all translation modules FIRST, and then create your views with multiple filters.

---
Tags: views, i18n-l10n
---


# Question
Title: Display summary of entered field values and permit user to cancel submission
Versions: Drupal 7.12 Webform Module 3.17

I have webform that has multiple pages (using pagebreaks). When the user completes the final page I would like to display a summary of the entered information so that the user can double check it before submitting it.

My first thought (after much searching) was to:

* Use the ***hook\_webform\_submission\_presave*** hook to catch the submission before it is saved
* Display the field values
* If the user decides not to submit the form cancel the submission

However I am having difficulties applying the above theory to reality.

1. Is this possible?
2. Is the above method the best approach (if it is, how do I achieve it)?
3. Or is there a easier/better way to achieve this?

Any help would be appreciated......Kevin

# Answer
> 2 votes
There is a feature request for a "summary" component for Webform in the Webform module issue queue here: http://drupal.org/node/435232, but there isn't any movement yet on actually making a built-in summary component in the core project.

In that issue, dealancer notes that he has already added his code to the http://drupal.org/project/webform\_bonus project, which allows you to add a summary component directly to your form in the same way you would add a textfield or any other component type. Install that module and add a summary field to your form, selecting which fields you would like to include in the summary. If you would like it on its own page, make sure to add a pagebreak component first.

# Answer
> 0 votes
This does not work for 6.x The summary component does not show the values but only the field names at the end of the form and just above the 'Submit' button. The 6.x version is broken and unusable

---
Tags: webforms
---


# Question
Title: How do I use rules scheduler to disable and enable a commerce product entity based on certain date fields?
I have a commerce product type (entity not display node) with two date fields (enable\_date and disable\_date). What are the steps to create a rule/component and use rules scheduler to schedule these to disable and enable these products, based on the value of these two fields?

The use case is that I have an event node (product display) that needs to always be viewable but the attached registration (product entity) needs to be disabled on a specific day/time. i.e. Registration is now closed, but users can still see the event info, like location, map etc. Using rules scheduler I am sure I can do this. I have tried with mixed results but I am still learning the rules module. Any help would be appreciated.

# Answer
First create a Rules component for setting the status of a product.

1. Go to *Configuration* -\> *Workflow* -\> *Rules* -\> *Components* -\> *Add new component*.
2. Create an *Action set*.
3. Give the component a suitable name, such as `Set product status`.
4. Create a parameter of type *Commerce Product*, label `Product`, machine name `product`; and another of type *Truth value*, label `Status`, machine name `status`.
5. Add action: *Set a data value*
6. For *Data*, use the Data selector to select the product parameter's status (`product:status`).
7. For *Value*, use the Data selector to to select the status parameter (`status`).
8. Save

You now have a component that can be scheduled. Next you need to trigger the creation of the scheduled action. I'm going to describe the process for enabling the product; you should be able to create another rule for disabling easily enough following the same method.

1. Go to *Configuration* -\> *Workflow* -\> *Rules* -\> *Add new rule*
2. Choose the triggers *After saving a new commerce product* and *After updating an existing commerce product*.
3. Add the condition *Entity has field*.
4. For *Entity*, use the Data selector to choose commerce-product as the entity.
5. For *Field*, use the dropdown to select your start date field.
6. Add condition *Data value is empty*.
7. For *Data to check*, use the Data selector to choose the start date field.
8. Check the Negate checkbox (we only want to proceed if the field is *not* empty)
9. Add another condition *Data comparison* and select the start date field *is greater than* `site:current-date`
10. Add an action *Schedule component evaluation*.
11. For *Component*, choose the component you created earlier.
12. For *Scheduled evaluation date*, use the Data selector to get the start date.
13. For *Identifier*, choose something like `Enable product [commerce-product:product-id]`
14. For *Status* check the box.
15. For *Product* use the Data selector to choose `commerce-product`.

Then in order to remove a scheduled action if the date's removed from the field:

1. Follow steps 1-7 (but not 8!) immediately above to create a new rule.
2. Add an action *Delete scheduled tasks*.
3. For *Component*, choose the component you created earlier.
4. For *Identifer*, use the same string you used before.

And another rule to delete the scheduled action when the product's deleted would be good too.

I quickly gave that a go and it seems to work for me. Let me know if you have any problems.
> 12 votes

# Answer
Here is something I have done in the past and I think will help you retrieve your product ids without having to loop through every single product.

You can use VBO to load a list of entity IDs to your view that you can loop through. You can read how to do that here: http://nodeone.se/sv/node/777

This will allow you to create two views to return the entity ids for your products enabling today and disabling today.

Then create your RULE to fire during cron or something, as long as its once a day.

Add your Action to load a list of entity objects through a VBO display. Add a loop based on that loop parameter List. It defaults to "entity\_list" Add an Action for the Loop to iterate over your entity list which is your product entity to either disable or enable the product. Select Data -\> Set a value

Once you are in the set a value part you will see your "entity-list" data selector pop up and you can set the value for enabling or disabling to w/e you need it to be.

Hopefully this will get you where you need to be, let me know if you get stuck.

Just a slight followup, you can add both VBO views to the single rule. One VBO display pulls all the products that need to be enabled today that you loop through, and then you can create another action to pull the VBO display that turns off the products for today. So this will run every day turning on/off your products and you never have to worry about scheduling anything.
> 1 votes

# Answer
I have also found a good answer of related to this question at Drupal groups. This is really nice discussion about creating rule in Drupal 7. Get the rest of material at https://groups.drupal.org/node/240678 .
> 0 votes

---
Tags: commerce, rules
---


# Question
Title: How do I increase time of slide in jcarousel?
I want to increase the timer of the slide by 4 seconds so that each slide should be visible for 4 seconds. How can I do this?

# Answer
Try this. Click on "*View Transition Advanced Options*" and into "*Timer delay*" set time in milliseconds as shown in below image.
> 3 votes

# Answer
Change the value of auto according to your time

```
$('#jcarousel').jcarousel({
  auto: 3, //delay 3 seconds
  wrap: 'circular',
  animation: 1000,
  scroll: 1
});

```
> 0 votes

---
Tags: views
---


# Question
Title: Showing Forum Topic Count 0 because, content access module conflict with Advanced Forum
In my project I am working with advanced forum. for this I installed module as below.

* advanced forum
* ACL
* content\_access
* chain\_menu\_access

The issue is after adding Forum Topic into forum, the count of topics display zero (0). Help for resolve this issue.

# Answer
> 0 votes
Finally, I find solution for my issue and post it on issue list of Advanced Forum. Also patch is created, and pushed in to future development.

---
Tags: nodes
---


# Question
Title: I need 2 blocks for the same search index, one with email alert and one without
I use the Search API saved searches module to save my search and to get email alerts. I need one more block in the same page, which I need to use for just saving the current search. Can anyone help in this, or with suggesting any other module to get my second block for just saving searches?

# Answer
setting negative value for notify interval will just save the search, without sending any mail alert in search\_api\_saved\_search module.
> -1 votes

---
Tags: search
---


# Question
Title: Add an enddate to my date field programmatically
I'm using the date field contrib module and added it to my custom module which creates a content type and its fields.

I've successfully added a field(+instance) of date with a popupcalendar to my contenttype with a lot of help of this comment. But I can't figure out how to get the end date working. It's only showing a first date, not value2. I've tried screwing around in the field settings by adding `'enddate'=> 1` to no avail.

What setting should I use to get a start AND enddate to work in my field within my module?

Here are the fields I'm using(Its within a field collection which also works fine)

```
//Field collection
array(
    'field' => array(
        'field_name' => 'field_available_periods',
        'label' => $t('Available periods'),
        'cardinality' => -1,
        'type' => 'field_collection',
    ),
    'instance' => array(
        'field_name' => 'field_available_periods',
        'entity_type' => 'node',
        'bundle' => 'accommodation',
        'label' => $t('Available periods'),
        'description' => '',
        'widget' => array('type' => 'field_collection_embed'),
        'required' => 1,
    ),
),
array(
    'field' => array(
        'field_name' => 'field_van_tot',
        'type' => 'datetime',
        'label' => $t('From - Until'),
        'cardinality' => 1,
        'settings' => array(
            'granularity' => array(
                'year' => 'year',
                'month' => 'month',
                'day' => 'day',
            ),
            'enddate' => 1,
        ),
    ),
    'instance' => array(
        'field_name' => 'field_van_tot',
        'entity_type' => 'field_collection_item',
        'bundle' => 'field_available_periods',
        'label' => $t('From - Until'),
        'cardinality' => 1,
        'description' => '',
        'required' => FALSE,
        'widget' => array(
            'type' => 'date_popup',
            'settings' => array (
                'input_format' => 'Y-m-d',
                'year_range' => '-0:+2',

            ),
        ),
        'display' => array('default' => array('type' => 'date_default')),
        'settings' => array(
            'default_value' => 'blank',
            'default_format' => 'short',
            'default_value_code' => '',
            'default_value2' => 'blank',
            'default_value_code2' => '',

        ),
    )
),

```

# Answer
Finally found it by changing the field settings' "todate":

```
'field' => array(
                'field_name' => 'field_van_tot',
                'type' => 'datetime',
                'label' => $t('From - Until'),
                'cardinality' => 1,
                'settings' => array(
                    'granularity' => array(
                        'year' => 'year',
                        'month' => 'month',
                        'day' => 'day',
                    ),
                    'todate' => 'required',
                ),
            ),

```
> 0 votes

---
Tags: 7, datetime
---


# Question
Title: How to grant edit access only to set of users defined in a cck field of a node?
I am trying to restrict edit(node/%nid/edit) access only to users defined in one of the node fields. can I use hook menu alter for node/%nid/edit so i can write a custom access callback or use hook node access to achieve it. One thing to mention here is any user can comment on that node and when they save the comment, I am updating some fields on the node and saving it thru node\_save. What will be the best way to achieve this access restriction.

# Answer
As per me the best way to restrict the edit access would be by implementing `hook_node_access`, something like the following:

```
function MODULE_node_access($node, $op, $account) {
  if ($op == 'update' && $node->type == 'YOUR_TYPE' && $node->field_custom[LANGUAGE_NONE][0]['value'] == 'some value') {
    return NODE_ACCESS_ALLOW;
  }
  else {
    return NODE_ACCESS_DENY;
  }

}

```
> 2 votes

# Answer
I'm not sure if it'll be considered as the *best* way, but a *possible* way to address your question is to use the Rules module, and a rule that is a variation of the rule I included (in export format) in my answer to the question about How to restrict access to a node via node/12 and allow access via a path like content/sometitle?

These are the changes to that rule to make it work for this case also:

* Append `/edit` at the end anywhere there is already something like `node/%`.
* Add a Rules '*Condition*' to verify your "... access only to users defined in one of the node fields".
* Change the "Message" (in the Rules '*Action*') to something that fits your needs.
* Modify the Rules '*Action*' to fit your own requirements, e.g. to issue a redirect to some other page.

Haven't experimented/tried creating this rule (= variation of the rule in the answer I mentioned above). But pretty sure it'll work.
> 1 votes

---
Tags: users
---


# Question
Title: How to organize content via taxonomy, blocks, panels, views?
I am new to Drupal. I have a guitar lessons site that I want to convert to drupal. Guitar lessons are a container that contain exercises, and lessons are categorized - I set up taxonomy). Exercises contain text, and media: audio, video, an image or two. Main image (tab) will automatically be displayed, audio will have link, and video would appear in tab, as would secondary image (fretboard diagram). So the media could be imagined as having its own mini horizontal panel or something below the image. Some audio/video will be designated as accessible to registered users only. On left there would be block that lists exercises in the current lesson. In lesson page there would be navigation (next exercise, etc, as well as a show all exercises option).

Not sure how to create this container-exercises relationship. And since I want people to be able search on exercises by themselves, apart from a lesson, I need a way for exercises to not only be attached to a lesson, but to be categorized and accessed on their own. I suspect taxonomy is the key here.

I have been reading about Panels as a way to control layout without editing themes. Also read about Views and understand the query function they play as well as perhaps display of results. So I understand these will be key. I have set up the exercise content type, adding custom fields. But now I am at a dead end. I don't know the process flow to make Drupal display the content the way I am seeing it in my head. And I don't know to what extent the tools will get the job done vs me having to code. I know PHP very well, CSS so-so, and Javascript so-so. I am trying to avoid coding if possible, except for minor tweaks. From building my site in postnuke some years back and doing an insane amount of coding, I know I don't want to repeat that!

Any tips on how you would go about this design with taxonomy, panels and views (or other tools) will be very appreciated. I would even be willing to hire someone to help me get started (apology if that is against the posting rules!).

# Answer
This is a very broad question Brian, but I think it boils down to 'how should I handle relationships between entities'.

Take a look at the Entity Reference module. With that you can create links between your various nodes so that you can display them on the same page.

For instance let's say your main content type is exercise, on each exercise node you could use the module to create links to a video and a fingering diagram (or several). Then for each other thing you wanted to display on the page, you create a view with a **contextual filter** that looks for the node id of the exercise which is being displayed.

I highly recommend finding some reading or videos on how contextual filters in views works.

Panels makes the handling of contexts a little bit easier in the long run. There's an excellent tutorial on Page Manager.
> 2 votes

# Answer
If you're new to Drupal, you might have a hard time getting your head around the (amazing) Panels module, and things like "context", etc. Don't take my word for it (yet). Instead watch the videos about Learn Page manager, which is an interesting (and amazing) set of videos. They contain various topics related to the Panels module. After you reviewed these videos, you should understand various features that come with the Panels module ... but also its challenges.

Maybe you should give it a try to see how far you can get with any (or all?) of these modules:

* Display Suite (a typical alternative for using Panels).
* DataTables used in combination with Views (especially because of its client side search facilities).
* You might want to check also to what extend the features provided by Organic Groups module might help in your case.

What you probably haven't thought of, but which I think you should look at for sure also, is the Rules and Flag module.

If you'd add taxonomies where appropriate, you could already get pretty far. Probably you'd also want to consider using "Term Reference" fields then. If you do, be aware that some say that *Term Reference* will be deprecated and potentially removed from Drupal (in favor of the "entity reference" field).

# Video tutorials
> 1 votes

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


# Question
Title: How to find which block is causing PHP errors?
I'm cleaning up a Drupal 7 site and currently its spitting out a bunch of PHP syntax errors pointing to some block that is causing it. It doesn't say which block but only says php\_eval() error. So I'm assuming its in a block somewhere.

How would one find the culprit of which block it is that is causing this php error?

https://i.stack.imgur.com/WSJXM.png

# Answer
> 1 votes
It appears to be an error in the php code in some of the blocks. There in no direct way to find out which block is causing the error. But you can find the ids of the blocks inside that page which contains php code by adding the following patch inside modules/block/block.module, just for debugging.

```
diff --git a/modules/block/block.module b/modules/block/block.module
index 48c80d7..d25a497 100644
--- a/modules/block/block.module
+++ b/modules/block/block.module
@@ -243,6 +243,9 @@ function block_block_view($delta = '') {
   $block = db_query('SELECT body, format FROM {block_custom} WHERE bid = :bid',
   $data['subject'] = NULL;
   $data['content'] = check_markup($block->body, $block->format, '', TRUE);
+  if (strpos($block->format, 'php')) {
+    echo "<pre>"; print_r($delta, TRUE); echo "</pre>";
+  }
   return $data;
 }

```

EDIT: Please note, the above code is just for debugging purpose and not meant to be commited. As Molot said on comment, Never Hack Core

# Answer
> 3 votes
The most probable cause of the error is a missing or a mismatched parenthesis in the PHP code you are using in your custom blocks or functions. To solve the missing parenthesis error in PHP blocks or in other areas, the code has to be checked from the beginning to search for it. But it's really hard to check all PHP code. One way to avoid errors is to use proper indentation in the code. Once all the parentheses in the code have been set correctly, **parse error: syntax error, unexpected $end** will be fixed.

**What causes this error?**

In fact, this error means that PHP has finished analyzing your code, but you forgot to close a symbol somewhere in your page or in those that were included. There could be a number of causes:

1. This issue could happen when someone used `<?` instead of `<?php` somewhere, but your server's `php.ini` disables short open tags. Check this line in your `php.ini` \- "`short_open_tag = On`".
2. You forgot to close a quote, so PHP is continuing to analyze your code until it finds the closing quotation mark.
3. You forgot to close a bracket, so from the last opening, PHP considers all the code that follows as part of a block that never ends.
4. You forgot to close a parenthesis, so from the last open parenthesis, PHP considers all the code that follows as part of a specific block (condition, arguments of functions etc) that does not end.
5. You forgot a comma, so for PHP there is an instruction in your code that has no end.

**NOTE:** This means that the problem may not be on the line mentioned in the error message, as the missing symbol could be anywhere after that point.

---
Tags: 7, blocks, debugging
---


title: How do I add a list of members

text:
# Question
Title: How do I add a list of members
I have added users and want to display a list of members as a block in a space on Open Atrium. I have looked in menus and Open Atrium when trying to add content but cannot find anything that will allow me to do this?

# Answer
Theres a widget called "OG members" that could help you.

When in a space, you have this button to personalize the display. Click it then you can add widget (the '+' button). In the new window, you can find widgets that you can add and configure as you need. Theres one called 'OG Members' in the category called (I think) 'Panel panes'. I think this widget is meant to display members of the space you visiting
> 1 votes

---
Tags: routes
---


# Question
Title: Tried to Inline CSS with AdvAgg but still get errors in Google
My Right-to-left site uses clean Bootstrap subtheme and has CDN, Internal caching (including Boost), Minification, Compression and aggregation, but still I get very low grades with all that has to do with **CSS performance**. Therefore I tried to inline all the CSS in my site via AdvAgg (please see image), what helped me in another theme, but not this time...

Is there anything else you think I should try?

---

# Answer
> 3 votes
What you are trying to do with the CSS inlining can only happen when the CSS is coming from Drupal, internal resource. External CSS resources cannot be inlined. If you read at the top of the "Inline CSS/JS On Specific Pages" it says, "This will prevent all local CSS and/or JavaScript files...". I agree that it is somewhat subtle and might need to be highlighted better in the UI that it only works for internal resources.Here is a screenshot of what I am referring to.

The only option you have with external CSS resources with AdvAgg is to move them to the **TOP** of the page. You could move the resource to the bottom of the page via a hook\_alter\_css in a custom module. But seeing this is the bootstrap CSS I can guarantee that will render your website broken.

Unfortunately, you cannot do anything about the CSS file with Pagespeed. You could host the CSS file in your site, but then you would lose the advantage of the CDN, which I see that the rest of your site is not using a CDN. Remember that Google Pagespeed scores are only one of many benchmarks and tests you should use in making a website perform. It is best to compare many different sources of data for optimizing your site (Pagespeed, YSlow, Pingdom Page Test, Webpagetest.org, etc.) And with optimization you have to give and take, it is nearly impossible to get a perfect score because you have to make sacrifices in certain areas. Being this CSS file is on a CDN and it is minified already, the impact to your site is honestly low. If you were to move the CSS to your site so AdvAgg could inline it, it would actually be worse for your site. It is a large CSS file that is critical for rendering your website, a CDN is the best place for it! I personally have found Pagespeed to be unrealistic in it's scoring from time to time.

# Answer
> 4 votes
Your setting for **Inline CSS on specific pages** is wrong. The path you should set is:

```
node/*

```

# Answer
> 0 votes
Inlined CSS is a double edged-sword...

It makes the page load quicker for the first visit to a site as there are no additional http requests to load the styles. However, for subsequent visits it is actually detrimental since with non-inlined css they would then be served up from the browser cache and cause pretty much zero load delay, whereas the inlined CSS adds to the page weight and thus load time of each and every page loaded.

It can be a useful tool to prevent an HTTP request by adding a few lines of CSS to a page but I certainly wouldn't recommend it for inlining hundred or thousands of lines of CSS, unless of course you are expecting the majority of visitors to visit only one page.

I'd say a good aggregation strategy is preferable to prevent large number of CSS files from being loaded on that first page load.

---
Tags: css-js-aggregation
---


# Question
Title: show messages of drupal_get_form loaded forms in custom module
In my case I use drupal\_get\_form in my custom module in order to load forms from other modules and show them combined in one page (menu callback). So in my custom module I have

```
  function mymodule_claim_menu() {
    $items['profile_edit/%user/%'] = array(
    'title' => 'Edit profile',
    'page callback' => 'connections',
    'page arguments' => array(1,2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
    'file' => 'node.pages.inc',
    'file path' => drupal_get_path('module', 'node'),
  );
 return $items;
}

function connections($account,$tab = "profile") {
  $link_output = array();
  $rss_output = array();

  $link_output['linkedin_settings']= drupal_get_form('linkedin_user_enable_form', $account->uid);

  $rss_output['rss_input'] = drupal_get_form('activitystream_accounts_form', $account);

  $output = array_merge($link_output,$rss_output);

  return $output;
}

```

The (simplified) code above works fine except status messages (drupal\_set\_message) not getting displayed when a user submits one of the forms. I realise from the previous posts that it's something with the order but I'm not sure what I can change to make it work. Any suggestions?

# Answer
I'm posting the solution in case anyone else faces the same issue.

This was finally related to the template file. The messages were printed in a section that was not rendered when inside my module page. This tricked me because doing it as admin was actually showing the relevant section but for registered users didn't.

So I just had to add an extra printout of the $messages var in a section of the template that was always rendered to all users.
> 0 votes

---
Tags: 7, status-messages
---


# Question
Title: Integrity constraint violation: 1052 Column 'uid' in on clause is ambiguous
I am using migrate module to transfer data from one site to another here is my query

```
$query = Database::getConnection('db1', 'db1')
        ->select('users', 'u');
$query->leftjoin('field_data_field_user_insti_name', 'insti_name', 'insti_name.entity_id = u.uid and insti_name.bundle = \'user\'');
$query->leftjoin('users_roles', 'ur', 'ur.uid = u.uid');
$query->fields('u', array('uid', 'name', 'mail', 'pass', 'status'));
$query->fields('insti_name', array('field_user_insti_name_target_id'));
$query->condition('u.uid', '1', '>');
$query->condition('ur.rid', '6', '!=');
$query->distinct();

```

than I am getting this error

> Integrity constraint violation: 1052 Column 'uid' in on clause is ambiguous

I found a solution for this problem that i have to add line

```
$this->source = new MigrateSourceSQL($query, array(), NULL, array('map_joinable' => FALSE));

```

After this error is solved, but don't know what this line do, is it safe to use this line

# Answer
> 2 votes
You have to add alias in MigrateSQLMap

```
$this->map = new MigrateSQLMap($this->machineName,
   array(
       'uid' => array(
           'type' => 'int',
           'not null' => TRUE,
           'alias' => 'u',
       )
   ),
) ;

```

---
Tags: database, migrations
---


# Question
Title: Urls without question mark are served with 404 in Drupal 7 with Nginx
I am migrating an Drupal 6 site to Drupal 7. I encountered some behavior, I cannot explain and would like to ask the community.

As I was testing if all urls work, I noticed, that there are urls like `example.com/node&a=b` (without `?`), which return `200` on Drupal 6 site and `404` on Drupal 7 one. (Normal urls like `example.com/node?a=b` are served with 200)

As I understand, these urls are not correct (maybe lost the question mark on copy/paste), but I think it is still better to serve the page, because the main part of the url is correct. Even better would be to redirect to the correct page with `301`.

But I cannot find, if the problem is in the Nginx configuration or if it is a desired behavior on Drupal 7. I am using the Nginx configuration example from http://wiki.nginx.org/Drupal.

Maybe someone could tell, if this behavior (404 on links without question mark is default for Nginx or Drupal 6/7)?

Edit: the malformed links come from access.log, there are some clients, which try to fetch them. Mostly search engines and bots.

# Answer
> 2 votes
After some debugging, I think, I can understand what happens.

Take a look at this Nginx rule from http://wiki.nginx.org/Drupal:

```
  location @rewrite {
            # You have 2 options here
            # For D7 and above:
            # Clean URLs are handled in drupal_environment_initialize().
            rewrite ^ /index.php;
            # For Drupal 6 and bwlow:
            # Some modules enforce no slash (/) at the end of the URL
            # Else this rewrite block wouldn't be needed (GlobalRedirect)
            #rewrite ^/(.*)$ /index.php?q=$1;
    }

```

I'm using the Drupal 7 rule and it tells Nginx to just execute the `/index.php` without any argument handling. Next, Drupal initializes and runs the drupal\_environment\_initialize() function, which calls the request\_path() function. Here Drupal tries to parse the `$_SERVER ['REQUEST_URI']` variable. And of course, here is no special handling for malformed urls, I see in my logs.

I think, that's the difference between my old Drupal 6 install and Drupal 7.

1. Another rewrite rule from Nginx
2. No url parsing by Drupal

Basically the question is not so big, if some search engine is too dumb to create malformed urls, it's not my problem. But I wanted to handle it, so I modified the Nginx config, by adding a rewrite string, which redirects malformed urls:

```
  location @rewrite {
            # You have 2 options here
            # For D7 and above:
            # Clean URLs are handled in drupal_environment_initialize().

            # redirect bad urls like /page&a=b to /page?a=b
            rewrite ^/([^?]*?)&(.+?)=(.+?)$ /index.php?q=$1&$2=$3 permanent;

            rewrite ^ /index.php;
            # For Drupal 6 and bwlow:
            # Some modules enforce no slash (/) at the end of the URL
            # Else this rewrite block wouldn't be needed (GlobalRedirect)
            #rewrite ^/(.*)$ /index.php?q=$1;
    }

```

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


# Question
Title: is it possible to have multiple access callback for a menu item
I am trying to add access callback to already existing access callback for a menu item.

For eg,

`path = [node/nid/edit] with access callback 'AC1'.`

Now is it possible for us to add another access callback to the existing `AC1`? I am thinking of hook menu alter but it wont overwrite the `AC1`.

# Answer
> 0 votes
No, it isn't. Drupal wouldn't know how to treat contradictory results\*.

On the other hand, nothing stops you from calling original function inside your own. If you are unsure what is it, copy it's name to access arguments and use it inside your callback. Don't forget to back up original access arguments in sub array, if needed.

---

* Or rather Drupal devs would need to agree how to treat them, and have a will to bother at all.

---
Tags: routes, users
---


# Question
Title: #default_value not being displayed in form
Here's a function that returns a form:

```
function myfunc($str)
{
    $form = array();
    $form['header text'] = array(
        '#markup' => '<h2>blah blah blah</h2>',
    );
    $form['new_str_value'] = array(
         '#type' => 'textfield',
         '#title' => 'New String Value',
         '#size' => 60,
         '#maxlength' => 128,
         '#required' => TRUE,
         '#default_value' => $str,
    );

    return $form;
}

```

The textfield displays correctly with the right size and label, but it is not populated with an initial value. Any ideas? Should I be rendering or building the form in the function before returning it, or setting the value in `$form_state` ... or something?

Any help much appreciated!

# Answer
> 0 votes
Assuming Drupal 7...

The signature for form functions needs to follow a strict pattern; Drupal will pass along `$form` and `$form_state` as the first two args, and anything else as subsequent args.

So assuming `$str` should be the first custom arg to the form, the signature should look like this:

```
function myfunc($form, &$form_state, $str) {

```

---
Tags: forms
---


# Question
Title: Getting "Fatal error: Class not found" by bootstrapping external script and executing user_save function
I have a problem i've struggled with for a long time, and it's starting to really piss me off, so i hope you can help me.

The thing is i'm writing a custom script (not a module) that needs access to the drupal user object, and it's profile2 fields, so i found out i could use the bootstrapper for this purpose.

Loading fields from the users profile works just fine, but when i try to make changes programmatically (user\_save function for example), it fails with the following error, which makes absolutely no sense to me:

**Fatal error: Class 'Drupal\gmap\GmapDefaults' not found in (root directory)\sites\all\modules\gmap\gmap.module on line 32**

A function that would return this error could be something like this:

```
function custom_add_role_to_user($user, $role_name) {
              // For convenience, we'll allow user ids as well as full user objects.

              // If the user doesn't already have the role, add the role to that user.
              $key = array_search($role_name, $user->roles);
              if ($key == FALSE) {
                // Get the rid from the roles table.
                $roles = user_roles(TRUE);
                $rid = array_search($role_name, $roles);
                if ($rid != FALSE) {
                  $new_role[$rid] = $role_name;
                  $all_roles = $user->roles + $new_role; // Add new role to existing roles.
                  user_save($user, array('roles' => $all_roles)); // <---- This function throws the above error...
                }
              }
            }

```

If i don't call **user\_save()**, everything works just fine, and until now i have been doing fine with direct sql queries, but i need to know why this doesn't work.

I've tried navigating to the GMap class to see what's actually going on at line 32 (Still not knowing why my simple script keeps referring to some random Google Map Module..?)

Here it is:

```
function gmap_defaults() {
 include_once(drupal_get_path('module', 'gmap') . '/lib/Drupal/gmap/GmapDefaults.php');
 return GmapDefaults::getInstance()->getDefaults();
}

```

So why is the bootstrapper calling this random module, and what is wrong with the module first of all???

It seems like it doesn't get to create the namespace required correctly. But i don't see where it goes wrong?

drupal\_get\_path returns the right path... I've tried to put a static path instead, to see if that made any difference... It didn't...

Thanks in advance for your help.

# Answer
> 1 votes
The correct answer could be to also use the necessary namespacing when instantiating the GmapDefaults class:

```
include_once(DRUPAL_ROOT . base_path() . drupal_get_path('module', 'gmap') . '/lib/Drupal/gmap/GmapDefaults.php');

$macro = !empty($field['settings']['gmap_macro']) ? $field['settings']['gmap_macro'] : '[gmap ]';
$map = array_merge(Drupal\gmap\GmapDefaults::getInstance()->getDefaults(), gmap_parse_macro($macro));

```

Note that I also converted the original include to an absolute path based include to make sure the path is correct...

I just prepended the necessary namespace before "GmapDefaults::" and it works.

# Answer
> 0 votes
So i solved it, and i gotta say it is a bit embarrassing...

It turns out i just needed to change the working directory of the script, one level up as i've put it in a subdirectory...

But i still dont understand why its just the google maps module that fails.... well anyway - guess i learned my lesson :)

---
Tags: google-maps, users, external-scripts
---


# Question
Title: Flexible addons for Solr to achieve sorting and filtering
My requirement is to provide end user with an option to sort/filter the search results. This can be achieved different ways but I am unclear to choose one. I found these methods.

1. Using facetapi - I can filter results, not sure about sorting.
2. Using apachesolr\_sort - I can group/sort results, not sure about filtering.
3. Using apachesolr\_views - I can show my results more flexible this way. But this doesn't seem to support sorting https://www.drupal.org/node/443410.
4. Using search\_api and search\_api\_solr - This method is more preferred and flexible to group/filter/sort results. But I am worried about heavy size of these modules.

Can someone suggest me to achieve the most flexible (and less resource consuming) method of sorting/filtering results by any combination of the above modules.

Thanks!

# Answer
Search API includes Views integration out of the box. Definitely you will need Facets Api. this combination is the best for Solr integration with Drupal. Here is a great screen-cast that might help.
> 1 votes

---
Tags: views, search
---


title: How to clone menus in Drupal?

text:
# Question
Title: How to clone menus in Drupal?
I want to implement conditional menus, where different options appear depending on the user's role.

In Display Different Menu links an content depending upon user role or user logged in, user "nevets" suggested making multiple menus each with the appropriate links, and then restricting the visibility of a particular menu by user role.

In my case, the different menus might share a lot of links, so I thought of cloning the links to avoid having to re-enter them when making the second and subsequent menus.

I found the Menu clone? module, but the project page warns:

> **D7: This module is still in beta and is a complete rewrite of the original port.** It is never recommended to use beta versions on a production environment. Please keep a backup of your database to avoid problems later on.

How can I achieve this? any suggestions?

# Answer
> 4 votes
If you want to be professional, use Menu clone module all right. Simply do it on development copy of client's site.

It's never a good idea to use beta modules on production site *without testing* them on devel and stage, but if you do test and they work for your particular site, it's usually safe\*. And if all you need are cloned menus, you can use it and then uninstall before stage -\> production migration so it will never even appear on your production server.

---

* As safe as your tests were good.

# Answer
> 3 votes
I am not sure that cloning menu's would fit your use case, this sound more like the job for Context Reaction Menus.

Cloning Menus becomes cumbersome when you have to remove or omit a menu link in **all** menus if it ever becomes irrelevant.

It's probably better to set the context for specific link (i.e. hide this link for Scenario B,C and E). This is especially useful if you want to present different menu content for different parts of the website.

# Answer
> 0 votes
Using the Content Access module may help to finetune your content (nodes), and their corresponding menu items. For any node for which you want a menu item to be shown to selected roles only (no matter in which menu), just use the Content Access rules to the appropriate roles. For those who do not have that role, the corresponding menu item will not be shown.

You can set such access for an entire content type, or for individual nodes. Which implies other possible options to implement what you're trying to do. Not sure if it applies in your case, but you could imagine using multiple content types (with corresponding content access settings), so that based on the content type you use to create a node, it is yes/no shown to specific roles in your menu block. Your content editors would probably love such an easy rule to dynamically change the menu content also.

If the menu items relate to views, then set the views access rules for each view also. Again, only those who have access to the view, will have a menu item that shows up.

**Note**: True, the Content Access module only has a **Beta** version for D7, but right now there are over 70K users using this version. Therefor I think "Beta" is not a valid release qualifier for that version anymore, because *+70K users can't be wrong*, right?

---
Tags: 7
---


title: creating a static front page

text:
# Question
Title: creating a static front page
Please bear with me, I am new to Drupal (I've been adding content for 3 years, now been asked to edit some structural aspects of a site.)

I've been asked to add a static frontpage/homepage to an existing Drupal site with no menus, no headers. This would be a very basic HTML page with an image and 2 links which connect to English and French versions of the main Drupal site.

Is the best way to use a module? I see there is a module called Front Page, but it hasn't been updated in almost 2 years (maybe this is normal?). Is there a more basic way to get a static front page in Drupal, without installing another module?

Also, I am concerned about what will happen to the URL of the current front page if I override it with the Front Page module.

Thank you!

# Answer
> 1 votes
You can add page--front.tpl.php in your enabled theme folder and clear the cache

---
Tags: theming
---


title: Why is my Query not returning a result

text:
# Question
Title: Why is my Query not returning a result
**Background**

I have a large table with lots of values and want to check if any of the names are repeating and only display those results. I have built a view and cannot get the SQL query to return the result I want.

**Code**

Here is the code as it stands, I've done loads of variations of it but cant get the result and think that there must be a core problem with my logic.

So I have built a view and selected a couple of column and now I want a column that will print out the name of the title the number of times it appears in the database. Or just count the number and print that.

```
<?php
  $value = $row->title;
  $query= "SELECT node.title, node.type
           FROM {node} node
           WHERE  (node.type IN ('institution')
           AND node.title  =".$value.")";
  $result= db_query($query);
  $wat = $result->fetchAll(PDO::FETCH_COLUMN, 0);
  foreach($wat as $res){echo $res;}
?>

```

So as you can see I get the value of title at the row I'm on and compare it to every value for title in the database, then return only results that match. After that I loop through them and get the value printed.

I have managed to get all the titles out and print them but as soon as i bring `$value` into it it breaks. I have checked the value of `$value` and it returns the expected result. I just cant figure out what is wrong with my SQL query.

**Question**

What is wrong with my Query? is there something that stops me using the `$row->title` in drupal that I don't know about?

# Answer
> 5 votes
Without access to your error logs etc. I'm going to assume the problem is that you are not putting quotes around your title string, so it is trying to use the title as a database column and it fails.

It should be like this:

```
AND node.title  = '" . $value . "')";

```

That is not a great solution either though because it opens you up to possible SQL injection attacks so instead, use Drupal's built in sanitisation like this:

```
$query = "SELECT title, type
            FROM {node}
           WHERE type = 'institution'
             AND title = :title";
$result = db_query($query, array(':title' => $value));

```

When you do it like that Drupal will sanitize the $value and it will also know that it is a string and wrap it in quotes. For more information see the documentation for Drupal's database API - Static queries.

In the above example I also changed the type "IN" operator to "=" because you only had one value, removed the redundant brackets around the where clause and removed the table alias to make the query as simple as possible.

On the topic of EntityFieldQuery, there are multiple different ways to run a query in Drupal and the best solution depends on the particular use case. If you want optimal performance and don't need to restrict results based on node access then db\_query() is likely the best method. Without knowing your requirements I couldn't advise on the best approach for your current query.

# Answer
> 2 votes
i have always used entity query for select records.

```
   $value = $row->title;

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'institution')
  ->propertyCondition('status', 1, '=')
  ->propertyCondition('title',$value , '=')
  ->propertyOrderBy('created','DESC');
     $results = $query->execute();
   if (isset($results['node'])) {
      $nodes = node_load_multiple(array_keys($results['node']));

      foreach ($nodes as $row) {
        // your stuff here
     }
  }

```

hope this helps you...

# Answer
> 2 votes
You should follow @Kamal Oberoi's advice and use EntityFieldQuery (EFQ).

The reason that changing to using EFQ is a good idea (apart from possibly fixing your issue) is that it will make your code more robust, transferable, extendable and secure.

* **Robust**: The underlying data structure might change with a module update one day; Your query would stop working while EFQ would not.
* **Transferable**: If you want to migrate your site to another data storage system (not MySQL), EFQ would still work.
* **Extendable**: e.g. adding a pager to your table is as simple as adding `->pager()`to your EFQ definition and `theme('pager')` to the end of your rendered output.
* **Secure**: It's pretty much impossible for any SQL injection attacks to be introduced as a result of using an EFQ. In your example above, if `$value` is not sufficiently sanitised then it could introduce a major security hole.

n.b. For queries for which EFQ is not suited (i.e. ones that don't return a list of entities), use db\_select, which has many of the same advantages. `db_query` is best left as the last resort.

# Answer
> 0 votes
I'd echo this would be a good place for EntityFieldQuery.

But to answer what's wrong with your actual code (besides the SQL injection vulnerability), it's that $value isn't wrapped in quotes, so it's not being treated as a string.

So if your $row-\>title is 'Foo Bar', this is how your clause is being prepared/executed:

```
WHERE node.title = Foo Bar

```

This won't work. The clause needs to look like this:

```
WHERE node.title = 'Foo Bar'

```

That's what's immediately wrong. The more complete answer is that you should use argument placeholders, which has consistent syntax regardless of variable type and protects against SQL injection:

```
$query= "SELECT node.title, node.type
           FROM {node} node
           WHERE  (node.type IN ('institution')
           AND node.title = :title)";
$placeholders = array(':title' => $row->title);
$result= db_query($query, $placeholders);

```

---
Tags: database
---


# Question
Title: How do I break my query result into smaller chunks
**Background**

I have a query that returns 140000+ results and I need to perform more calculations on the result before displaying them to the user. This has caused a huge wait time (left it to run for 1hr and 30 mins and it still wasn't finished).

**Problem**

The wait time is huge and needs to be reduced. I can happily load all the data (140000+ results) and run a lesser calculation. This is no use if I can't run the full calculation.

**Possible Solution**

I've thought about this and I think if I was able to limit the results returned (say 1000 results) I would be able to run the full calculation with no problems.

**Question**

Can I limit the amount of results back (say results 0-999) run my calculation on them and then load the next bit (results 1000-1999) and run the calc again?

# Answer
> 1 votes
According to https://www.drupal.org/node/1848368

> Queries may also be restricted to a certain subset of the records found. In general this is known as a "range query". In MySQL, this is implemented using the LIMIT clause. To limit the range of a query, use the range() method, which takes two arguments: the first specifies offset and the second specifies limit
>
> In most cases we want "the first n records". To do that, pass 0 as the first argument and n as the second.
>
> ```
> <?php
> // Limit the result to 10 records
> // where 0 is offset and 10 is limit
> $query->range(0, 10);
> ?>
>
> ```
>
> The following example will instruct the result set to start at the 6th record found (the count starts at 0) rather than the first, and to return only 10 records.
>
> ```
> <?php
> $query->range(5, 10);
> ?>
>
> ```
>
> Calling the range() method a second time will overwrite previous values. Calling it with no parameters will remove all range restrictions on the query.

---
Tags: database
---


title: Add custom link to a page

text:
# Question
Title: Add custom link to a page
I am not able to find out how can I add a custom link at the bottom of a page (like in the image below - "hlee's blog"). When I click on the 'Edit' tab, there is not html/code for that link. I need to add another link on this page but have no clue where the setting/code is.

Thank you.

# Answer
> 0 votes
I'm assuming that you're using Drupal 7. Many ways to do this, one way is to implement hook\_node\_view

---
Tags: navigation
---


title: Errors when saving node

text:
# Question
Title: Errors when saving node
Im at a bit of a loss here, this error started happening when saving a new node, or updating an existing node.

It says The website encountered an unexpected error. Please try again later..

The error on the screen is...

> Notice: Undefined index: fid in file\_field\_update() (line 276 of C:\wamp\www\thelhp\modules\file\file.field.inc).
>
> Notice: Undefined index: fid in file\_field\_update() (line 302 of C:\wamp\www\thelhp\modules\file\file.field.inc).
>
> Notice: Undefined property: stdClass::$fid in file\_usage\_add() (line 689 of C:\wamp\www\thelhp\includes\file.inc).
>
> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1048 Le champ 'fid' ne peut être vide (null): INSERT INTO {file\_usage} (fid, module, type, id, count) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4); Array ( \[:db\_insert\_placeholder\_0\] =\> \[:db\_insert\_placeholder\_1\] =\> file \[:db\_insert\_placeholder\_2\] =\> node \[:db\_insert\_placeholder\_3\] =\> 196 \[:db\_insert\_placeholder\_4\] =\> 1 ) in file\_usage\_add() (line 696 of C:\wamp\www\thelhp.co.uk\includes\file.inc).

I am now not able to create nodes, or update existing ones.

HOWEVER, after further testing, I have found that if I upload an image to the optional image field, nodes save and update just fine. When no image is uploaded, the errors show up. help! :-(

# Answer
> 0 votes
I had custom code in my module...

```
function custom_node_presave($node) {

  if(isset($node->field_gallery_images)) {
    $node->field_gallery_images[LANGUAGE_NONE][0]['alt']=$node->title;
    $node->field_gallery_images[LANGUAGE_NONE][0]['title']=$node->title;
  }

}

```

Commenting it out stopped the error

---
Tags: entities, media, files
---


# Question
Title: Add JavaScript files to the administrative pages
How do I add JavaScript/CSS files in every administration pages, using a module?

# Answer
> 25 votes
Using a module, you can follow two methods:

The first method would allow you to add the extra JavaScript (or CSS) files to any administration pages, while the second method would allow you to add those files only to pages containing forms.

```
function mymodule_init() {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_js($path . '/mymodule.js');
    drupal_add_css($path . '/mymodule.css');
  }
}

```

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (arg(0) == 'admin') {
    $path = drupal_get_path('module', 'mymodule');
    $form['#attached']['css'][] = $path . '/mymodule.css';
    $form['#attached']['js'][] = $path . '/mymodule.js';
  }
}

```

Replace "mymodule" with the short name of your module; replace "mymodule.js" and "mymodule.css" with the actual names of the JavaScript and CSS files.

system\_init() contains the following code, to add specific files to administrative pages.

```
  $path = drupal_get_path('module', 'system');
  // Add the CSS for this module. These aren't in system.info, because they
  // need to be in the CSS_SYSTEM group rather than the CSS_DEFAULT group.
  drupal_add_css($path . '/system.base.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));

  // Add the system.admin.css file to the administrative pages.
  if (path_is_admin(current_path())) {
    drupal_add_css($path . '/system.admin.css', array('group' => CSS_SYSTEM));
  }

  drupal_add_css($path . '/system.menus.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));
  drupal_add_css($path . '/system.messages.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));
  drupal_add_css($path . '/system.theme.css', array('group' => CSS_SYSTEM, 'every_page' => TRUE));

```

path\_is\_admin() is the function that in its documentation is described as:

> Determine whether a path is in the administrative section of the site.

Consider that some node-related paths, such as `node/<nid>/edit`, could be included in the administrative section, depending on the setting found on admin/appearance.

The list of the node paths that could be included in the administrative pages is returned from node\_admin\_paths().

```
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/edit' => TRUE,
      'node/*/delete' => TRUE,
      'node/*/revisions' => TRUE,
      'node/*/revisions/*/revert' => TRUE,
      'node/*/revisions/*/delete' => TRUE,
      'node/add' => TRUE,
      'node/add/*' => TRUE,
    );
    return $paths;

```

If, for any reason, you need to avoid any page with a path like node/\*, you need to add specific code to avoid those, if you are using `path_is_admin()`. Consider that any module could change the pages that are considered part of the administrative pages.

In both the cases, the alternative would be using a library, if the module implements hooks\_library() with code similar to the following one.

```
function mymodule_library() {
  $path = drupal_get_path('module', 'mymodule');

  $libraries['mymodule.library'] = array(
    'title' => 'MyModule Library',
    'version' => '1.0',
    'js' => array(
      $path . '/mymodule.js' => array(),
    ),
    'css' => array(
      $path . '/mymodule.css' => array(
        'type' => 'file',
        'media' => 'screen',
      ),
    ),
  );

  return $libraries;
}

```

In this case, the previous implementation of `hook_form_alter()` would become the following.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (arg(0) == 'admin') {
    $form['#attached']['library'][] = array('mymodule', 'mymodule.library');
  }
}

```

Instead of calling `drupal_add_js()`, and `drupal_add_css()`, the code should call `drupal_add_library('mymodule', 'mymodule.library')`.

The pro of using `hook_library()` is:

* Dependencies between libraries are automatically handled. That is what happens in the case of system\_library(), which defines two libraries using the following definitions.

```
  // Drupal's form library.
  $libraries['drupal.form'] = array(
    'title' => 'Drupal form library',
    'version' => VERSION,
    'js' => array(
      'misc/form.js' => array(
        'group' => JS_LIBRARY,
        'weight' => 1,
      ),
    ),
  );

  // Drupal's collapsible fieldset.
  $libraries['drupal.collapse'] = array(
    'title' => 'Drupal collapsible fieldset',
    'version' => VERSION,
    'js' => array(
      'misc/collapse.js' => array('group' => JS_DEFAULT),
    ),
    'dependencies' => array(
      // collapse.js relies on drupalGetSummary in form.js
      array('system', 'drupal.form'),
    ),
  );

```

Calling `drupal_add_library('system', 'drupal.collapse')`, misc/collapse.js and misc/form.js would both be included.
* The CSS files associated with the library would be automatically loaded together the JavaScript files.
* Whenever the library would use more JavaScript, or CSS files, the code to include the library would not change; it would still be using `$form['#attached']['library'][] = array('mymodule', 'mymodule.library');`, or `drupal_add_library('mymodule', 'mymodule.library')`.

There is no need to use current\_path() when you can use arg(). If the path for the current page is admin/structure/block, then

* `arg(0)` will return `"admin"`
* `arg(1)` will return `"structure"`
* `arg(2)` will return `"block"`

### Update

`hook_init()` is not used anymore from Drupal 8. The alternative for Drupal 8 is using `hook_form_alter()`, `hook_page_attachments()`, or `hook_page_attachements_alter()`. `hook_page_build()` and `hook_page_alter()` are not anymore used in Drupal 8.
What I said about using a JavaScript library is still true, even if it is suggested to use `#attached` to attach a library (or a Javascript file, or a CSS file) to a page. Drupal 8 doesn't allow anymore to attach just JavaScript or CSS files to a page; you need to always attach a library, which a set of JavaScript and CSS files, eventually made of just JavaScript or CSS files.

# Answer
> 3 votes
Here are two approaches to adding JS/CSS to pages.

You can add JavaScript and CSS directly to the template file page.tpl.php, since the template files are PHP files, you can check the URL using arg() and present accordingly.

Alternatively, and better since it's theme independent, create a module that implements hook\_init(), and call drupal\_add\_js() or drupal\_add\_css() based on current\_path().

Something like the following code would work.

```
// Runs on every page load.
function mymodule_init() {
  // Check if current path is under "admin"
  if (substr(current_path(), 0, 5) == 'admin') {
    drupal_add_css('path/to/my/css');
    drupal_add_js('path/to/my/js');
  }
}

```

# Answer
> 1 votes
I created a module using the steps described here: http://purewebmedia.biz/article/2014/04/23/adding-your-own-css-admin-theme

Copied the module text as desribed on that page:

```
    function mymodule_preprocess_html(&$variables) {
// Add conditional stylesheets for admin pages on admin theme.
  if (arg(0)=="admin") {
    // reference your current admin theme
    $theme_path = drupal_get_path('theme', 'commerce_kickstart_admin');
    // reference your own stylesheet
    drupal_add_css(drupal_get_path('module', 'mymodule') . '/css/mymodule.css', array('weight' => CSS_THEME));
  }
}

```

However the admin check was faulty when I (as one of the things) wanted to style the submit buttons in all pages as well as the node edit form. Since that path goes to node/edit and not admin the check made me scratch my head for hours.

So I came up with this version to make my simple module called admin\_css.

**admin\_css.info**

```
name = admin_css
description = Custom css alterations for editor interface
core = 7.x
version = 7.x-1.01

```

**admin\_css.module**

```
function admin_css_preprocess_html(&$variables) {
    if (path_is_admin) {
        $theme_path = drupal_get_path('theme', 'seven');
        drupal_add_css(drupal_get_path('module', 'admin_css') . '/css/admin_css.css', array('weight' => 0));
    }
}

```

What is different to the answer here is to check if the path is in the administrative part of the site with path\_is\_admin instead of using **arg**. Using arg caused my css-file not to load on the node-edit and other pages.

# Answer
> 1 votes
It's considered bad practice to add JS and CSS from `hook_init()`. Instead you'ld use `hook_page_build()`:

```
/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  if (path_is_admin(current_path())) {

    drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/scripts/magic.js');
  }
}

```

# Answer
> 1 votes
I just used another method that may appeal to front-end devs. Subtheme your preferred admin theme and then add a simple:

`scripts[] = myscripts.js`

to your theme.info file that contains the javascript you need for your admin pages. If you wish, you can add more overrides, since this will inherit your favorite admin theme's resources.

---
Tags: 7, javascript, theming
---


# Question
Title: The page request for /admin/structure/block only returns part of the html and doesn't render it
I'm logged in to Drupal and am requesting the blocks page at /admin/structure/block. However, the page request doesn't render properly in my browser. (I tried two different browsers with similar results).

The page I get begins with this:

```
d90
>configure</a></td>
        <td><a href="/admin/structure/block/manage/block/356/delete" id="edit-blocks-block-356-delete">delete</a></td>
      </tr>
                  <tr class="draggable even">
        <td class="block">Set Free - FAQ 1</td>
        <td><div class="form-item form-type-select form-item-blocks-block-333-region">   <label class="element-invisible"
for="edit-blocks-block-333-region">Region for Set Free - FAQ 1 block
</label>  <select class="block-region-select block-region-user_first
form-select" id="edit-blocks-block-333-region"
name="blocks[block_333][region]"><option value="-1">- None
-</option><option value="help">He

```

Or this:

```
10000 ion><option value="map">Map</option><option
value="preface">Preface</option><option
value="breadcrumb">Breadcrumb</option></select> </div> <input
type="hidden" name="blocks[block_110][theme]" value="omnia" /> </td>
        <td><div class="form-item form-type-textfield form-item-blocks-block-110-weight">   <label class="element-invisible"
for="edit-blocks-block-110-weight">Weight for 30 DIGITAL TALENTS -
Home Corprate block </label>  <input class="block

```

or this:

```
a46c t form-select" id="edit-blocks-block-366-region"
name="blocks[block_366][region]"><option value="-1">- None
-</option><option value="help">Help</option><option value="content">Content</option><option value="top_first">Top
First</option><option value="top_second">Top Second</option><option
value="top_third">Top Third</option><option value="top_fourth">Top
Fourth</option><option value="social_top">Social Top</option><option
value="search_form">Search Form</option><option
value="logo">Logo</option><option value="menu">Menu</option><option
value="strapline_first">Strapline</option><option
value="latest_first">Latest Work</option><option
value="sidebar_first">Sidebar First</option><option
value="sidebar_second">Sidebar Second</option><option
value="postcontent_first">Post Content First</option><option
value="team_first">Team First</option><option
value="logoslider_first">Logo Slider First</option><option
value="bottom_first">Bottom First</option><option

```

Every page refresh is different.

Anyone have any ideas?

I have a custom module or two, but I don't think they are doing anything bad. We haven't touched the theme. I've cleared Drupal's cache. I can't see anything relevant in Drupal's log or the PHP error log. Every other admin page works fine. Any ideas?

# Answer
I got it working. This is what I did: I restarted Windows.
> 0 votes

---
Tags: blocks
---


title: Restricting Content by License / Code

text:
# Question
Title: Restricting Content by License / Code
I'm working on migrating a custom coded site over to Drupal and am having trouble with one piece of functionality.

Currently, if a user wants to download a certain file, they have to enter a serial number into a form. That serial is compared to a list of serials in the db. If the serial matches, the end user can download the file.

Is there any way to create this same type of functionality? I'm willing to use any Commerce add-on, as Commerce will be used for other products.

# Answer
> 0 votes
Take a look Commerce File & its dependency Commerce License. These module enable a licensing product functionality tied to some sort of digital file. This will get you a good way there, but you'll probably add extra features for your particular use (e.g. some sort serial code validation before displaying the download link).

---
Tags: commerce, files, users
---


# Question
Title: How do I specify in which database my schema should be created?
When using multiple databases in Drupal 7, how can I specify that a table is to be created in a different database on a different server?

By default, when you install a module, Drupal assumes that everything in `hook_schema()` should be installed in the default database. Is there a way to specify that a table should be created on a different database, or is there some kind of manual workaround I can use?

# Answer
I don't think there is an official API; it doesn't make much sense to do this in general.

That said, all you need to do is give your `hook_schema` a different name than `yourmodule_schema` (basically whatever you want, like `yourmodule_schema_otherdb`) and then in hook\_install(), first switch your database, then replicate what drupal\_install\_schema() does except that you call your custom schema definition function and then switch the database back to the default.

Also, remember to implement `hook_uninstall()`.

No idea why you'd want to do this, though. :)
> 4 votes

# Answer
I have achieved this with the information provided by Berdir. My code looks like:

```
<?php
function mymodule_schema_otherdb() {
  $schema['mytable'] = array(
    'description' => 'My table description',
    'fields' => array(
      'myfield' => array(
        'description' => 'My field description',
        'type' => 'serial',
        'size' => 'medium',
        'not null' => TRUE,
        'unsigned' => TRUE,
      ),
    ),
    'primary key' => array('myfield'),
  );
  return $schema;
}

function mymodule_install() {
  db_set_active('otherdb');
  $schema = mymodule_schema_otherdb();
  foreach ($schema as $name => $table) {
    db_create_table($name, $table);
  }
  db_set_active();
}

function mymodule_uninstall() {
  db_set_active('otherdb');
  $schema = mymodule_schema_otherdb();
  foreach ($schema as $name => $table) {
    db_drop_table($name);
  }
  db_set_active();
}

```
> 11 votes

# Answer
A **Drupal 8** version of the \*.install file code provided by @Елин Й.:

Note: Database must exist and be specified in settings.php.

```
<?php
function mymodule_schema_otherdb() {
  $schema['mytable'] = array(
    'description' => 'My table description',
    'fields' => array(
      'myfield' => array(
        'description' => 'My field description',
        'type' => 'serial',
        'size' => 'medium',
        'not null' => TRUE,
        'unsigned' => TRUE,
      ),
    ),
    'primary key' => array('myfield'),
  );
  return $schema;
}

/**
 * Implements hook_install().
 */
function mymodule_install() {
  \Drupal\Core\Database\Database::setActiveConnection('otherdb');
  $connection = \Drupal\Core\Database\Database::getConnection();

  $schema = mymodule_schema_shared();
  foreach ($schema as $name => $table) {
    $connection->schema()->createTable($name, $table);
  }

  \Drupal\Core\Database\Database::setActiveConnection();
}

/**
 * Implements hook_uninstall().
 */
function mymodule_uninstall() {
  \Drupal\Core\Database\Database::setActiveConnection('otherdb');
  $connection = \Drupal\Core\Database\Database::getConnection();

  $schema = mymodule_schema_shared();
  foreach ($schema as $name => $table) {
    $connection->schema()->dropTable($name);
  }

  \Drupal\Core\Database\Database::setActiveConnection();
}

```

Here's a Gist.
> 1 votes

# Answer
In Settings.php
`$db_url=array('default'=>$db_url, 'sec_db'=>$sec_db_url);`
In `hook_schema` `db_set_active('sec_db')` will now connect to your another DB , *not sure if this is recommended or not try it at your own risk.* And you can make use of db\_prefix to query from this secondary DB. You can make use db prefix in settings.php
> -2 votes

---
Tags: 7, database
---


# Question
Title: Can a disabled module pose a security risk?
Is it possible for a module that is installed but not enabled to pose a security risk?

Corollary question: Is it a recommended practice to update disabled modules when security updates become available?

# Answer
I say yes since the vulnerable code is still sitting right there in the web directory which can (will) be scanned by potential attackers. Monitoring disabled modules is certainly part of our update routine.

I didn't find a whole lot of discussion on this in regards to Drupal in particular, likely because it isn't really a Drupal-related issue (see note below). Greg Knaddison (@greggles on Drupal.org) noted on a thread a few years back that:

> Sometimes the vulnerabilities exist regardless of whether or not the module is enabled, so I think it's better to warn on all modules.

Source: Issue #942960: Don't warn about security updates for disabled modules

**As always, best to err on the side of caution.**

Note: I think this is more a server admin related question, but I hesitate to flag it as not relevant since IMHO people who aren't server admins shouldn't really be expected to know that.
> 5 votes

---
Tags: updating, security
---


# Question
Title: How to add JS Confirmation popup when clicking an #AJAX button in custom module?
```
$form['button4'] = array(
'#value' => 'RESET',
'#type' => 'submit',
'#submit' => array('form_test_form_button4'),
'#ajax' => array(
  'callback' => 'ajax_example_submit_driven_callback1',
    'progress' => array('type' => 'none'),
    'wrapper' => 'deletevalue',
    'event' => 'click',
),

);

```

This is the RESET button I want to ask Are you sure?.

AJAX submit also working fine. But POPUP Confirmation not working properly.Please anyone guide to me?

If user click the OK button the data will be reset.

JS

`$('#edit-button7').on('click', function(){
var r = confirm("Are you sure you want to reset?");
});`

If user click the CANCEL button also data was reset.

# Answer
I could have sworn it was on so somewhere. But I could not find it quickly. You can try this using the form API in your button. Found here

```
 '#attributes' => array('onclick' => 'if(!confirm("Really Delete?")){return false;}')

```

You can of course use JS as you were. I think you were missing the `return false;`
> 1 votes

---
Tags: ajax, javascript
---


# Question
Title: how to add javascript with #attached and hook_page_alter
I tried to add `js` to pages by means of `#attached`, as it seems to be the recommended way. From what I understand, this involves altering a render array. `hook_page_alter` seems to me like good candidate.

As per https://www.drupal.org/node/756722 (and answers below), I came with:

```
function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['#attached']['js'][] = array(
    'js' => array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'),
  );
}

```

The file does not get attached, though. If I use

```
drupal_add_js($my_path . '/module_test.js');

```

it does get attached (it's not a problem of the js file, access persmissions, etc.).

What is wrong?

PS. I asked a related, but apparently wrong-headed question here

# Answer
The code that finally got it included an important change with regard to @AyeshK 's answer. The `[attached]` is not put at the top level if `$page` , but inside `['content']` or `['header']`.

The adapted code from the **Format#1** is now:

```
function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['content']['#attached']['js'][] = array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'
  );
}

```
> 3 votes

# Answer
Your code is almost correct. However, when you have a numeric key in `[#attached][js]`, and its value is an array, you must include the `data` key.

**Format #1**

```
function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['#attached']['js'][] = array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'
  );
}

```

**Format #2**

```
function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['#attached']['js'] = array(
    $my_path . '/module_test.js'
  );
}

```

**Format #**

```
function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['#attached']['js'] = array(
    $my_path . '/module_test.js' => array(
      'type' => 'file',
    ),
  );
}

```
> 2 votes

---
Tags: javascript, theming
---


# Question
Title: Why does $page['content']['#attached']['js'] works , while $page['#attached']['js'] does not?
Trying to attach js by means of #attached by means of hook\_page\_alter (see https://drupal.stackexchange.com/questions/171918/how-to-add-javascript-with-attached-and-hook-page-alter), I found that the following code

```
 function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['content']['#attached']['js'][] = array(
    'js' => array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'),
  );
}

```

works properly - it attaches the file - while

```
function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['#attached']['js'][] = array(
    'js' => array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'),
  );
}

```

does not. Why is it so?

# Answer
> 8 votes
For `#attached` elements to be processed, the array needs to be run through `drupal_render()`. That never happens for the `$page` array.

Parts of it are rendered, e.g. in page.tpl.php:

```
<?php print render($page['content']); ?>

```

But never the `$page` array itself.

---
Tags: 7, javascript, theming
---


# Question
Title: What's the easiest way to add a contact form for all nodes of a certain content type?
I need to add a contact form to all nodes of a certain content type, so when a user submits the form it's delivered to the e-mail address of the author of the node. I tried using Webforms as a block with Contexts but Tokens doesn't work.

# Answer
I ended using Webforms, passing the node author's e-mail using the token \[current-page:node:author:mail\] for passing the e-mail via a hidden field. I enabled the option to use the webform as a block and Context module for showing that block only in the desired content type.

With the lastest stable versions of Webforms and Token, I had to patch Token module as it's explained in this forum because the token wasn't working with Webforms.

http://doublemthemes.com/comment/3307#comment-3307
> 1 votes

# Answer
There was a module for that, Author Contact. If you are using Drupal 6, it might still be good. If you are using later version, it's still a decent source of opensource code. There is Drupal 7 port, but I can't personally vouch for it. *Seems* good, but I only glanced at code. If it works, it will be *the* easiest way - because that's what it does, nothing less, nothing more.

Alternatively, you could give Entityform a try. It does not send email to author out of the box as far as I know, it was discussed on drupal.org, but if you are feeling lucky, it would be worth try again.
> 0 votes

---
Tags: nodes, forms, emails
---


# Question
Title: How to display custom table without using views?
I have tried it to display the table by using core PHP concept and it display the table but at the top of the page now i need to display inside my page my current display is below

and my code for view is

```
function testing_db_viewall($form, &$form_state){
    $result = db_select('infobox_new')
    ->fields('infobox_new', array('name','emailid','contactno','nid'))
    ->execute();

    $entries = $result;
    $output ='';
    $rows = array();

    foreach ($entries as $entry) {
    // print_r($entry);
    // echo "<br>";
        $rows[] = array( $entry->name, $entry->emailid, $entry->contactno, l('edit','examples/edit/'.$entry->nid), );
    }
  // Make a table for them.
    $header = array(t('Name'),t('Email id'), t('Contact No'),t('edit'));
    $output .= theme('table', array('header' => $header, 'rows' => $rows));

     echo $output;
}

```

I want to display my table after my title i.e. "Custom Table View"

Thanks in advance

# Answer
> -1 votes
My issue has been resolved

I made silly mistake in my menu creation link.

# Answer
> 2 votes
Instated of "echo"

> echo $output;

You have to write

> return $output;

---
Tags: theming
---


# Question
Title: Automatically cycle through full-page nodes
Looking to implement something that will loop through nodes in the system. I'm not looking for carousel functionality, but instead want to load/display full-page node content, wait, and then load/display the next node.

The end result should be kinda like a TV channel, presenting nodes of various content types on big TVs in the common areas of our building.

I've got some ideas for how to build this, but would like to ask if there is a module that already accomplishes something similar?

# Answer
> 1 votes
I tried to implement this feature and I had almost achieved it. To try-out, click any preview button in this page, you can see the content cycling through nodes.

I suppose you want to cycle through a list of nodes generated by a View.

**Procedure:<br>**

I used Views navigation module to preserve the list of nodes generated in a View. It also preserves the order of those nodes in cache.

In script:

```
(function ($) {
  Drupal.behaviors.module = {
    attach: function (context, settings) {

      //Posts the current position of node and Views-navigation cache ID - on clicking 'next' button
      $("body", context).on("click", ".next", function() {
        var pos = $(this).attr('data-pos');
        var cid = $(this).attr('data-cid');
        $.ajax({
          type: 'POST',
          url: '/navigation',
          dataType: 'json',
          data: 'pos='+pos+'&cid='+cid+'&dir='+dir+'',
          success: DoWhateverWithNextNode
        });
      });

    },
  };
})(jQuery);

```

In module:

```
//Menu callback for 'navigation'
function get_next_node() {
  if($pos = $_POST['pos']) {
    module_load_include('inc', 'views_navigation', 'views_navigation');

    $result = views_navigation_get_result($_POST['cid']);
    $max_index = count($result) - 1;
    $pos = ($pos > $max_index) ? 0 : (($pos < 0) ? $max_index : $pos);

    if ($nid = $result[$pos]) {
      $next_node = node_load($nid);
      return drupal_json_output($next_node);
    }
  }
}

```

In *DoWhateverWithNextNode(data)*, you are required to increment 'data-pos' for '.next' element by 1. So that you can cycle through nodes.

P.S. This code may not be a working version. I just provided you an overview of my implementation.

---
Tags: views, nodes, javascript
---


title: Validating user email ID during sign up

text:
# Question
Title: Validating user email ID during sign up
We are making a accounting software and would like to know how we can use a open source API or query to validate user email id by sending email to the specific email id and getting a activation response from the same using a weblink.

# Answer
> 2 votes
There's no need to use any sort of API or query. If you're goal is to validate email, it's built into Drupal's core account settings (Configuration \> People \> Account settings). Just make sure the ***Require e-mail verification...*** checkbox is ticked on the form page.

# Answer
> 1 votes
You can do this using contributed module https://www.drupal.org/project/user\_email\_verification

---
Tags: users
---