# Question
Title: How can I restrict access to my website via web services only?
I am getting lots of spam in my website. Here are some modules I tried as a remedy:

1. Honeypot
2. Http BL

No luck yet however.

Now I **decided** to make the site available only for web services only, whereas the web services are done with Services module.

So how can I allow access to my website via services only? Is there something I can achieve this from ***.htaccess*** ?

# Answer
Assume a setup like so:

* Assume that for site access via Services you use an account called "ServicesUser".
* Create a new role, say you call it "ServicesOnly".
* Make sure that there are no other "custom" roles in your site apart from anonymous, Authenticated and Administrator (if there are any: remove them again).
* Authorize only user "ServicesUser" for this role "ServicesOnly".
* Tune your permissions where appropriate, so that:

+ No permissions are granted to Anonymous or Authenticated.
    + All permissions are granted to Administrator (but only in case you have a need to ever login without using services, with a userid different from user/1, if there is no need for that, then no permissions granted to Administrator either).
* Granularly issue permissions to role "ServicesOnly", so that "ServicesUser" receives appropriate permissions whenever required.
* Whenever the site is switched to maintenance mode (eg to apply Drupal updates), ServicesUser will not be able to login either, which is what you should want also.

With a setup like above, access via Services (and userid = ServicesUser) should work as desired. While I cannot think of any other user who can do anything on your site, except user/1 (and optionally some other user who has access to role Administrator).

With this configuration, these are the only ways around it that I can think of:

* Some security issues that are exploited somehow.
* Somehow getting access to the ServicesUser account

**Note**: no additional contributed or custom) modules needed either ...
> 1 votes

---
Tags: 7, services, .htaccess, advertising
---


title: How to call image on views tpl file?

text:
# Question
Title: How to call image on views tpl file?
I have a view in drupal 7 and I have created a template of this view. Now I need to call image here.

# Answer
Try this

```
<div class="attachment-property-thumb">
  <?php print $fields["field_real_thumbnail"]->content; ?>
</div>

```
> 0 votes

# Answer
You need to do field level theming.

1. Create a template file having name like: `views-view-fields--your-view-name.tpl.php`
2. `drupal_set_message('<pre>' . print_r(array_keys($fields), TRUE) . '</pre>');`

see Calling a field in views-view-fields--view-name.tpl.php ---- Error
> 0 votes

# Answer
If you have multiple images, please make changes from view to display only single image as shown in attached file.

Please use below code snippet in your view tpl file.

```
$fid = file_id_from_your_view

$file = file_load($fid);

$img_url = $file->uri;

// Path for your image with specific style
$style_image = image_style_url('your_image_style_to_display', $img_url);

```

Hope this helps you!

Thanks!
> 0 votes

---
Tags: views
---


# Question
Title: Administrator notification on user registration
Administrator is not notified when a user registers on my D7 site, while the registrants do receive a message. On the D6 version of the site it worked. Here's the setup:

* Drupal 7.10
* User registration is upon admin approval.
* Contact users works.

I can't find a flag anywhere to turn on notification to administrator. Google search and search on this site has not turned up a solution. Is this capability in core, how do I turn it on. Do I have to use additional module?

Thanks.

# Answer
First, go to `/admin/config/system/actions`. In the section "Create an advanced action", choose "send an email" and click on "create". It takes you to a page where you need to enter a recipients email address, (enter the Administrator's email address here), subject and message. Click Save.

Second, go to `/admin/modules` and enable the Trigger module.

Third, go to `/admin/structure/trigger/user`. In the Section "Trigger: After creating a new user account" Choose "Send e-mail" in the select box. Click Assign.

Example Message:

```
A user has created an account.

Details:
 - Username: [user:name]
 - Email: [user:mail]
 - Time: [user:created:long]

Activate their account by going here: [user:edit-url]

```
> 24 votes

# Answer
Although this is an old question, I just found it in a search, and found that the suggested approach, though excellent, does not work with Tokens.

If you want the administrator to be sent an email that contains some or all of the fields that you have attached to your user account: eg something like:

\[account:field-contact-name\] has created an account. Details submitted: \[account:field-business-name\]

Use Rules module which offers a nice simple tokenised email approach.

Once you have installed Rules, from /admin/config/workflow/rules, add a new rule.

1) Add an event : After saving a new user account

2) Add an action: Send Mail

3) In the message body, choose your tokens from the Replacement Patterns dropdown and save your new Rule.

4) test, and rejoice at how lovely Rules is.
> 11 votes

# Answer
User registration **workflow** (*pending email to "site admin" and "user" --\> approve by "site admin" then confirmation email to the user*) is a default (core) system of drupal.

From `Admin > Configuration > People > Account Settings` page, set Red-marked option of the attached image.

Note: You can set email content (message) in the **E-mail** section from bottom of the same account setting page.
> 2 votes

---
Tags: emails
---


title: SSL errors on Heroku (Mixed contents)

text:
# Question
Title: SSL errors on Heroku (Mixed contents)
I have an app via Drupal 7 on Heroku. You know, myapp.herokuapp.com is default with SSL.

But when I try `https://myapp.herokuapp.com` get many errors in console like this:

```
 Mixed Content: The page at 'https://myapp.herokuapp.com/' was loaded over HTTPS, but requested an insecure stylesheet 'http://myapp.herokuapp.com/modules/system/system.base.css?ngonpd'. This request has been blocked; the content must be served over HTTPS.

```

I tried to add this code in settings.php but not working:

```
if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') {
  $base_url = 'https://myapp.herokuapp.com';
}
else {
  $base_url = 'http://myapp.herokuapp.com';
}

```

How can I fix this?

# Answer
> 1 votes
IMO `$base_url` in `settings.php` should work

Alternatively you can try

```
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

```

or

```
RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

---
Tags: 7
---


# Question
Title: Can you make a node title \ heading link to it's NID?
I'm looking for a way to click a node's title to refresh it's very page. For example, if the current node is node/1 and I'll click it's **title \ H1** the page will be refreshed...

Tried to go to \> structure \> Content types (desired content type) \> edit \> edit display, but I couldn't find an option to edit the Page-heading \ h1 there.

I must say I'm looking for a **non-modular** solution (preferably without customization also).

Thanks.

# Answer
There are possibly few ways to do this.

Not sure if this actually works, but I *think* it does, you can install Display Suite and go to Manage Display tab and apply one of display suite's layouts to your "Full" view mode. After you do that, Display Suite will give you all the fields (including Title) on the Manage Display tab of that view mode. From there you just need to configure the fields and config the "title" field and check the option "Link title to node".

You could also do it from template files, I guess it qualifies as non-modular? For example in `node.tpl.php` or `page.tpl.php` (wherever the page\_title is being printed) one can easily create a link to the current node if the `$node` object is available or if not the node ID's available from the URL always. From there it should be a pretty easy call to `l()`:

```
<h1 class='page_title'><?php print l($page_title, 'node/'.$node->nid); ?></h1>

```
> 2 votes

# Answer
The page titles are not hyperlinks as you have discovered. Clicking the browser's refresh button allows you to refresh the page.

So perhaps you could say more about what problem you are trying to solve or function you are trying to add here. You can add new fields to the cont type and make such fields hyperlinks. But it's difficult to imagine a case where one needs to be able to hyperlink the title of the page itself.

In short, the answer is "no you can't do that" out of the box.
> 0 votes

---
Tags: theming
---


# Question
Title: View of users with the same 'entity reference' field vale
I'm running a D7 site where every user profile has a 'entity reference' field referencing to their manager.

All I want to do is to create a list of the users sharing the same manager in context to logged-in user.

Can anyone please help

# Answer
> 2 votes
You need two entity references and a contextual filter to accomplish this.

The contextual filter does not use either of the relationships. Just select provide default value, User ID from logged in user.

The first relationship will get you the manager of the currently logged in user: User entity referenced from field\_manager

The second relationship will get you the users that have that manager reference: User referencing User from field\_manager. Set this relationship to use the other relationship. That's the first dropdown after you create the relationship.

Then you can simply add the User name field to your view and set it to use the second relationship (User referencing User from field\_manager).

Any questions let me know. I have this running on a stripped down local install of Drupal 7.

---
Tags: 7, views, entities, users, database
---


# Question
Title: Override drupal form output. Place two input fields side by side
I am building a form using the FAPI and so far it is going fine.

I do however have a requirement for two tightly coupled values (currency and amount) that I wish to appear side by side in the form and not on separate lines.

What I need is something very similar to the way Drupal handles dates (3 inputs side by side, Im not sure, but are their input values added together to produce one value?)

Im sure this is possible using the FAPI but I cant see how off hand.

I would like to avoid any extra modules if possible.

Any takers?

thanks

Kevin

# Answer
> 1 votes
You can groupe the two fields into a field group. This gives HTML code wrapped around the fields. Just change the CSS settings of this HTML to your needs.

# Answer
> 0 votes
In Drupal 7, you can use the Double Field module. It even allows for prefixes and suffixes for text fields, which work great for currency fields.

---
Tags: 6, forms
---


title: How to hide views page title

text:
# Question
Title: How to hide views page title
I need to hide the page title in Views but still have it appear as the page title on the browser's window tab (for SEO). Could someone help me with that? I've looked around many times for answers but I haven't had any luck yet.

# Answer
This sounds like something that should be pretty easy to do with a CSS selector. The user won't see the title but all functionality outside of seeing it on the page will still work.

More specifically, you could add a rule to your css file like:

```
#page-title {
    display:none;
}

```
> 0 votes

# Answer
The CSS solution might not be the best for SEO purposes...
Another better alternative is to write in the page title field :

```
<No Title>
or : to leave it blank

```

And the title wont be displayed
> 3 votes

# Answer
```
function module_block_view_alter(&$data, $block){
    if($block->delta == 'your view name or id'){
        $data['title'] = 'my new title';
    }
}

```
> -1 votes

# Answer
unset the title in page preprocess hook
> -3 votes

---
Tags: views
---


# Question
Title: Programmatically loaded taxonomy form ajax errors
I load a taxonomy term in the edit form via the following code:

```
module_load_include ( 'inc', 'taxonomy', 'taxonomy.admin' );
$vocabulary = taxonomy_term_load ( $tid );
$form = drupal_get_form ( 'taxonomy_form_term', $vocabulary );

```

The vocabulary has a custom text field with unlimited values, so this appears on the form, but when I click the "add another item" button, I get:

> Call to undefined function, taxonomy\_form\_term\_validate() in \[truncated path\].../form.inc" on line 1513.

I appreciate any guidance I can get in solving this.

# Answer
This function worked for me: Please try to use form\_load\_include() and drupal\_build\_form() instead of drupal\_get\_form() to generate form

```
  $form_id = 'taxonomy_form_term';
  $vocabulary = taxonomy_vocabulary_load($tid);

  $form_state = array();
  $form_state['build_info']['args'] = array($vocabulary);

  // use form_load_include() and drupal_build_form() instead of drupal_get_form()
  form_load_include($form_state, 'inc', 'taxonomy', 'taxonomy.admin');

  $form = drupal_build_form($form_id, $form_state);

```
> 0 votes

---
Tags: 7, forms, taxonomy-terms, ajax
---


title: No images appearing?

text:
# Question
Title: No images appearing?
OK the site was fine until I updated the core of the website. Now the images do not show up. I have checked the paths and they are correct. I have checked the permissions and they are 777. I have an SSL on the site but as I say, it was all working well before! I've spent the last few hours trying to resolve this but to no avail. I've deleted and uploaded the core again - same. Any suggestions appreciated!

# Answer
It can be something wrong with File system settings. You may check it here `admin/config/media/file-system`
> 2 votes

# Answer
This might be a temporary solution but add this to settings.php:

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```
> 0 votes

---
Tags: media
---


# Question
Title: How to control Block revisions before being published?
Does Drupal support blocks versioning? Are there any modules can be used for controlling blocks revisions and publish selected version?

For example: a newly created blocks shall be published after being reviewed by a reviewer role user. So that the content will not be displayed in the page until it is published, meanwhile the content can be edited and sent for review and publish many times between the creator and reviewer.

Any suggestions about how to achieve this?

# Answer
> 2 votes
I would use the Bean module for this. Here is a quote about its project page:

> Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The Bean module also works great in combination with the UUID and UUID Features Integration modules. On top of that, after you become familiar with the Bean module, you might find other cases in your site where you also want to use the Bean module.

Moreover, by using Beans (i.e. entities), you qualify also for considering the Content Publishing System module (CPS for short) ... from commonly known "merlinofchaos". Here is an excerpt from that project page:

> ... CPS is a radical way of handling revisions for entities. It takes total control over revision management for all supported entities. For CPS-enabled entities, the revision tab is completely replaced and users are not allowed to manually create or move around revisions.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

A few more interesting issues related to all this:

---
Tags: blocks, workflows, nodes
---


# Question
Title: views contextual filter based on NID that is selected from a list
I have a slideshow in front page build by with Views and placed by Panels.

Currently i'm using contextual filter based on Nid and end user should enter Nids in Panels pane setting like "6,14,54,98" but it's not user friendly.

I need a list of nodes that end user can select nodes and the list automatically returns Nids.

# Answer
> 1 votes
You can use Nodequeue module for this. Quote from its project page:

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

# Answer
> 1 votes
You should use nodequeue module: https://www.drupal.org/project/nodequeue or entityqueue: https://www.drupal.org/project/entityqueue

Just:

* create queue
* fill it by nodes (with pretty autocomplete field)
* create new view based on this queue
* done

Some instruction for this:

---
Tags: views, panels
---


# Question
Title: Automatically add class to images added through CKEditor
I'm trying to add classes automatically to images which are added through CKEditor, I have spent considerable time trying to research this and found How to add class or attribute automatically to img tags in CKEditor? & Create new dom elements using dataProcessor.htmlFilter which hint at solutions that I can't get working.

I'm using the CKEditor module rather than WYSIWYG and found it's possible to add a new plugin using hook\_ckeditor\_plugin and my new plugin appears as a selectable option in the CKEditor admin, based on the 2 documents provided I managed to put together:

```
( function() {
  CKEDITOR.plugins.add('imageclass', {
    init : function( editor ) {
      var rules = {
        elements: {
          img: function( element ) {
            console.log(element);
          }
        }
      };

      // It's good to set both filters - dataFilter is used when loading data and htmlFilter when retrieving.
      editor.dataProcessor.htmlFilter.addRules( rules );
      editor.dataProcessor.dataFilter.addRules( rules );
    }
  });
})();

```

The problem is that nothing get's written to the console, I changed the line `img: function( element ) {` to `$: function( element ) {` which then writes all the elements at the root to the console, but all images, spans, etc. don't get written to the console as they are children of other elements (p, div, etc.) and I think this is something to do with the way CKEditor is integrated with Drupal and the options available via text formats.

I just don't understand enough about CKEditor and the documentation isn't easy to follow on how to move through more than just the elements at the root, unless trying to create this as a plugin is the wrong way to go.

# Answer
> 1 votes
Ok, I got the answer.

Forget about the simple image plugin. Let's use the default image plugin from CKeditor.

Go to sites/all/modules/ckeditor/ckeditor/plugins/image/dialogs

Open the image.js file in notepad.

Search for `c.lang.common.cssClass` beside it you should see a `"default": "",`

So just type your class in between the default quotes.

For Example: `"default": "MyCustomClassName",`

# Answer
> 0 votes
A workaround could be to give the fields which are using CKeditor a custom CSS class (e.g. `ckfield`, and define a class in your stylesheet in the likes of:

```
.ckfield img{
  max-width: 25%;
  margin: 15px;
}

```

---
Tags: wysiwyg, input-formats
---


title: Vanishing Blocks/Menues

text:
# Question
Title: Vanishing Blocks/Menues
I have a legacy site running Drupal 6.19, and today, I found out that the entire side bar had disappeared. I haven't run any updates, and no administrators have been on the site for a while, so I'm not sure what could have triggered this. Does anyone have any suggestions for how to reverse this?

I have gone into the /build/blocks menu, and the proper menu items are listed as being there (right sidebar region), and if I add a test item to any block region, it won't show up. The site is using a custom theme; however, the issue persists if I change themes the the default Drupal theme. I didn't see anything in the theme or global theme configs that would indicate a problem.

Thank you for you help.

# Answer
The problem was fixed by my collegue when he MySQL. Unfortunately, I didn't find any errors displayed on screen or in the logs, so I'm not sure what happened.
> 1 votes

---
Tags: routes, blocks, theming
---


# Question
Title: How to upgrade my Zen sub-theme so that navigation and most of the blocks are no longer missing?
I have been looking quite a bit for a "step by step" for what people did to upgrade their Zen Sub-themes from its 6.x version to the 7.x-5.x version.

I did not make the sub theme I'm working with and I am not familiar with the process (last webmaster made it).

The issue I am having: the front page and all other pages don't have navigation and almost all the blocks are missing.

In my searching I saw that the `.info` file and `template.php` file have something that needs to be done. Haven't been able to really get a good outcome at all.

This is how my 6.x regions look like:

```
regions[sidebar_first]  = First sidebar
regions[sidebar_second] = Second sidebar
regions[navigation]     = Navigation bar
regions[highlight]      = Highlighted content
regions[content_top]    = Content top
regions[content_bottom] = Content bottom
regions[header]         = Header
regions[footer]         = Footer
regions[page_closure]   = Page closure

regions[footer_col1]   = Footer Column 1
regions[footer_col2]   = Footer Column 2
regions[footer_col3]   = Footer Column 3
regions[footer_col4]   = Footer Column 4

regions[homepage_col1]   = Homepage Column 1
regions[homepage_col2]   = Homepage Column 2
regions[homepage_col3]   = Homepage Column 3

```

Any suggestions about how I should proceed?

# Answer
The issue about How to upgrade Zen theme from 6.2 to 7.3 contains quite some info (and links to other resources) about such Zen upgrade. However it also includes these suggestions about possible alternatives to consider:

* Something like "maybe you should just consider restarting from scratch".
* Swap from the Zen theme to the Omega theme (by creating an Omega sub-theme from scratch).

For more in depth documentation, you might want to look at Upgrading 6.x themes to 7.x.

Based on the current (further edited) content of your question, these are some of the topics to be sorted out (at least):

1. ## Navigation:

The navigation items shown in D6, possibly correspond to your primary and/or secundary menus (though they may also come from some "custom" menu that got added). Check which technique was used to actually display that menu in D6. Possible options I can think of: (a) some block makes them show up or (b) some theme settings is turned on (enabled checkbox) to make them display. Depending on which option was used, try to find the corresponding D7 options to do the same there.
2. ## Blocks:

For any of the blocks shown in the D6 version, in which theme region were they displayed? Head over to the D7 version to verify where probably "most of these blocks" will be shown within the "disabled" list of blocks. For any such block you find, in the D7 version start experimenting with moving those disabled blocks to what you think will be the most appropriate region in D7.

Keep repeating this for each of your blocks that are missing (= iterative process). In doing so, little by little most (if not all) of your blocks should start showing up).

If sorting out the above topics appears to be too complicated and/or turns out to take too long, then I'd really consider going the route of either possible alternatives mentioned above, because creating a "sub-theme" from the most recent Zen or Omega theme might simplify further maintenance of your "custom" theme also.
> 0 votes

---
Tags: theming
---


title: Custom styles on labels in views?

text:
# Question
Title: Custom styles on labels in views?
I would like to create custom styling for the label in a field for a table in a view. Is this possible within the view edit page? Or will I have to define a custom CSS class and write the styling in the css pages included in the theme?

# Answer
CSS in the theme (or in the module that provides the View) is the best way to do this.
> 1 votes

# Answer
Yes, it is possible within the view edit page.

You just need to click on the field.

Then under Styles Settings, check mark Customize label HTML. Select DIV or SPAN as element, then type a class name.
> 1 votes

---
Tags: views, theming
---


# Question
Title: Font-Awesome issue: how to remove menu-link text from a menu item with font-awesome icon?
I installed the module Font awesome icons (with it's library) & the module Menu attributes; I've configured them, and now have a working font-icon in my main menu.

The problem is that instead of the desired icon, there is a combination of icon&Text (img1), and I need only an icon to appear... If there was an option to delete the text I would do that, But I haven't seen such an option - The menu-link text seems to be mandatory (img2).

I though of the css command `text-indent: 200px` to remove the text but the font itself is also text... Any ideas how to safely remove the text without removing the icon? Thx,

# Answer
> 1 votes
In this case you're better off using a background image. Save yourself the hassle.

```
.menulink{
  Width: 25px;
  Height: 0;
  Padding-top: 25px; /* height of image */
  Overflow: hidden;
  Background: url(images/home-25x25.png) 0 0 no-repeat;
}

```

---
Tags: routes, theming
---


title: drupal webform styling pages

text:
# Question
Title: drupal webform styling pages
I have a form that I created using webform. I have it styled like I want on the client side but whenever I view the submissions or edit the submissions I would like to style that portion as well on the admin side but cannot find a way to style these. Can some provide some help regarding how to handle this?

# Answer
Have you considered ThemeKey?

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme **depending on current path**, taxonomy terms, language, node-type, and many, many other properties.
> 1 votes

# Answer
I would go with your original thought and use Views. You're probably going to want the control over the output that you wouldn't necessarily have if you just tried to style the tables in the admin section.

Creating your own view of the submissions would give you full control vs. wrestling with the existing display. Webform does already use Views to display the submissions table, but I don't think that it's modifiable via any UI.

Creating a view with submission #'s and edit/delete links is pretty straightforward, but if you want to display the actual submission data you'll need to use Webform mysql Views.
> 0 votes

---
Tags: webforms
---


# Question
Title: View does not display results when added as a block to a region
UPDATE 2: I'm not sure if this is relevant but when click 'demonstrate block regions' the only region it displays is content

---

UPDATE: I have just discovered that the block displays just fine when added to the content region. However when added to any other region such as the left sidebar or any custom region it does not display at all

---

I currently have a view that displays the results just fine in the view preview. It also works when I create a basic page and embed it like so:

```
<?php print views_embed_view('mobile_slide_menu','block');?>

```

However when I add this view to a region it displays no results. However I know that it's trying to display something because I see this in my source.

```
<div class="region region-slide-menu">

</div>

```

My info file that is defining the regions looks like this

```
;regions
regions[main_menu] = Main Menu
regions[header] = Header
regions[content] = Content
regions[help] = Help
regions[slide_menu] = Slide Menu
regions[footer] = Footer
regions[sidebar_first] = Left Sidebar
regions[sidebar_second] = Right Sidebar

```

and I'm calling the region like this

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

```

I'm using Drupal 7 and this is a custom theme I've built. I've cleared the cache multiple times.

# Answer
> 0 votes
The issue was the location of

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

```

Placing it inside of a unordered list prevented it from rendering anything. Not even in the source. Placing it outside of the list allowed it to render properly.

# Answer
> 0 votes
Verify which of the blocks you have enabled for the theme you're using. To do so, navigate to admin/structure/block. Somewhere your "block created with views" should be listed there. If it is within "Disabled" (near the bottom), then you need to indicate there in which region (like sidebar 1st, sidebar 2nd or something similar?) you want that block to be displayed.

From what you seem to experience, it seems that hardly any block is enabled (most seem to be disabled).

PS: just to be sure, try to clear the cache ... it doesn't hurt, but sometimes that is what is required ...

---
Tags: views, blocks
---


# Question
Title: Question about steps to convert from Ubercart to Drupal Commerce
After running into some discount functionality/module install issues with Ubercart for Drupal 7, my client has agreed to try Drupal Commerce. Do I need to completely remove everything related to Ubercart before Drupal Commerce can work, or can I unpublish the existing Ubercart content and disable the modules to allow my client to give it a test drive?

I see that there are some machine names that are the same from one to the other, which could pose a problem.

# Answer
The two projects are incompatible because of the lack of name spacing in Drupal 7. Your best bet will be to completely delete all of the Ubercart related content and uninstall all of its modules. For obvious reasons, I'd recommend not doing this on your client's live site. Create a copy from a backup and perform your test / research in that.
> 0 votes

# Answer
I agree with Ryan. We tried the same thing and NEVER recovered the site. You might be entering the world of spaghetti. It was Drupal 6 however. Whatever your "discount functionality/module install issues" are - would probably be easier to ***work through*** than converting to Drupal Commerce. ALSO if you take the time to count the modules available or that could be converted and fixed using Coder - AND the number of Drupal core contributors who actually develop for Ubercart also - you might find a stronger case for staying with Ubercart after all
> 0 votes

# Answer
This is a partial answer: In the process of deleting Ubercart, I found that Product Classes created in Ubercart, remain in Content Types. Of course, the cart fields are missing, but all the custom fields created for client needs are still available.

Partial question remaining to be answered: can these Content Types be connected to Drupal Commerce as Products?
> 0 votes

---
Tags: commerce, ubercart
---


# Question
Title: How do I use an array with an 'IN' condition on EntityFieldQuery::entityCondition?
I read that entityCondition should take an array, and I've constructed an array according to examples I've seen on the web. But no dice. I get the error below. If I use a string, the error goes away.

Here's my code:

```
$query = new EntityFieldQuery();
$types = array('commerce_product', 'produce_share');
$query->entityCondition('entity_type', $types, 'IN');
$result = $query->execute();

```

And here's the error:

```
Warning: Illegal offset type in isset or empty in entity_get_info() (line 7690 of /**/includes/common.inc).
Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1573 of /**/includes/bootstrap.inc).
EntityFieldQueryException: Entity <em class="placeholder"></em> has no base table. in EntityFieldQuery->propertyQuery() (line 1209 of /**/includes/entity.inc).

```

# Answer
Correct me if I'm wrong, but aren't commerce\_product and product\_share bundles not entity\_type's (both of entity\_type node)?

I think you may want:

```
// The types we're looking for.
$types = array('commerce_product', 'produce_share');

// Build the query.
$query = new EntityFieldQuery()

  // Looking for nodes.
  ->entityCondition('entity_type', 'node')

  // With the specific bundles.
  ->entityConditiion('bundle', $types, 'IN');

// Run the query.
$result = $query->execute();

```

https://www.drupal.org/node/1343708
> 1 votes

# Answer
I know this answer comes almost a year too late for you, but I dealt with the same problem and found out why the answer is you can't.

According to the API:

> While the field storage engine might support field conditions on more than one entity type, there is no way to query across multiple entity base tables by default.

Which means you can't query both the comment and node entity types with one entity field query because they derive from two separate database tables.

Simple Solution: I performed two separate queries and concatenated the results together.
> 1 votes

---
Tags: entities, database
---


# Question
Title: How can i include views page in search results
I had created a view called "donor" with a page display. I includes nodes from content type "Donor-node". The title of "donor" views page is "donor wall". I created a view with type as content, which lists all nodes. An exposed search form with search term field. Is there any way to include "donor wall" page in this search results. If any one search for a key word donor, donor wall needs to list in result.

# Answer
> 0 votes
Building a page via the views interface implements this page with the hook\_menu. An entirely different approach from the nodes wich are saved in the database.

Views is essentially a query engine wich basically searches those database tables (and only one base table per view).

There is no real way to make a hook\_menu implementation appear a node view. Ollies advice to put your view into a block and add it to a node is probably the best viable option.

---
Tags: search
---


# Question
Title: Client needs Ubercart member sign up function, but there is error with edit/option_prices
I have a Drupal 7 client with Ubercart installed. They would like to add a Membership feature to their site where the members can receive a discount on their products and services.

We have Ubercart Price Per Role installed (in spite of it not being updated since 2013 which makes me nervous), which has added a nice little Member Price field in Product. I have added a test Product Class called Memberships to allow for membership levels.

I understand that a Role can be assigned to a Product Class through Attributes and Options to allow for membership expiration dates. Attributes and options have worked just fine for other products, but when I clicked the link for 'Note: "Price" column is the default option price. To set option prices per role use the options prices form.' 'I get The requested page "/?q=node/test/edit/option\_prices" could not be found.'

Now it is entirely possible that I am trying to do it all wrong and that fixing that error won't get me the solution I'm looking for. So, I would also like to hear hetherw I just headed down a rabbit hole, as well as finding out why the edit page cannot load.

# Answer
> 0 votes
If there is a problem it sounds like it's an issue with the menu tab links being generated for your nodes; **node/test/edit/option\_prices** isn't a valid path, it should should be something like **node/$nid/edit/option\_prices**.

The module enables that path if the UC Attributes module is enabled. It sounds like you've installed that module so I would substitute "test" with whatever product NID you're trying to test. Once you've confirmed it's working there, you can troubleshoot why your tab link is generating a bogus path.

---
Tags: ubercart
---


# Question
Title: Entityform is spanning the full width of the browser. Well beyond page margins
http://chesapeakeregional.com/volunteer#overlay-context=volunteers

I did not create the form, nor the site, nor do I have any knowledge of Drupal. But somehow I got assigned to make this form fit within the normal width of the site and I'm clueless. If I'm not being clear, I basically just want to wrap the form with a div about 1140px wide and center it horizontally in the browser.

Please help!

# Answer
> 1 votes
The problem lies in the somewhat flawed structured and logic of the theme. The best solution to this would have been to restructure the theme and apply the styles for the `container` class, which handles most of the content layout, to a wrapper in the `page.tpl.php` template so that all pages get the same layout no matter content.

However, as the theme is as it is, and you don't have much Drupal knowledge I would instead recommend to apply the "container" class to the form element, or wrap the form in a div with that class. Unfortunately you can't do that in the UI.

The fastest and easiest way to fix this is to add the class to the form using hook\_form\_alter().

In your `/sites/all/themes/chesapeake/template.php` file, add:

```
/**
 * Implements hook_form_alter().
 */
function chesapeake_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'volunteer_form_entityform_edit_form') {
    $form['#attributes']['class'][] = 'container';
  }
}

```

And then clear the cache at `Configuration > Development > Performance`. That should add the "container" class to the form and display the page correctly.

---
Tags: entities, theming
---


# Question
Title: how to use two different feeds on one drupal
I am using drupal.org/project/views\_export\_xls Views Excel export I added two different feeds to my drupal view , but only one of them (the second one) shows as an icon on the page , and if I remove the second one the first one shows up on the page. how can I see both of them on the view page?

# Answer
> -1 votes
I was able to create a page view w/ two RSS icons with the following steps.

1. Create a view with a **page** display.

2. Add a first "feed" display. You can customize what you want the feed to return here.

3. Set a path for the first feed display.

4. Attach the first feed display to the "page" display.

5. Repeat steps 2-4 to create and attach a second feed display. It should look something like this.

6. Save the view and view the page. There should be two separate feed icons.

I hope this helps!

---
Tags: views, feeds
---


# Question
Title: How to delete/block a list of users contained in a CSV file?
I'm looking for a solution that allows me to delete/block users from a CSV file.

**Here is more information of the solution that I'm looking for:**

I have a CSV with a list of users that are spam or not responding to emails. I would take that list and give it to a Drupal module and corresponding delete or block or make inactive users.

Ideally, it would work like logintoboggan:

* Disable the account and keep its content.
* Disable the account and unpublish its content.
* Delete the account and make its content belong to the Anonymous user.
* Delete the account and its content."

User should be able to set that for the batch.

How can I achieve this? If there is a module that can take me to a similar direction, that would be fine too.

# Answer
You really don't need a CSV; all you need is the identifying column (e.g. `mail` or `uid`). To that end, you have one option with the Bulk User Delete module.

> This module allows you to bulk delete users through the admin interface. You provide a list of email addresses, one per line, and the users are deleted using the batch processing API.

With this module, you can grab your mail column to feed into the interface to bulk delete.
> 6 votes

# Answer
As Shawn Conn said, the Bulk User Delete module seems like it would work. If you're looking for more of a one time quick-and-dirty solution, you could accomplish it with a shell script and Drush like so:

```
#!/bin/sh
while read username; do
  drush user-cancel $username
done < list_of_usernames.txt

```

See http://www.drushcommands.com/drush-7x/user/user-cancel for more info on that Drush command.
> 5 votes

---
Tags: users, advertising
---


title: Putting sites online

text:
# Question
Title: Putting sites online
Well, I'm finally ready to put my five-site multi-site installation online. This community has been a great help in getting me to this point. So thank you all for that.

I'm a bit nervous about the gotcha's that await me in this next step -- discovering differences in operation between my local environment and the one online. I'm running XAMPP on my computer with Apache 2.4.10, PHP 5.6.3, and MySQL 5.6.21. Drupal core and all modules are up-to-date. In addition to each site's database, there is an extra db that is accessed by all sites for common data. For the online system, I plan to select a host company from the list on the Drupal.org, so I can expect them to have all the right stuff. I plan to get a shared server account.

In my current ASP sites (which these Drupal sites will replace), I've been able to develop the sites entirely on my local computer and then just upload the files to the online server and I don't think I've ever had a problem with any differences in operations. My scripts are set up to detect whether they are running locally or online and adjust certain things (such as inter-site URLs accordingly). I've attempted to develop things in Drupal to work that way too, but I'm not sure if there are differences I don't yet know about. I'm concerned about this because on the ASP sites I never had to instal any software. The server company instals whatever is necessary to run the site and I just uploaded files compatible with their software. But in Drupal, I've had to instal Drupal over again for each site, so I'm a bit unsure about how this will translate to the online environment.

So one question I have: Is it possible to simply FTP the entire Drupal folder plus the MySQL database to an online server and have a functioning set of sites, or do I need to go through the installation process on the online computer again for each site?

The doc page on *Migrating a site* says that it is for single site and that migrating multi-sites is covered elsewhere, but doesn't say where. Even for a single site, it lays out a 16-step process in which I don't think I'll understand most of the steps until I've done them. In any case, that page seems to say that the answer to my above question is very much NO, that I cannot do this by just copying files over.

Anything helpful to suggest on entering this process?

# Answer
To answer your question: Yes. All you should need is your code sitting on a web server and your data sitting in a database for your Drupal site to go live.

As for suggestions, I have a few regarding workflow. Drupal has a lot of pain points with deployment because not only is the content stored in the database, but most of the configuration is as well. So while you can upload modules, the settings need to be manually set on production, automatically deployed with the Features module, or automatically deployed with update hooks in modules.

Uploading your site for the first time via FTP will work, but it's usually a lot more complicated when deploying updates. Here are a few things that you should learn to help combat this:

My first suggestion would be that you set up a development server (your local dev will work), a staging server to test your deployments, and a production server which will host your live site. It's crucial to have this (or something similar) so you can catch any problems and avoid a production down situation.

Second, you should learn how to use Git for version control to manage and deploy your code. You should use it for all projects, actually, even if you're not deploying them. I cannot tell you how many times I've rolled a change to production that broke the site and was able to roll back with one command. I'm not going to try and convince you why using version control is a good idea because there is an entire internet that says you should. Here is just one article: http://www.git-tower.com/learn/git/ebook/mac/basics/why-use-version-control

Third, assuming that you're using Drupal 7, you should use the Features module to store your settings in code and deploy them via git. Features is a necessary evil in order to accomplish this, and there are a ton of quirks that give it a huge learning curve, but it's worth it in the long run. This answer seems pretty solid. A more advanced and custom approach is to use calls to hook\_update\_n in your modules to automatically deploy database updates and settings. This article Does a good job explaining it.

Fourth, and probably most importantly, **BACK UP YOUR DATABASE AND YOUR CODE**. As I mentioned before, Drupal makes heavy use of the database. If you lose that, you lose your site. Make sure you have scheduled backups for your database (and your code if it isn't in Git).

I'm not trying to scare you, but I'll be honest: if you do decide to go this route (and I believe I'm not the only one who thinks you should), there will be a lot to learn and a ton of frustration at first. I can tell you that you're going to have a maintenance nightmare on your hands if you plan to deploy updates by uploading files via FTP.

I have been to a lot of talks and training on this subject at Drupal Camps, Drupal Cons, and Drupal meet-ups, and I'm still learning how to manage deployment. Once you learn the tools and get your workflow down, things will go a lot smoother and you'll be able to recover quickly if anything bad happens.

I hope this helps. Let me know if you have any questions!
> 8 votes

# Answer
Yes, all you need to is to upload your codebase (via FTP) and import your database (via a MySQL client like phpMyAdmin, MySQL Workbench, Sequel Pro, or the command line tool `mysql`) to the remote server. From there, all that's needed is to make sure the **settings.php** for each domain points to the correct server.

A few pieces of advice:

* Turn off all CSS/JS aggregation before you move the files/DB. One common issue I've hit is broken CSS/JS because of missing files, unwritable file directories, or something else different about the file environment.
* Be prepared for WSOD's that might occur because you don't have PHP dependencies in your new environment. d.o. has a good writeup on how to troubleshoot this problem if you hit it.
* Check for any PHP errors in the site logs. If you do hit any problems with an environment change, it's likely to show up in the form of PHP errors/warnings.
> 4 votes

---
Tags: migrations
---


# Question
Title: Views Taxonomy get children of a specific parent term within a vocabulary
I have a taxonomy vocabulary with 2 parent terms with children (fishing, and hunting) I want to get all children of the fishing parent term. I've tried to do it with core, but not sure it is possible.

# Answer
> 1 votes
I'm not exactly sure what you need to implement, but here are the steps to get you what I think you need. For demonstration, I created my own vocabulary with animals like so:

Then I created a view that will accept any of the term names as a contextual filter and return its children like so:

If that's what you need, then here is how you create the view. I'm not sure how you wanted to display them, so I didn't create a page or block display.

**Step 1: Add new view**

**Step 2: Add contextual filter for parent term**

**Step 3: Configure the contextual filter like so**

Save that contextual filter to the view and it will return the children based on the name of the term you pass to it. There may be additional steps to get it working the way you want it, but you weren't really specific. I hope that gets you started.

# Answer
> 0 votes
You may install Taxonomy Edge module and use "Taxonomy edge: Parent term ID" in Contextual filters

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


title: Display a view inside a <nav> and <ul>

text:
# Question
Title: Display a view inside a <nav> and <ul>
I have a view that outputs list items as links. Like so

- Link 1
- Link 2
- Link 3
- Link 4

I need to be able to wrap those items in

```
<nav class="customclass">
    <ul>

```

And close them. However when I attempt to do this in the template. Or in a basic page that is using a function to display the view.

When I attempt

```
<nav class="customclass">
    <ul>
        <?php print views_embed_view('mobile_slide_menu','block');?>
    </ul>
</nav>

```

I end up with

```
<nav class="customclass"><ul>
    <div class="view-content mm-panel" id="mm-m0-p1">
      <div class="container">
          <li><a href="example.com">Link 1</a></li>
          <li><a href="example.com">Link 2</a></li>
          <li><a href="example.com">Link 3</a></li>
          <li><a href="example.com">Link 4</a></li>
      </div>
    </div>
</ul></nav>

```

Which doesn't work for my list. Is there any way to take only the list items and prevent it from being wrapped in all those containers. And if not is there a way to append the opening and closing tags of 'nav' and 'ul' within the view?

# Answer
> 3 votes
A tutorial with more detail can be found here tutorial. But in short what you want to do is the following:

Find the correct .tpl file and copy it into your theme. Edit the .tpl in your theme and remove the wrappers. Don't forget to flush caches after inserting a new template. All the template files are in the sites/all/modules/views/theme folder (depending on where exactly you installed views). There are quite a lot of them and the view templating is quite complex, luckily views helps you with a list to find the right one.

You can find the list of template names you can use in the views interface (where you edit your view) under the advanced tab. Look for the Theme: information item. Clicking it will give you the list of all the .tpl files this view would use if able (ordered from most general to most specific and highlights the current one).

Note

Be as specific as possible to prevent accidentally breaking other views (rename the template file if to match the name in the list). more about the view templates

# Answer
> 0 votes
To remove extra views container markups

On your view's edit page. Under **Format** click on the 1st **settings** and uncheck `Add views row classes` and `Add striping (odd/even), first/last row classes`

Also, on the 2nd **settings**, uncheck `Provide default field wrapper elements`

Lastly, click on your field, and under **STYLES SETTINGS** make sure everything is unchecked

---
Tags: views, theming
---


title: Render fields url in tpl.php

text:
# Question
Title: Render fields url in tpl.php
I have a content type (music) with fields(image,track,title). I used a soundmanager player to display my track with its tpl.php(bar.tpl.php).

I have tried to display url of the image field inside the (bar.tpl.php) but got only (http://localhost/mysite) using this code

```
<div class="sm2-inline-element album-art">
 <img src="<?php $file = file_load($node->field_image_boss['und'][0]['fid']);
  print file_create_url($file->uri); ?>" />
</div>

```

# Answer
I use IMAGE URL FORMATTER module

Then on view's, click on your field, for formatter you can select Image URL.

**Then on your tpl.php file use** `<?php print $fields["field_image_boss"]->content; ?>`

**Note** if you see that your field gets printed with extra markup such as `<span>url</span>` instead of just `url`. Then you need to remove extra views container markups

On your view's edit page. Under Format click on the 1st settings and uncheck Add views row classes and Add striping (odd/even), first/last row classes

Also, on the 2nd settings, uncheck Provide default field wrapper elements

Lastly, click on your field, and under **STYLES SETTINGS** make sure everything is unchecked
> 0 votes

# Answer
You can use image\_style\_url if you only want to dsplay an image. Like this:

```
<div class="sm2-inline-element album-art">
 <img src="<?php $file = file_load($node->field_image_boss['und'][0]['fid']);
  print image_style_url('STYLE_NAME (e.g. large, or use custom)', $file->uri); ?>" />
</div>

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to create wrapping menu tabs with CSS in Omega
I'm using the menu api (MENU\_LOCAL\_TASK) to create tabs in Drupal 7. In Omega, I can't figure out how to wrap the tabs in css so that they are responsive. I'm new to Omega. This was easily accomplished in other themes.

# Answer
> 0 votes
It appears that the default system.menus.css in Drupal sets the white-space property to:

* white-space: nowrap;

The default value for white-space is normal. So, if you set the white-space property on your menu's UL to white-space:normal they will wrap when your screen size gets smaller.

I placed the following in my global.css.

* ul.primary {white-space: normal; }

---
Tags: 7, theming
---


title: how detect form is submitted?

text:
# Question
Title: how detect form is submitted?
I use Drupal 7 and the Webform module.

How can I know if a form is submitted or not? I need this to show either error messages or success message after form submission in form page.

I prefer not to write a module because I think it is unnecessary to write a module for a very small task.

Some more info to further explain my question:

* I already know about the setting for Webform per form. This setting is located "Content \> Webforms(tab) \> Edit(your form) \> Webform(tab) \> Form settings" (where you can add the confirmation message or redirect to a Custom URL).
* Actually I render my webform in my `node--contact.tpl.php` and I use the Webform Validation module for my form validations. And with the `form_get_errors` function I get errors and loop through them and show them. And if submission is successful I show form successful submission message. I just don't know how to detect whether form is submitted or not.

# Answer
> 0 votes
I solved this problem with drupal\_get\_messages() function ! the result of this function is different for when form is submitted and also for when form is not submitted.

# Answer
> 0 votes
There a setting for Webform per form. This setting is located "**Content \> Webforms(tab) \> Edit(your form) \> Webform(tab) \> Form settings**". You can add the confirmation message or redirect to a Custom URL.

---
Tags: webforms, forms
---


# Question
Title: Why is my Language Switcher Dropdown block NOT displayed in my site?
I have a multi-language site in Drupal 7. And I use the Language Switcher Dropdown module in it. I enabled all the settings required by this module, as described in the module's readme.txt. I have also assigned the block to new region. But still the Language Switcher Dropdown block is not displayed anywhere in my site.

What are the other settings I may have to review/configure? Or maybe there is a possible plugin which conflicts with this one that causes the block not to be displayed?

# Answer
> 3 votes
make sure that:

1. add few languages to site here - admin/config/regional/language
2. enable one of Detection Methods here - admin/config/regional/language/configure
3. clear cache

# Answer
> 0 votes
I'm assuming that you also enabled the core modules "Locale" and "Content translation", as mentioned in the modules Community documentation (so that's probably not the reason for the block being displayed). And I'm assuming that you have more then 1 language enabled (otherwise there is no other language to switch to, right?).

However, a *possible* reason for the block not being displayed, is because of what is mentioned in the issue "Does not work without URL-detection" ... More specifically in Comment #3 of that issue it says:

> If not url detection, nor session detection or both are enabled then the switcher will not be shown by design as on those cases the selection of the language is done by other means: user profile, language sended by browser, **so there is no reason to show a switcher**.

Curious to hear if "this" is what explains your issue ... If this is not the reason in your case, then consider editing your question a bit to eliminate this as possible reasons.

---
Tags: i18n-l10n
---


title: Using ajax in my entityform

text:
# Question
Title: Using ajax in my entityform
I have a content type called Area and another content type called apartment that has a reference to area.

I have an Investment form (using entityform module) in which users select which area; after that, users should be able to see apartments in that area in a select box. (This feature should be implemented wit ajax.)

I want to have some filters on areas and apartments like views module filters (for example apartment which are not sold). How should I implement these features?

and here's my node--invest.tpl.php:

```
<?php $language = $GLOBALS['language']; if ($language->language == $node->language): ?>
    <div class="panel">
        <div class="viewport">
            <div class="main match-height">
                <div class="col-con">
                    <div class="col-1-1">
                        <?php echo $custom_content['body'] ?>
                    </div>
                </div>

                <div class="col-con">
                    <?php foreach($custom_content['panels'] as $panel): ?>
                        <div class="col-1-2">
                            <div class="roadmap">
                                <h3><?php echo $panel['title']?></h3>
                                <ul>
                                    <?php foreach($panel['steps'] as $step): ?>
                                        <li><?php echo $step ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="sidebar match-height">
                <h3><?php echo $custom_content['form_title'] ?></h3>
                <p><?php echo $custom_content['form_body'] ?></p>
                <div class="form">
                    <?php print drupal_render($entityform) ?>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

```

And if you wonder what is `$custom_content`, this is the code that generates it.

```
function get_invest_page_data($node) {
    $invest = [];
    $invest['title'] = $node['title'];
    $invest['body'] = $node['body'][0]['value'];
    $invest['form_title'] = $node['field_form_title'][0]['value'];
    $invest['form_body'] = $node['field_form_body'][0]['value'];
    $invest['panels'] = [];

    if ( ! empty($node['field_step_panel'])) {
        $i = 0;
        foreach ($node['field_step_panel'] as $panel_key) {
            $panel = load_collection($panel_key['value']);
            $panels[$i] = [];
            $invest['panels'][$i]['title'] = $panel->field_invest_panel_title['und'][0]['value'];

            $steps_keys = $panel->field_invest_panel_step;

            $j = 0;
            foreach ($steps_keys['und'] as $step_key) {
                $step = load_collection($step_key['value']);
                $invest['panels'][$i]['steps'][$j] = $step->field_invest_panel_step_body['und'][0]['value'];
                $j++;
            }

            $i++;
        }
    }

    return $invest;
}

```

This code exists in template.php. The following line is used in `theme_prepreprocess_node()`.

```
$node['custom_content'] = get_invest_page_data($node);

```

# Answer
> 1 votes
The ajax from a form is handled by the form function itself wich is edited in the mdule layer, not in the template layer. The custom module approach would be.

Find the id of the entity form, see this Tutorial

Once you have the id you can use the `MY_MODULE_form_FORM_ID_alter` to edit the form elements to use ajax. See this Tutorial for more info on ajax forms.

If you want the ajax callback to alter an external element/several wrappers you can use the `ajax_command_*` functions to change pretty much anything selectable by JS. Have the ajax callback return something like this. (you won't need to set the #ajax wrapper in this case).

More about the drupal's ajax\_command\_\* functions

```
function AJAX_CALLBACK_CALLED_FROM_FIELD($form, &$form_state){
  $commands[] = ajax_command_html('JQUERY_SELECTOR', 'VALID_HTML'); // Or any other valid ajax command.
  return array(
    '#type' => 'ajax',
    '#commands' => $commands
  );
}

```

---
Tags: 7, forms, ajax, entities
---


# Question
Title: add a repeatable autopopulate node title select list to custom block
I'm going to develop a new block that user can select 4(or more) node with 4(or more) autopopulate node selection list but i couldn't find any documentation or tutorial on how to build those select list.

Any suggestion?

# Answer
> 1 votes
You can use form select options

put the list of your nodes in to an array and pass them into the form function

```
function mylist_form($form, &$form_state, $args) {
$mylist = array();
foreach ($args as $node){
$mylist[$node->nid]= $node->title;
}

$form['mylist'] = array(
  '#weight' => '1',
  '#key_type' => 'associative',
  '#multiple_toggle' => '1',
  '#type' => 'select',
  '#options' => $mylist,
  '#title' => 'Select nodes',
);
 return $form;
}

```

after in the block view function you can render the form

```
$mylistform = drupal_get_form('mylist_form' , $nodes );

```

---
Tags: forms
---


# Question
Title: How to check if a library is present during installation?
How can I check if the library, which is required by my module, is present while the module is getting installed?

I have used `hook_requirements` with the `libraries_detect` function with `REQUIREMENT_ERROR` severity. This restricts the module from getting installed irrespective of the library is present of not.

Here is my code:

```

function hook_requirements($phase) {
  $requirements = array();
  $t = get_t();
  if ($phase == 'install') {
    if (function_exists("libraries_detect") && !libraries_detect('external-lib-api')) {
      $requirements['library_api'] = array(
        'severity' => REQUIREMENT_ERROR,
        'description' => $t(
          'The required Libarary is not installed.'
        )
      );
    }
  }

  return $requirements;
}

```

Am I doing something wrong in this? Is there any other way of doing it?

# Answer
> 4 votes
this is one of the working example from my module. I hope this helps you

```
function sfs_requirements($phase) {
  $requirements = array();
  $t = get_t();
  if ($phase == 'install' && function_exists('libraries_get_path')) {
     $plupload_path = libraries_get_path('plupload');
     $chosen_path = libraries_get_path('chosen');
     if (!$plupload_path) {
       $requirements['plupload'] = array(
         'severity' => REQUIREMENT_ERROR,
         'description' => $t('Secure File Share module requires !plupload, which is missing. Download and extract the entire contents of the archive into the %path directory on your server.',  array('!plupload' => l($t('Plupload Library'), 'https://github.com/moxiecode/plupload/archive/v1.5.8.zip'), '%path' => 'sites/all/libraries/plupload')),
       );
     }
     if (!$chosen_path) {
        $requirements['chosen_js'] = array(
          'severity' => REQUIREMENT_ERROR,
          'description' => $t('Secure File Share module requires !chosen, which is missing. Download and extract the entire contents of the archive into the %path directory on your server.', array('!chosen' => l($t('Chosen Library'), 'https://github.com/harvesthq/chosen/releases/download/v1.3.0/chosen_v1.3.0.zip'), '%path' => 'sites/all/libraries/chosen')),
        );
      }
  }
  return $requirements;
}

```

---

Karthik

# Answer
> 0 votes
You should change

```
hook_requirements($phase)

```

into this

```
 Name_of_your_module_requirements($phase)

```

"library\_api" is not a Library is a module https://www.drupal.org/project/libraries

for create a module dependency you can add a line into your module .info file like this :

```
dependencies[] = libraries

```

# Answer
> 0 votes
You may want to look at how module Forena is handling this, around line 429 of forena.module:

```
function forena_library_file($library) {
  $libraries = array(
      'dataTables' => 'dataTables/media/js/jquery.dataTables.min.js',
      'mpdf' => 'mpdf/mpdf.php',
      'SVGGraph' => 'SVGGraph/SVGGraph.php',
      'prince' => 'prince/prince.php'
  );
  $path = isset($libraries[$library]) && file_exists('sites/all/libraries/' . $libraries[$library]) ? 'sites/all/libraries/' . $libraries[$library] : '';
  return $path;
}

```

FYI: Forena interfaces with up to 4 libraries, which is why you'll 4 such entries around there.

---
Tags: installation, theming
---


# Question
Title: Why am I getting "Your browser does not support iframes" in multiple browsers?
I want to display a third party page within my theme and thought an `<iframe>` should do. However, I added the `<iframe>` to my basic page, selecting`Full HTML` but all I'm getting is `Your browser does not support iframes` with multiple browsers while I can use the iframe on the W3School website just fine. Why is this?

The link: http://spabc.com/drupal/content/store

# Answer
> 0 votes
I figured out that it's because I'm using CKEditor.

When editing the page, I had to click on **Switch to plain text editor** in order to get the iframe to load. CKEditor would convert that HTML into a misleading string of **Your browser does not support iframes**.

---
Tags: theming
---


title: How do I use "NOT IN" in a query?

text:
# Question
Title: How do I use "NOT IN" in a query?
What is the proper way to write a query containing 'NOT IN' using a condition statement?

My query is the following one:

```
SELECT DISTINCT nid FROM node WHERE language NOT IN
  (SELECT language
    FROM languages WHERE language = 'ab');

```

I've tried something like the following:

```
$query->condition('n.' . $key, $value, 'not in (select language from
  languages where language = $value)');

```

# Answer
In the specific example, you should simply write the condition as:

```
$query->condition('n.language', 'ab', '<>');

```

In the generic case, where you need to select the rows in a database basing on the values returned from a sub-query, you should consider what follows:

* "NOT IN" is accepted as operator from `SelectQuery::condition()`. In fact, the following query would be executed:

```
$query = db_select('node', 'n')->fields('n');
$query->condition('n.nid', array(1, 2, 3), 'NOT IN');
$nodes = $query->execute();

foreach ($nodes as $node) {
  dsm($node->nid);
}

```
* As reported in Conditional clauses ("Subselects"), `SelectQuery::condition()` accepts also an object implementing `SelectQueryInterface` as value for `$value`, such as the one returned by `db_select()`; the problem is that actually you can just use it when the value of `$operator` is equal to `"IN"`. See Subselects don't work in DBTNG conditions, except when used as value for IN.

The only way I can see to use the "NOT IN" operator with a sub-query in `condition` is to:

* Execute the subquery to get an array
* Execute the main query setting the condition as in the following snippet

```
$query->condition($key, $subquery_result, 'NOT IN');

```

`$subquery_result` is the array containing the result of the sub-query.

Otherwise, you could use `where()` as others said, which accepts a string for the part of the query you need to add.

Keep in mind that `db_select()` is slower that `db_query()`; you should use the first when you know the query could be altered by other modules. Otherwise, if other modules are not supposed to use `hook_query_alter()` to alter your query, you should use `db_query()`.
In the case of accessing nodes, if you need to obtain only the nodes to which a user has access, then you need to use `db_select()` and add `'node_access'` as tag of the query, with `SelectQuery::addTag()`. For example, `blog_page_last()` uses the following code.

```
  $query = db_select('node', 'n')->extend('PagerDefault');
  $nids = $query
  ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('type', 'blog')
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('created', 'DESC')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access')
    ->execute()
    ->fetchCol();

```

Similar code is used by `book_block_view()`.

```
$select = db_select('node', 'n')
  ->fields('n', array('title'))
  ->condition('n.nid', $node->book['bid'])
  ->addTag('node_access');
$title = $select->execute()->fetchField();

```
> 45 votes

# Answer
When writing complex queries you should definitely use `db_query()` instead of `db_select()`.

1. You can't write a `NOT IN` clause with a subquery with the current Drupal database API (it's a know issue being worked out).
2. If you don't need your query to be dynamic (hence rewritten by others modules), don't bother trying to write such a complex one with `db_select()`.
3. Subqueries aren't well supported yet (see a previous answer of mine) and if you're used to write SQL it's way easier to use `db_query()`.

Regarding your query, I'm not sure why you want to use a subquery (unless you simplified your exemple) ? You can write it easily like this:

```
SELECT nid
FROM node n INNER JOIN languages l ON n.language = l.language
WHERE language NOT IN ('ab')

```

`DISTINCT` isn't necessary as `nid` is a primary key so it won't be duplicated.
> 5 votes

# Answer
There's also where() which allows to add an arbitrary where condition to the query.

Example:

```
$query->where('n.language NOT IN (SELECT language FROMlanguages WHERE language = :lang)', array(':lang' => $value));

```

As keithm mentioned, you must use db\_select() and addTag('node\_access') when selecting nodes which are then displayed to users.
> 4 votes

# Answer
An easier way to use db\_select with a NOT IN subselect is just to use the little known

$query-\>where

to add an arbitrary where condition.

e.g:

```
  // Count query for users without rid 3
  $query = db_select('users', 'u');
  $query->fields('u', array('uid'));
  $query->where('u.uid NOT IN(select uid from {users_roles} where rid = :rid)', array(':rid' => 3));
  $count = $query->countQuery()->execute()->fetchField();
  drupal_set_message($count);

```
> 2 votes

# Answer
Where $subquery\_values is an array of $key =\> $nid format as result of a subquery

```
$query->condition('node.nid', array_values($subquery_values), "NOT IN");

```

it works fine.
> 1 votes

---
Tags: 7, database
---


# Question
Title: Having trouble figuring out PDO Exception
I am trying to figure out what is causing my PDO Exception.

It's for a custom entity, and I had to rename some table columns because the API data changed (and it was easier to do it this way). It keeps seeming to be saying that something is malformed in my query, but I can't for the life of me figure out what it is - all of the data looks correct, and the entity object right before saving looks entirely normal too.

Here's the exception:

> PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'change, changein\_percent, volume, average\_daily\_volume, bid, ask, previous\_close' at line 1: INSERT INTO {stockinfo} (symbol, name, last\_trade\_with\_time, last\_trade\_price\_only, last\_trade\_date, last\_trade\_time, change\__percent\_change, change, changein\_percent, volume, average\_daily\_volume, bid, ask, previous\_close, open, days\_range, year\_range, change\_from\_year\_low, percent\_change\_from\_year\_low, change\_from\_year\_high, percebt\_change\_from\_year\_high, earnings\_share, p\_e\_ratio, short\_ratio, dividend\_pay\_date, ex\_dividend\_date, dividend\_yield, market\_capitalization, oneyr\_target\_price, e\_p\_s\_estimate\_current\_year, e\_p\_s\_estimate\_next\_year, e\_p\_s\_estimate\_next\_quarter, price\_e\_p\_s\_estimate\_current\_year, price\_e\_p\_s\_estimate\_next\_year, p\_e\_g\_ratio, book\_value, price\_book, price\_sales, e\_b\_i\_t\_d\_a, fiftyday\_moving\_average, change\_from\_fiftyday\_moving\_average, percent\_change\_from\_fiftyday\_moving\_average, two\_hundredday\_moving\_average, change\_from\_two\_hundredday\_moving\_average, percent\_change\_from\_two\_hundredday\_moving\_average, stock\_exchange, updated) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9, :db\_insert\_placeholder\_10, :db\_insert\_placeholder\_11, :db\_insert\_placeholder\_12, :db\_insert\_placeholder\_13, :db\_insert\_placeholder\_14, :db\_insert\_placeholder\_15, :db\_insert\_placeholder\_16, :db\_insert\_placeholder\_17, :db\_insert\_placeholder\_18, :db\_insert\_placeholder\_19, :db\_insert\_placeholder\_20, :db\_insert\_placeholder\_21, :db\_insert\_placeholder\_22, :db\_insert\_placeholder\_23, :db\_insert\_placeholder\_24, :db\_insert\_placeholder\_25, :db\_insert\_placeholder\_26, :db\_insert\_placeholder\_27, :db\_insert\_placeholder\_28, :db\_insert\_placeholder\_29, :db\_insert\_placeholder\_30, :db\_insert\_placeholder\_31, :db\_insert\_placeholder\_32, :db\_insert\_placeholder\_33, :db\_insert\_placeholder\_34, :db\_insert\_placeholder\_35, :db\_insert\_placeholder\_36, :db\_insert\_placeholder\_37, :db\_insert\_placeholder\_38, :db\_insert\_placeholder\_39, :db\_insert\_placeholder\_40, :db\_insert\_placeholder\_41, :db\_insert\_placeholder\_42, :db\_insert\_placeholder\_43, :db\_insert\_placeholder\_44, :db\_insert\_placeholder\_45, :db\_insert\_placeholder\_46); Array ( \[:db\_insert\_placeholder\_0\] =\> AAPL \[:db\_insert\_placeholder\_1\] =\> Apple Inc. \[:db\_insert\_placeholder\_2\] =\> 4:00pm - 130.28 \[:db\_insert\_placeholder\_3\] =\> 130.28 \[:db\_insert\_placeholder\_4\] =\> 5 \[:db\_insert\_placeholder\_5\] =\> 4:00pm \[:db\_insert\_placeholder\_6\] =\> -1.50 - -1.14% \[:db\_insert\_placeholder\_7\] =\> -1.5 \[:db\_insert\_placeholder\_8\] =\> -1.14 \[:db\_insert\_placeholder\_9\] =\> 50884452 \[:db\_insert\_placeholder\_10\] =\> 49022000 \[:db\_insert\_placeholder\_11\] =\> 130.51 \[:db\_insert\_placeholder\_12\] =\> 130.53 \[:db\_insert\_placeholder\_13\] =\> 131.78 \[:db\_insert\_placeholder\_14\] =\> 131.25 \[:db\_insert\_placeholder\_15\] =\> 129.90 - 131.45 \[:db\_insert\_placeholder\_16\] =\> 88.93 - 134.54 \[:db\_insert\_placeholder\_17\] =\> 41.35 \[:db\_insert\_placeholder\_18\] =\> 46.5 \[:db\_insert\_placeholder\_19\] =\> -4.26 \[:db\_insert\_placeholder\_20\] =\> -3.17 \[:db\_insert\_placeholder\_21\] =\> 8.05 \[:db\_insert\_placeholder\_22\] =\> 16.19 \[:db\_insert\_placeholder\_23\] =\> 1.3 \[:db\_insert\_placeholder\_24\] =\> 5 \[:db\_insert\_placeholder\_25\] =\> 5 \[:db\_insert\_placeholder\_26\] =\> 1.6 \[:db\_insert\_placeholder\_27\] =\> 750.55 \[:db\_insert\_placeholder\_28\] =\> 148.75 \[:db\_insert\_placeholder\_29\] =\> 9.01 \[:db\_insert\_placeholder\_30\] =\> 9.69 \[:db\_insert\_placeholder\_31\] =\> 1.83 \[:db\_insert\_placeholder\_32\] =\> 14.46 \[:db\_insert\_placeholder\_33\] =\> 13.44 \[:db\_insert\_placeholder\_34\] =\> 1.11 \[:db\_insert\_placeholder\_35\] =\> 22.39 \[:db\_insert\_placeholder\_36\] =\> 5.89 \[:db\_insert\_placeholder\_37\] =\> 3.58 \[:db\_insert\_placeholder\_38\] =\> 72.94B \[:db\_insert\_placeholder\_39\] =\> 128.38 \[:db\_insert\_placeholder\_40\] =\> 1.9 \[:db\_insert\_placeholder\_41\] =\> 1.48 \[:db\_insert\_placeholder\_42\] =\> 121.08 \[:db\_insert\_placeholder\_43\] =\> 9.2 \[:db\_insert\_placeholder\_44\] =\> 7.6 \[:db\_insert\_placeholder\_45\] =\> NMS \[:db\_insert\_placeholder\_46\] =\> 1433009226 ) in drupal\_write\_record() (line 7261 of C:\Users\Desktop\Websites\domain\includes\common.inc).

And here's the entity object:

```
stdClass Object
(
    [symbol] => AAPL
    [ask] => 130.53
    [average_daily_volume] => 49022000
    [bid] => 130.51
    [book_value] => 22.39
    [change__percent_change] => -1.50 - -1.14%
    [change] => -1.50
    [currency] => USD
    [dividend_share] => 2.08
    [last_trade_date] => 5/29/2015
    [earnings_share] => 8.05
    [e_p_s_estimate_current_year] => 9.01
    [e_p_s_estimate_next_year] => 9.69
    [e_p_s_estimate_next_quarter] => 1.83
    [days_low] => 129.90
    [days_high] => 131.45
    [year_low] => 88.93
    [year_high] => 134.54
    [market_capitalization] => 750.55B
    [e_b_i_t_d_a] => 72.94B
    [change_from_year_low] => 41.35
    [percent_change_from_year_low] => +46.50%
    [change_from_year_high] => -4.26
    [percebt_change_from_year_high] => -3.17%
    [last_trade_with_time] => 4:00pm - 130.28
    [last_trade_price_only] => 130.28
    [days_range] => 129.90 - 131.45
    [fiftyday_moving_average] => 128.38
    [two_hundredday_moving_average] => 121.08
    [change_from_two_hundredday_moving_average] => 9.20
    [percent_change_from_two_hundredday_moving_average] => +7.60%
    [change_from_fiftyday_moving_average] => 1.90
    [percent_change_from_fiftyday_moving_average] => +1.48%
    [name] => Apple Inc.
    [open] => 131.25
    [previous_close] => 131.78
    [changein_percent] => -1.14%
    [price_sales] => 3.58
    [price_book] => 5.89
    [ex_dividend_date] => 5/7/2015
    [p_e_ratio] => 16.19
    [dividend_pay_date] => 5/14/2015
    [p_e_g_ratio] => 1.11
    [price_e_p_s_estimate_current_year] => 14.46
    [price_e_p_s_estimate_next_year] => 13.44
    [short_ratio] => 1.30
    [last_trade_time] => 4:00pm
    [oneyr_target_price] => 148.75
    [volume] => 50884452
    [year_range] => 88.93 - 134.54
    [stock_exchange] => NMS
    [dividend_yield] => 1.60
    [percent_change] => -1.14%
    [updated] => 1433009226
)

```

What precisely am I doing wrong? Could it be that one of my columns has the wrong data type set?

This is with a standard MySQL database.

# Answer
> 5 votes
You've got a column called change. And that's a reserved word for mysql. (See the full list in the mysql online documentation).

I think that's the cause for the error you're getting.

Try changing that column name and see how it goes.

---
Tags: 7, entities
---


# Question
Title: Creating linkable images using Flexslider and Slideshow View
I am looking to create the ability to have my slider images link to link specified in my field\_link. I have tried to put the node \[field\_link\], but it is reading as plain text. I have tried a few suggestions, but I must not be doing them right.

Below you will find the current configuration I am using.

**This is how I have set up my Slideshow View:**

**This is how I have set up my Image Field:**

**This is how I have set up my Link Field:**

# Answer
I do this the same way you are doing it. Try putting (rearrange order) the field\_link before/above the field\_image in your view fields list. Views reads through them one at a time.. and as you have it, field\_link isn't yet available when it's processing the field\_image. does that make sense?
> 0 votes

# Answer
I have always had to modify the view template for the specific display to wrap everything in a link properly. The issue is compounded even more when using Picture for responsive image variations.

The custom template changes aren't extensive, but I've not found a re-usable or GUI based method to do this with sliders.
> 0 votes

# Answer
How do you get fields: ? I only have content and feeds etc. not fields.

I have a field collection with three fields: 1: field\_slideshow\_link 2: field\_slideshow\_image 3: field\_slideshow\_title

I want to link the image to the link provided in 1.

so I want to rewrite the output, "Output this field as a link" setting should be \[field\_slideshow\_link\] How do I do that in a collection?
> -1 votes

---
Tags: views, javascript
---


# Question
Title: more fields on a content type or more content types
I know this is a situational/subjective question..... but I am trying to figure out a site architecture for a drupal site.

I have multiple products with different attributes/properties. I could either make one content type called 'products' with multiple fields for all possible attributes ..... or I could could make multiple content types; one for each type of product.

I am just looking for a 'best practice' kind of answer.

should I make one content type with more fields (that may go unused more often)

....

or should I make more content types.

Thanks in advance.

# Answer
My personal preference is to limit the amount of content types, for user friendly reasons. Clients can get confused when you throw a whole list of content types at them. Unless your products are very different to each other (car, washing machine, house), I'd go for the fields.

Maybe the Field Group module can help to keep things tidy in the backend part of a product node.
> 1 votes

# Answer
I also tend to prefer using less content types, assumed products have not a dramatically distinct set of fields.

I agree that the module @cptstarling suggested should be useful, but at the same time seems it may be a bit heavy for your need.
So in the other hand you could also look at Conditional field module, which is quite simpler.
> 0 votes

---
Tags: entities, nodes
---


# Question
Title: Body classes still showing 'page-node-#' instead of title or menu word
I'm trying to get either the title of a page or the menu entry to be listed as a class in the body tag. I came across a posting here utilizing this code:

```
function THEMENAME_preprocess_html(&$vars) {
  $path = drupal_get_path_alias();
  $aliases = explode('/', $path);

  foreach($aliases as $alias) {
    $vars['classes_array'][] = drupal_clean_css_identifier($alias);
  }
}

```

flushed all caches but my body tag still looks like:

```
<body class="html not-front not-logged-in no-sidebars page-node page-node- page-node-47 node-type-page section-content">

```

So instead of that page-node-47, I'd like to see 'about-us' or whatever the path or title of the page is. I guess the path would be a better option for a class name but I'm not picky on that matter right now.

I do have Pathauto and clean urls installed and working. And in my html.tpl, I do have this:

```
<body class="<?php print $classes; ?>" <?php print $attributes;?>>

```

# Answer
I noticed that your function is named THEMENAME\_preprocess\_html(). If you don't have THEMENAME replaced with the name of your theme, the function won't be called and your classes won't get added.
> 0 votes

# Answer
@Richard yes, I have my theme name, neptune instead of "THEMENAME" and so, no @Clive I'm not using Omega but a child theme of Neptune.

so to check the $path and $aliases, do I just print those vars in the template.php (and then remove) as the correct way to get the values?
> 0 votes

---
Tags: theming
---


# Question
Title: Can the Feeds module work with get parameters?
Is there a way that I can use the Feeds module in Drupal 7 to connect to an API which requires specific get parameters to interact with?

The reply that the API gives will be in a simple XML format. The valuable information will be included in Content. This data will be in JSON format. I want to use this data to be put in a form which users can edit and submit back to the (API) server.

Is this possible? If not, what other solution can you recommend me?

# Answer
By default, the Feeds importer is set to file upload, but you can set it up to fetch data using an HTTP request.

1. On the settings page for your importer, click the **Change** link next to **Fetcher** in the left menu.
2. Select the radio button for **HTTP Fetcher** and hit the **Save button**
3. Visit /import and click on the link for your importer.

There will be a field there where you can enter the URL you want it to retrieve data from.
> 0 votes

---
Tags: feeds
---


# Question
Title: URL path settings not supporting more than one level
I'm trying to edit and create content on my inherited Drupal site and when I enter an address into the "URL Path Settings' URL Alias" field, it will not save the first part of the desired URL. For example if I enter "firstpart/contentname" it just saves "contentname" instead of the full hierarchy.

# Answer
That's strange. If you edit the URL alias manually, it shouldn't be automatically changed unless you bulk delete and update your URL aliases in Pathauto.

Have you checked your Pathauto pattern settings (/admin/config/search/path/patterns) to see if there is something overriding your changes?

You said that you inherited the site. Are there any URL/path-related modules that your predecessor has enabled?
> 0 votes

---
Tags: 7, path-aliases
---


# Question
Title: How can I keep a record of user email addresses when users update their email address?
I have a site where a minority of users are causing trouble by registering with one email address and then changing to another email address. Email Change Confirmation helps with this, but I would also like to keep a record of changed email addresses per-user, preferably in the Drupal UI.

I am thinking about making an email address field and using rules to automatically add an old email address when the user changes his or her email, but if there is a more robust solution I would love to know about it.

# Answer
> 1 votes
The first thing that came to mind is Drupal's revision feature. Out of the box, Drupal let's you keep records of what changes are made to nodes over time. Users are a different entity, but the User Revision module aims to provide the same functionality. This Lullabot article explains it pretty well. You could give it a shot.

---
Tags: users, emails
---


# Question
Title: Drupal changes language after clicking html link
Based on the internationalisation module i have my site set up in two languages.

My problem is when ever i click a link which i created with html. e.g.

```
<a  href="mypage"  >link</a>

```

As soon as i arrive on my page after clicking the link, the language will change.

I have tried:

```
<a  href="en/mypage"  >link</a>

```

However then drupal changes the link to:

```
<a  href="en/en/mypage"  >link</a>

```

resulting in a page not found.

What should i add to my html link to stay in the selected language?

# Answer
> 0 votes
I unchecked all the options on admin/config/regional/language/configure except the url option. Now my links `<a href="en/mypage" >link</a>` seems to work. Credits to drupalist: thanks

---
Tags: i18n-l10n
---


# Question
Title: How do I create inline border style in views table for views data export word output?
I am using views data export module to generate word output. I am able to get word document but views table out is coming without border. How to put border in word output ?

# Answer
I have created views template and saved in theme folder. then used styles in template itself like below:

```
      <th style="border:1px solid #000000; border-collapse:collapse; padding:5px; min-width:80px" <?php if ($header_classes[$field]) { print 'class="'. $header_classes[$field] . '" '; } ?>>
        <?php print $label; ?>

```

Useful link: http://www.wdtutorials.com/drupal-7/drupal-7-how-to-create-custom-template-view#.VWsGAlJp0-Y
> 1 votes

---
Tags: views
---


title: Set select list default value

text:
# Question
Title: Set select list default value
I have select list with options:

```
$options = array(0 => '0', 500 => '500', 1000 => '1000');

```

I'm trying to set it's default value to 500:

```
$form['price']['min']['#options'] = $options;
$form['price']['min']['#default_value'] = 500;

```

But this don't work.

# Answer
I've never seen this problem. That default value should work. I would say try making the key a string and set `#default_value` as a string. The `#options` array may be being passed through `array_merge` somewhere, thus rekeying integer keys. If keys are strings then that shouldn't happen. Currently, your array looks like this:

```
$options = array(
  0 => '0',
  500 => '500',
  1000 => '1000',
);

```

But passing that array through `array_merge` can reorganize those integer keys to be in sequential order:

```
$options = array(
  0 => '0',
  1 => '500',
  2 => '1000',
);

```

If that happens then the `500` key simply doesn't exist. This is because `array_merge` does not like to preserve integer keys, but you can use strings to prevent it. So, I think your array should look more like this:

```
$options = array(
  '0' => '0',
  '500' => '500',
  '1000' => '1000',
);

```

Then you can set your `#default_value`:

```
$form['price']['min']['#default_value'] = '500';

```

Otherwise, is there anywhere else where the `default_value` may be being overridden?
> 5 votes

# Answer
Your code should be work, generally use key value as default value, if it not working make the string as keys and use it as default value.
> 4 votes

# Answer
Did you try using a string instead of an integer?

```
$form['price']['min']['#default_value'] = "500"

```

Maybe also worth a try adding the `'und'` key.
> 2 votes

# Answer
Did you try using the key out of the array $options to define the default value?
`$form['price']['min']['#default_value'] = $options[500];`
> 1 votes

# Answer
```
$options = array(0 => '0', 500 => '500', 1000 => '1000');
$form['price'] = array(
          '#type' => 'select',
          '#options' => $options,
          '#default_value' => 500,
        );

```

In order to set default value in select list we use #default\_value parameter. The value of the default\_value attribute of the select list would be the key of the select list array.
> 1 votes

# Answer
Following code will show the field with its default value as 500.

```
$options = array(0 => '0', 500 => '500', 1000 => '1000');
$form['price'] = array(
          '#type' => 'select',
          '#options' => $options,
          '#default_value' => 500,
          '#title' => 'Price',
        );

```
> 0 votes

# Answer
I faced the same problem and I tried giving the index of the array which I want to be the default value and it worked. My answer is similar to Ashok KS but his second line I could not understand.
> -1 votes

# Answer
fixed,we should set default value first of that $option array, if we added last,the array key changed \[1\]=\>science,\[2\]=\>drama,the right should be \[192\]=\>science,\[231\]=\>drama:-)
> -1 votes

# Answer
try:

$form\['price'\]\['#default\_value'\] = 500;

It's work good for me.
> -1 votes

# Answer
The `#default_value` should have it's arguments in the form as the `#value`.

```
$form['price']['min']['#default_value'] = $options['500'];

```
> -2 votes

# Answer
Just use

```
$form['price']['min']['#default_value'] = 2

```

which means the default value will take the 2eme option
> -4 votes

# Answer
SOLUTION: Figure out that form\_select\_options doesn't handle `#default_value` at all. So I used `#value property`:

```
$form['price']['min']['#value'] = isset($_REQUEST['price']['min']) ? $_REQUEST['price']['min'] : $my_default_value;

```
> -5 votes

---
Tags: forms
---


title: Define constants in hook_init

text:
# Question
Title: Define constants in hook_init
I am writing a custom module for stripe payments and I need to declare constants for CLIENT\_ID and CLIENTSECRETKEY.

is it good to declare them in hook\_init because then they will available every where ?

module contains other functions like make\_payment and add customer etc.

# Answer
> 6 votes
`hook_init()` is not invoked for cached pages, so you could be opening yourself up to a world of pain if you do that.

Constants outside of a class that need to be accessed by several functions are global by nature, so just put them in the global namespace. It's the best way to ensure they're consistently available when you expect them to be.

# Answer
> 3 votes
If you define the variables in hook\_init, then it would work for non cached pages. But in case of Cached pages it would not work.

So it is recommended to use hook\_boot instead of hook\_init.

hook\_boot would be provide you variables for cached pages as well.

---
Tags: 7
---


# Question
Title: Exporting Custom Display Suite View Modes With Configuration
I'm using display suite with custom display settings for several view modes. I am also using the configuration management module for D7.

When I go to import my config on the staging server, the content types and settings and even the 'ds' field format settings come through, but it does not remember what view modes I've checked to have custom display settings. If I manually go back in and recheck the view modes, everything displays fine again.

Any idea where to track those changes?

# Answer
> 1 votes
Found the answer. It is under the strongarm variables. The setting you have to click is field\_bundle\_settings for that particular content type. You must have the strongarm module enabled for this to work.

---
Tags: display-suite, configuration
---


title: Why do I get duplicated files?

text:
# Question
Title: Why do I get duplicated files?
I am creating a Drupal site using Acquia Dev Desktop. I have noticed that there seems to be duplicate files located at C:\Users\Sam\Sites\devdesktop\columbiablooms-dev\docroot\sites\all and C:\Users\Sam\Sites\devdesktop\openoutreach-7.x-1.19\sites.

*Columbiablooms* is the name of the site I'm building. Using Acquia Dev Desktop I pushed the site up to Acquia. What is the relationship between the two file paths?

Does the C:\Users\Sam\Sites\devdesktop\columbiablooms-dev folder have anything to do with multisite or is it necessary for Acquia Dev Desktop?

# Answer
**C:\Users\Sam\Sites\devdesktop\columbiablooms-dev** contains data for your Acquia site (e.g. **hooks** has scripts that can trigger upon deployment, **private** contains files that setup as private in Drupal's file system, etc.)

The **C:\Users\Sam\Sites\devdesktop\columbiablooms-dev\docroot** dir is the webroot of your site; this is the dir that is the base of your domain that is uploaded to Acquia (e.g. C:\Users\Sam\Sites\devdesktop\columbiablooms-dev\docroot\index.php -\> http://www.example.com/index.php). See this post for an explanation of all the subdirectories.

**C:\Users\Sam\Sites\devdesktop\openoutreach-7.x-1.19** is a copy of OpenOutreach 1.19 you downloaded. It contains the OpenOutreach installation profile, its needed modules/themes, and the version of Drupal it's bundled with.
> 2 votes

---
Tags: acquia-dev-desktop
---


# Question
Title: Change product price before putting it on a cart
**Overview:**

I have a website that only sells **one** product. It has a $0.00 Price.

I have this custom form when sent, it will give the product id (e.g.) to the uc\_cart\_add\_item

```
uc_cart_add_item($nid, $qty = 1, $data = NULL, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE);

```

Well, technically it goes to the cart with a price of $0.00.

So the question here is, how can I alter the product price before sending it to the cart?

I saw this function from other website that this one alters the product price

```
hook_uc_product_alter(&$node)

```

Unfortunately, it doesn't seem to work or something.

I've searched for some questions

Ubercart alter product price when product added to cart

Even this one, but it's on Drupal Commerce not on Ubercart

programmically change price of product

Any help would be appreciated.

# Answer
You want to alter the *cart item*, not the product node. `hook_uc_cart_alter` is what you're looking for.

```
function MYMODULE_uc_cart_alter(&$items) {
  foreach($items as $key => $item) { //Set all items to $3.50
    $item->price = 3.50;
  }
}

```
> 1 votes

---
Tags: ubercart
---


# Question
Title: How to know from variables tu use them in a custom code
I know it's a newbie question, but it's take me a lot of time to find a a small code for a small fonctionality.

for example I wanted to make the address phone field required, I didn't know how to know the arrays keys.

```
        <?php
/**
 * Implements hook_field_widget_form_alter().
 */
function organize_address_field_widget_form_alter(&$element, $form_state, $context) {
  if(!empty($element['#addressfield'])) {
    $element['country']['#weight'] = 100;
    $element['phone_block']['phone_number']['phone_number']['#required'] = TRUE;

  }
}

```

I tried devel to find it but without result.

So my question,after finding the good hook, how I can know the variables to use.

Is a general question to help me to learn module development.

# Answer
> 1 votes
May be I'm missing something: I don't understand why you want to **programatically** make the field required.

`Required` is not a feature of a field **by itself**, it is an option you can set on its **instance** once it's attached to a node, through the `admin/structure/types/manage/yourContentType/fields/yourFieldName`.

---
Tags: hooks
---


# Question
Title: Cloning Node with Webform and Conditional Confirmation Message
I currently have an "Event" content type with a webform attached to each event. The webforms use the conditional confirmation message module to display different confirmation messages depending on the input to the form. I'm using the node clone module to duplicate events and everything works well expect that the conditional confirmation messages are not being duplicated. What should I do so that every part of the event node (including the conditional confirmation messages) is duplicated?

# Answer
The node clone module gives you the tools to make this happen. You can have a custom module make use of `hook_node_clone_alter` then use the Webform Conditional Confirmation module's functions to load & copy the original messages, store them temporarily, then save them upon saving the newly cloned node.

Something like this...

```
function MYMODULE_clone_node_alter(&$node, $context) {
  $messages = webform_conditional_confirmation_message_load($node->clone_from_original_nid);
  foreach($messages as $msg_id => $message) {
    //@TODO: Store in some temporary spot until cloned node is saved
  }
}

function MYMODULE_node_update($node) {
  //@TODO: Retrieve messages from temp location and place into $messages
  foreach($messages as $msg_id => $message) {
    $message->nid = $node->nid;
    webform_conditional_confirmation_message_save($message);
  }
}

```
> 0 votes

---
Tags: nodes, webforms
---