# Question
Title: Scheduler module not working even after cron run
Installed 'Scheduler module' and try to publish a content on specific time. But it seems like it is not working.

I tried with 'Run cron manually' also, But it doesn't ,While trying with Scheduler light weight cron it is working.

Why is it not working?

# Answer
> 0 votes
Step: 1. First of all u have to uncheck the published node content types..

Then u have to set the schedular time for particular node

Then U can use Rules module to publish.

---
Tags: 7, cron
---


title: Limit filter operators

text:
# Question
Title: Limit filter operators
Is there a way to limit the operators for views-filtering for users. I want them to only have "starts-with", "contains" and "same". But not the rest. Do I have to form\_alter with a custom module? Or is there some intern way to achieve that?

# Answer
I don't think there is an option to sort the exposed operators.

You can do it with a custom module using hook\_form\_alter().

Example:

```
function module_name_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'view_name') {
    unset($form['field_name_filter_op']['#options']['empty']);
    unset($form['field_name_filter_op']['#options']['not empty']);
  }

}

```

You can find the form details using "dpm()" from devel module.

* dpm($form\_id);
* dpm($form);
* dpm($form\_state);
> 1 votes

---
Tags: 7, views
---


title: Drupal function to delete folder

text:
# Question
Title: Drupal function to delete folder
How I created the folder i want to delete:

```
$form['logo'] = array(
'#title' => t('Upload logo'),
'#type' => 'managed_file',
'#description' => t('Allowed extensions: .gif .png .jpg'),
'#upload_location' => 'public://myfolder/',
'#upload_validators' => array(
  'file_validate_extensions' => array('gif png jpg jpeg'),
  'file_validate_image_resolution' => array('500x250'),
),);

```

Now how to delete it? I have tried this

`file_unmanaged_delete_recursive('public://myfolder/');`

and

```
drupal_rmdir('public://myfolder/');

```

There are files in the folder I'm trying to delete.

# Answer
`file_unmanaged` functions are allowed to fail on managed items, so when you create folder using `'#type' => 'managed_file'`, they are not the way to go.

`drupal_rmdir` is only a wrapper around PHP `rmdir`, and it requires folder to be empty.

It means both solutions you have tried was not able to work.

---

Correct way is to use EntityFieldQuery to load all files in the folder you want to purge, then use `file_delete` on them, with `$force` set to `TRUE` to remove files that are in use (think twice if that's really what you want to do!). Only when the folder is empty, call `drupal_rmdir` on it.
> 2 votes

---
Tags: files
---


# Question
Title: In subtheming Commerce Kickstart, how to load my own background image?
I followed the instructions in this drupal.org article to subtheme Commerce Kickstart theme, but one thing I didn't get. I have changed the background logo bg.png to my own. Create directory my\_theme/images, and put the new bg.png there. There is a line in MyTheme\_style.css, in section 1. Global:

```
body {
  background: #ececec url("../images/bg.png") left top; }

```

I've supposed then that the bg.png charged woul'd be my own, but it doesn't happen.

By the way, I first subthemed Commerce Kickstart theme with drush, and followed the other steps to make changes in MyTheme.info file.

I tried provide full path in url("../images.bg.png"), but still not working.

Am I missing something?

Edit: I will explain in details.

First I made a sub-theme of commerce kickstart with drush.

```
$ drush dl omega_tools
$ drush en omega_tools
$ drush omega-subtheme "The New Theme Name Here" --base=commerce_kickstart_theme --enable

```

To change some css attributes I create the file livraria-acervo-theme-alpha-default.css, where livraria-acervo-theme is my theme name. That file overrides the attributes changed from commerce-kickstart-alpha-default.css. Ok, works well.

But I need to change some global attributes that are in global.css. Then, from the drupal.org article cited, I follow some parts, as other was already done by drush. File livraria\_acervo\_theme.info was created by drush. But the code block

```
; OPTIONAL STYLESHEETS

css[livraria_acervo_style.css][name] = Livraria Acervo theme global style.
css[livraria_acervo_style.css][description] = This file holds all the globally active custom CSS of Livraria Acervo theme.
css[livraria_acervo_style.css][options][weight] = 12
settings[alpha_css][livraria_acervo_style.css] = 'livraria_acervo_style.css'

```

except the last line, was added in livraria\_acervo\_theme.info file

I think including this code block in livraria\_acervo\_theme.info file and create livraria\_acervo\_style.css and put it in path livrariaacervo/sites/all/themes/livraria\_acervo\_theme/ would cause my changed attributes in livraria\_acrevo\_style.css to take effect. But it doesn't.

I also created livrariaacervo/sites/all/themes/livraria\_acervo\_theme/images/ directory and put my background image bg.png there, and in

```
body {
  background: #ececec url("../images/bg.png") left top; }

```

I change "../images/bg.png" by "livrariaacervo/sites/all/themes/livraria\_acervo\_theme/images/bg.png", but didn't take effect.

The fact is that the livraria\_acervo\_style.css isn't used, as inspecting the chanted attribute in DOM, the file that is used is commerce\_kickstart\_style.css

It's my first time with sub-theme a Drupal theme, so I think is something I'm missing.

# Answer
> 1 votes
It's necessary to go in /admin/appearance/settings for your custom sub-theme and in vertical menu on the left, click "Toogle Styles", uncheck the box for "Commerce kickstart theme global style" and click "Save configuration". Now click again in "Toogle Styles" and there is a new option: "MY THEME NAME theme global style. (all) - MYTHEMENAME\_style.css".

Check this option and again click in "Save configuration". Now changes in attributes in mysite/sites/all/themes/MYTHEMENAME/css/MYTHEMENAME\_style.css does work.

# Answer
> 0 votes
First provide the absolute path like abc.com/sites/all.. to your image and see if it loads or not if it loads then there is something missing your relative path then check your relative path..

---
Tags: theming, commerce
---


# Question
Title: Has anyone worked on a built-in CLI terminal [w/ drush]?
What would make my experience with clients/end-users easier is if there was a self-contained GUI-like terminal that would be exclusive to their drupal 7 subsite in a multi-site configuration. This would allow them to be full-stack developers without the headache of managing \*nix users?

The only reference I could find was for Drupal 6 - https://drupal.org/project/terminal.

In the meantime, the way I can think of manually achieving some of this is to write custom forms on a user dash (page--front.tpl.php) that would trigger drush calls on the server side for particular (custom) tasks. Maybe add some ajaxy for wiz-bang.

Now granted, a lot of the customs tasks I can think of atm can be achieved via drupal modules - such as editing css, limiting access to module uploads, and even exposing features. It's just turning each one of those on/off for over 100+ sites is cumbersome, and so it'd be nice to leave it up to the end-user to manage their own site.

Without paying Pantheon to do the same thing.

# Answer
> 0 votes
The upcoming Drush 7 now has `drush core-cli` which used the Boris shell

---
Tags: drush, modal-dialogs, dashboard
---


# Question
Title: When I edit a display within a view, it changes other displays too
I have a question about the way displays in views work:

I have a view that has 8 different displays. Each display shows content of the same content type, but with different taxonomy terms associated with each (so one display would be something like Research Topic 1, another would be Research Topic 2, and so on).

The issue is that with two of the displays, when I edit one, the other automatically takes the same changes. All other ones work fine, except two. What I'm editing is the type of research (which as I said I'm using taxonomy terms to decide what is what). When I select one research type on display X, it changes the research type in display Y to be the same.

I'm not the one who originally set up this view, so I'm not really sure what was differently, if anything, to the others to make them work fine. Any help is appreciated!

**Edit:** One additional thing I just noticed is that "FILTER CRITERIA" for the two displays that seem to be connected is not italicized, but that heading in Views for all of the other displays within this block are italicized. No idea what this means, but just adding this info in case it's helpful.

# Answer
Never mind! I figured it out... Each display was still overriding the others, but I found where to change that and everything is good!

For anyone else with the same question: When you click on a filter criteria, you can select options in the drop down at the top of this overlay which specifies whether you would like to apply the changes to all displays or just this page.
> 1 votes

---
Tags: views, nodes
---


# Question
Title: How can I hide the label saying "URL*" from content creation form when using the link module?
I'm using the link module to ask the user for a link. I have disabled the link text (I.E\> the text that would be inside the anchor tag) so the user wouldn't be asked for a title. What I would expect to happen is that I wouldn't see the field label, followed by the label "URL\*". However, it isn't so.

As an example, my field label is `Download link`. What I see in the node creation form is a label like `Download link*` and then another label with the text `URL*`. Is there a way to hide the latter (the one saying `URL*`)?

# Answer
You can use hook\_form\_alter() to change the title of that field to an empty string.

Let me know if you need help along the way.

Good luck!
> 0 votes

# Answer
Look at the `Manage Display` tab of your content type. On that page you can set how the label is displayed:

* Above
* Inline
* Hidden

and how your link displays:

* Title, as link (default)
* Title, as plain text
* URL, as link
* URL, as plain text
* URL, absolute
* Domain, as link
* Short, as link with title "Link"
* Label, as link with label as title
* Separate title and URL
* Hidden
> 0 votes

---
Tags: entities
---


# Question
Title: Creating a view with a dynamic link from taxonomy term
Trying to create a view block with a list of five links

* Event Details (dynamic)
* Cause (dyanmic)
* Sponsors (statis)
* Volunteer (static)
* Register (static)

Dynamic url will look like this:

/events/golf-tournament/\[year\]/\[taxonomy-term\]/event-details

/events/golf-tournament/\[year\]/\[taxonomy-term\]/cause

I am not able to format the taxonomy term to use it in the url

Taxonomy term prints as: The William Dennis Memorial Golf Tournament (with capitals and spaces)

View looks like this:

\** Solution \** * Not sure if this is the 'right' way *

Added contextual filter for: Content: has taxonomy term ID

But it doesn't appear to use the taxonomy term....so really I providing a value from the url

Then I messed around with tokens, first trying \[token\_taxonomy\_term\] \<--- not actual token; %1 and !1 \<---- all of these exist in the available Replacement Patterns

Here is the rewrite I used to rewrite the url for 'cause'

Cause

# Answer
In the contextual filters you may have to add the Context: Has taxonomy term ID filter. You can set the Specify validation criteria settings. The validator option is usually Taxonomy Term, but other validator options are available. Make sure to choose Term Name converted to Term ID, as this is what is needed to be passed for to the url. Also check the Transform dashes in URL to spaces in term name filter values checkbox underneath. Choose your action to take if the filter value does not validate dropdown.
> 0 votes

---
Tags: views, blocks, navigation
---


# Question
Title: How to delete a cck field base in Drupal 6
I have programatically created some cck fields with this function:

```
content_field_instance_create($field)

```

and I tried to delete them with this:

```
content_field_instance_delete($field_name, 'product', FALSE)

```

However, this didn't actually delete the cck field from the Product types database table. The fields didn't show up on the UI edit page but they still exist in the database, which is causing me some issues. How can I systematically make sure the database entry is wipes as well?

# Answer
I believe deleting the fields programmatically like this flags the fields as deleted by CCK or the Field API in Drupal 6/7. You must then run `Cron` to have the system fully purge the database tables from the system.
> 0 votes

---
Tags: 6, entities
---


# Question
Title: Metatags not showing despite calling render in template
My custom page.tpl.php is not outputting metatags. I've tried all of these:

```
 render($page['content'])
 print render($page['content'])
 render($page['content']['metatags'])
 print render($page['content']['metatags'])

```

I know that the metatags module is passing in the metatag info, because doing this

```
watchdog('foo', print_r($page['content']['metatags'], true));

```

results in an array like this:

```
 Array (
  [node:feed] => Array (
    [abstract] => Array (
      [#attached] => Array (
        [drupal_add_html_head] => Array (
          [0] => Array (
            [0] => Array (
             [#theme] => metatag
             [#tag] => meta
             [#id] => metatag_abstract
             [#name] => abstract
             [#value] => This is an abstract
            )
            [1] => metatag_abstract
          )
        )
      )
    )
    [keywords] => Array (
    [#attached] => Array (
    [drupal_add_html_head] => Array (
    [0] => Array (
      [0] => Array (
        [#theme] => metatag
        [#tag] => meta
        [#id] => metatag_keywords
        [#name] => keywords
        [#value] => keyword1 keyword2
      )
      [1] => metatag_keywords
    )
  )
 )

 ... etc ...

```

What might be stopping it from rendering the metatags on the page?

I've also noticed that the metatags element in the default devel tab is an empty array, BUT in the tokens tab within devel, the node:metatag tokens are all present and correct.

Further investigation shows that drupal\_add\_html\_head() is being called and the metatag information is being passed in.

# Answer
> 3 votes
Turned out someone had overridden `html.tpl.php` and had removed the reference to `$head`. Adding `echo $head` between `<head>` and `</head>` in `html.tpl.php` fixed the problem.

---
Tags: 7, theming, meta-tags
---


# Question
Title: Need help defining IE specific stylesheet with Zen Starter-kit and Conditional Stylesheet Module
I need help defining a conditional IE stylesheet in my .info file.

I am using the Zen starterkit as my base theme, and I have the conditional stylesheet module installed and enabled. I have added an ie.css file added to my css directory along with my other stylesheets. In that ie.css file, I have changed the background to an obnoxious color to confirm when the stylesheet is being used appropriately.

However, I have been struggling with what I need to put in my .info file. I have researched as much as I could and read the help.txt file multiple times. I just want this stylesheet to target IE. I do not want to create one for each version. This site will not support ie6 and ie7 anyways.

Here is what I currently have defined in my .info file for it:

```
stylesheets-conditional[if IE][all][] = css/ie.css

```

I have also tried this that just results with that stylesheet loading for all browsers:

```
stylesheets-conditional[!IE][all][] = css/ie.css

```

So far with all of my attempts, I can either get it to act as a normal stylesheet, having it override my other styles, or not having it load at all. Is there something I need to add in my page templates that I am overlooking?

I have this in the head of my html.tpl.php as well (I have my actual theme name in there):

```
<!--[if IE]><link rel="stylesheet" type="text/css" href="sites/all/themes/THEMENAME/css/ie.css" /><![endif]-->

```

Other resources that I have used:

1) Conditional Stylesheets Set-up: Using the Module

2) Add conditional stylesheet CSS for internet explorer only (not trying to use this method)

# Answer
If this link is in your head it is like if the css file is in a folder under the currrent one. You need a first backslash: `<!--[if IE]><link rel="stylesheet" type="text/css" href="/sites/all/themes/THEMENAME/css/ie.css" /><![endif]-->`

As you can see in the answer you linked the definition in .info file has to look like

```
stylesheets-conditional[IE][all][] = css/ie.css

```

not

```
stylesheets-conditional[if IE][all][] = css/ie.css

```

(I just have it from this answer - never used this module). Honestly I would not install a module just to add conditional comments for IE. It is easier and saves performance eating module to put them simply into the html.tpl.php - you just have to keep the right paths.

```
stylesheets-conditional[!IE][all][] = css/ie.css

```

Makes absolutely no sence - I do not know if this module could interprete that. But at least no browser in the world would read a css file in such a conditional comment: every browser except IE ignores conditional comments. So you tell the only browser who reads them that this file is notfor it to use... you got it :)
> 0 votes

---
Tags: .info, theming
---


# Question
Title: How to change the style of the pages title in a view?
I've created a content type view using teasers. The titles are all H1s. How to change that to H3, for example?

Is this just a case of CCS?

# Answer
> 0 votes
Open firebug to see what are the ancestors of the `h1`, there should be a name that contains the content type or view, you can easily set:

```
.WRAPPER-OF-CONTENT-TYPE h1{
    //here is your css style
}

```

# Answer
> 0 votes
Enabling `Display Suite` and `Display Suite Extras` allows you the ability to control each field output's element, class, etc.

# Answer
> 0 votes
Simply go to views admin page, go to the field with the title to "Output settings" and choose another tag for the output

---
Tags: views, theming
---


# Question
Title: How to get the country from shipping address in a view?
I am using Drupal Commerce Kickstart! I want to get 'Only' the country name from the shipping information of a particular order in a view, The shipping information field in my view shows the entire shipping address including the country at last, is there a way that I can extract only the country name from that? or a db query using the order\_id?

# Answer
Implying that you have the **Order ID** in your view:

1. Add a relationship to **Commerce Order: Referenced customer profile**, for the shipping address (Relate this entity to the customer profile referenced by its commerce\_customer\_shipping value)
2. Add field for **Commerce Customer profile: Address - Country**

My output after those steps:

```
Order ID: 4
Bulgaria

Order ID: 5
United States

```

FYI the data is located in **field\_data\_commerce\_customer\_address** table **commerce\_customer\_address\_country** column.
> 2 votes

# Answer
Finally I did it by sending a DB query to get the address of a customer by an order id.

```
SELECT field_data_commerce_customer_address.commerce_customer_address_country as country
                FROM field_data_commerce_customer_address
                INNER JOIN field_data_commerce_customer_shipping
                ON field_data_commerce_customer_address.entity_id = field_data_commerce_customer_shipping.commerce_customer_shipping_profile_id
                WHERE field_data_commerce_customer_shipping.entity_id ='".$order_id."'"

```
> 0 votes

# Answer
You can isolate the country field by enabling aggregation. Add address to your result set and group the results by the country field.
> 0 votes

---
Tags: views, commerce
---


title: Track One Time Login

text:
# Question
Title: Track One Time Login
In my Drupal 7 site, when a user registers they are emailed a one time login link that they can use to set their password using this token: \[user:one-time-login-url\]. Is there any hook that I can use to update a field in my database so that I can differentiate users who have activated their accounts, versus those who have not clicked on the link?

# Answer
> 1 votes
I never found a solution for that. I did it always the following way:

* Install the rules module (if you did not work with Drupal's hooks yet - otherwise you could use these hooks for that)
* Then give an user a role like "unconfirmed" as soon as a new user account is created by one rule
* Then define another rule: triggering event is "user logged in", check, if the user has the role "unconfirmed" and if so -\> action "Take role away" (do not know now what the action is called in English).

---
Tags: users, emails
---


# Question
Title: Using EntityFieldQuery with Address Field
I have a custom content type with a **postal\_address** field provided by the module addressfield. postal\_address fields are one field in the custom content type. This one field is comprised of many subfields like: country, name\_line, and postal\_code.

How can the core function **EntityFieldQuery** be used to retrieve nodes of my custom content type based on their postal code value (a subfield of the postal\_address field)?

Specifically, I do not know what to put in the code below instead of the text: **what\_goes\_here**:

```
$query  =  new EntityFieldQuery();

$entities  =  $query->entityCondition( 'entity_type', 'node' )
  ->propertyCondition( 'status', 1)
  ->propertyCondition( 'type', 'consumer_store' )
  ->fieldCondition( 'what_goes_here', 'value', $postal_codes )
  ->execute();

```

# Answer
Although Addressfield can be extended, the standard columns like zip code are normal field columns and live in field storage (see `addressfield_field_schema()`).

In your case you want the `postal_code` column:

```
$query  =  new EntityFieldQuery();

$entities  =  $query->entityCondition( 'entity_type', 'node' )
  ->propertyCondition( 'status', 1)
  ->propertyCondition( 'type', 'consumer_store' )
  ->fieldCondition( 'field_postal_address', 'postal_code', $postal_codes )
  ->execute();

```
> 5 votes

---
Tags: 7, database, entities
---


# Question
Title: Add a popup text link to a specific "create content" page
I've looked everywhere and can't find an answer to my problem. I'm trying to do something that seems like it would be relatively simple, but I keep coming up empty: add a pop-up text link to the "node/add/content" form for just one of my content types.

I've figured out how to use the popup module (https://www.drupal.org/project/popup) to make pop-up text elements using blocks, but that won't help me when it comes to the add content page. The idea here is to give users instructions on how to fill out the "add content" form on the form itself. Since I'm using an overlay screen, it makes the most sense to include the link directly on the form itself.

I've seen many places where people suggest a variation on this: Base tpl file for "add content" page?. In other words, copying the node file contents to a new file called `page--node--add--my-content-type.tpl.php` in the base theme directory, but this has no effect for me.

Also, I've tried to use the Theme Developer module to figure out what the page is called, but enabling this module just breaks the form for me, rendering Devel useless.

Do I need to somehow manipulate the template.php file in my theme? Any direction anyone can give me would be great. Thank you in advance.

# Answer
> 2 votes
Have you considered `hook_form_alter` and the usage of either of these 2 modules:

BeautyTips, which allows:

> The Beautytips module provides ballon-help style tooltips for any page element by integrating the BeautyTips jQuery Tooltip plugin by Jeff Robbins with Drupal. It provides an API for adding custom beautytips as well as some built-in features. Admins can enable rollover balloon-help style tooltips for text fields within forms. It also supplies hover tips for Drupal help links and advanced help links.
>
> Most importantly, it allows developers to add their own custom beautytips popups to their site without having to delve into jQuery.

Guided Tours, which allows:

> Gives content creators the ability to build tours on their sites which allow users to better understand complex workflows on the site and be guided through those workflows. The main advantage of this module is that you can build tours leading the user through multiple different pages with multiple tooltips on one page/step. This module uses qTip and jgrowl\_d7.

**EDIT**

As an example for `/node/add/page` the recipe would be:

1. Implement `hook_form_alter` in a custom module for this pages `$form`.
2. For any form item of the form you want to add a beauty tip for add a class so you can find it easily using beauty tips.
3. For instance then at the end of your hook\_form\_alter function you then can add the beauty tips calls following the documentation. You can use your helper CSS classes to make your life somewhat easier.
4. repeat (1) thru (3) as necessary ...

```
# in file mymodule.module

// This is step #1.
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // This is step #1. Or target 'page_node_form', or use a Regex for certain forms.
  if ($form_id == 'student_blog_node_form') {
    // This is step #2. See https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attributes
    $form['field_survey_program']['#attributes']['class'][] = 'my-beauty-tip';
  }

  // This is step #3. See: http://cgit.drupalcode.org/beautytips/tree/README.txt?id=HEAD
  $options['bt_drupal_help_page'] = array(
      // what selects the content from the page using css selectors.
      'cssSelect' => '.my-beauty-tip',
      // what to show in the tooltip.
      'text' => 'This is my tooltip!',
      'trigger' => array(0 => 'mouseover', 1 => 'click'),
      'width' => 350,
    );
    beautytips_add_beautytips($options);
}

```

---
Tags: theming, nodes, navigation, debugging
---


# Question
Title: Why cannot I get any value from configuration objects?
I have made a simple example to practice using the configuration API in Drupal 8. I created the twitter\_pull.credentials.yml file in the config/install folder with the following content and flushed the cache.

```
oauth_access_token: "12345"
oauth_access_token_secret: "67890"
consumer_key: "54321"
consumer_secret: "09876"

```

In a custom block, I use the following code to retrieve the configuration object.

```
namespace Drupal\twitter_pull\Plugin\Block;
use Drupal\block\BlockBase;

/**
 * Provides a block for executing PHP code.
 *
 * @Block(
 *   id = "twitter_pull_tweets_block",
 *   admin_label = @Translation("Twitter Tweets")
 * )
 */
class TweetsBlock extends BlockBase {

  /**
   * Builds and returns the renderable array for this block plugin.
   *
   * @return array
   *   A renderable array representing the content of the block.
   *
   * @see \Drupal\block\BlockViewBuilder
   */
  public function build() {
    $config = \Drupal::config('twitter_pull.credentials');
    $enabled = \Drupal::config('system.maintenance')->get('enabled');
    dpm($enabled);
    dpm($config);
    drupal_set_message($enabled);
    return 'this is a block: ' . $config->get('consumer_key');
  }
}

```

I don't get any value from `\Drupal::config('system.maintenance')->get('enabled')` nor `$config->get('consumer_key')`.

What am I missing here?

# Answer
> 9 votes
To elaborate on @dawehner's answers, default configuration is not cached.

It is only imported when you install a module. After that, if you make changes to default configuration, the only way to add it to existing installations is to write an update function that adds it manually.

During development, there are modules like Configuration development, that can automate that process, but they will obviously not be present on any productive installations.

---
Tags: 8, configuration
---


title: Only user number 1 can add content

text:
# Question
Title: Only user number 1 can add content
Recently all users (except UID 1) lost the ability to add content.

When going to node/add we get the message "no content types created yet"

When going to node/add/page we get "Access Denied, you are not authorized to access this page"

There are people having similar issues like here - https://www.drupal.org/node/1073994

I have already checked the navigation menu to see if that was the issue, since it seems to be a known bug, but this was not the case. All the permissions are set correctly in the permissions UI and database too.

I am not sure if this is relevant, but the site was migrated from 6 to 7

Any insights would be appreciated!

# Answer
This is indeed most likely an access issue. However, I don't think it's something with Apache Solr but more with some of the additional modules you might have enabled. Can you list them with the versions here?

Also, as mentioned above, disable apachesolr access and rebuild your permissions. Check if it is still the case?
> 0 votes

# Answer
The problem was with the node limit module.

Our developer Weiling Gu noticed that the problem started after anonymous users were submitting content.

By process of elimination we discovered that node limit was causing the block.

We have not yet confirmed if a settings change in node limit would have resolved the issue, but at least turning it off solved our immediate problem.
> 0 votes

---
Tags: users, nodes
---


title: Click button to change CSS in D7

text:
# Question
Title: Click button to change CSS in D7
I'm trying to create a clickable link that changes the css using jquery. I've tried many approaches and nothing seems to work. Hopefully someone here can push me into the right direction.

Button html (in a block):

```
<a href="#" id="change_css">Change CSS</a>

```

Button code (in change\_css.js):

```
(function($) {
    Drupal.behaviors.my_node_toggle = {
        attach: function(context, settings) {
            $("#change_css", context).click(function(){
                $('a').css({"color":"#ff0"});
            });
        }
    };
})(jQuery);

```

The script is being loaded, but nothing happens when I click on the link.

# Answer
> 0 votes
Your problem resides in the way you are calling the css function in jQuery. Try this, it works for me:

```
(function($) {
  Drupal.behaviors.my_node_toggle = {
    attach: function(context, settings) {
      $("#change_css", context).click(function() {
        $('a').css("color","#ff0");
      });
    }
  };
})(jQuery);

```

---
Tags: javascript, theming
---


# Question
Title: update user data without a form from a module
in my drupal system i use the basic\_wemail module along with a custom module i created that creates a postfix mail alias for a new user, so we can provide users with free email addresses as part of the service.

The basic\_webmail module has a user form where a user can input their email address and logins for the module to save the email credentials as serialised user data. Since we dont want users to update this information and only to use the email credentials created by our custom postfix integration, but user\_update(), user\_insert() and user\_presave() all work on a form submit, is there another way to pragmatically update a users serialised data?

# Answer
> 0 votes
```
 $edit = array(
    'basic_webmail_username' => $full_username,
    'basic_webmail_password' => $password,
  );

user_save($user, $edit);

echo('lol that was easier than i thought');

```

user\_save();

# Answer
> 0 votes
You may also use this short snippet to update an existing user

```
// load user object
$existingUser = user_load('USERID');
// update some user property
$existingUser->some_property = 'blah';
// save existing user
user_save((object) array('uid' => $existingUser->uid), (array) $existingUser);

```

Hope it works for you!

---
Tags: webforms, users, emails
---


# Question
Title: Image gallery with original image proportions
I was looking for a module a tutorial how to create an image gallery in drupal 7 where when you go in album all images are not cropped in rectangulars and displayed in a table, but remain with their natural proportions and displayed in columns as I provided a print screen below(tumblr theme), each image has a unique page with it's caption. I am not sure what is the particular term for such way of displaying images is called so I am asking here

# Answer
> 0 votes
You most probably want the functionality provided by Masonry API and its sub-modules: Masonry Views and Masonry Fields.

> Masonry is a dynamic grid layout plugin for jQuery. Think of it as the flip-side of CSS floats. Whereas floating arranges elements horizontally then vertically, Masonry arranges elements vertically, positioning each element in the next open spot in the grid. The result minimizes vertical gaps between elements of varying height, just like a mason fitting stones in a wall.

In the view you will specify a image formatter that only sizes on the width so that the height remains proportional.

---
Tags: media
---


# Question
Title: How can I restart the PHP environment installed with Drush for Windows?
I have installed Drush for Windows, works great, but it installs its own version of PHP in a subdir of the install directory. I've increased the memory limit and execution times in that ini but how can I restart that PHP environment (if in fact that is even the correct PHP environment). Short of restarting my machine (which is fine) just wondering what would be the way to do this?

# Answer
> 1 votes
Drush works using CLI. It means it is not dependent on web server you are using. "Restarting environment" simply does not apply, Command Line Interface PHP is started each time you call drush, and stops when drush finishes it's job, that's all.

---
Tags: drush
---


# Question
Title: Drush, post receive hooks and git branches/tags
I am stuck with a nagging issue in our deployment systems

* drush version 5.7
* git version 1.7.7
* Drupal 7.x

We currently have a bare git repository (consisting of drush makefiles) on the production server that fires off a post-receive hook to recursively build our Drupal multisite structure with drush make when it receives new data via a push from our local machines.

Everything works very swimmingly until a project in the makefiles contains either a git **tag** or **branch** in the definition. Then, the post-receive hook triggered build fails with :

> > git://github.com/\[account\]/\[repo\].git. DOWNLOAD\_ERROR: Unable to check out tag 7.x-1.01. -- build forced \[warning\]

Even more interesting : if I run the build on the production server locally or via a remote SSH command, the build succeeds. The problem only arises if it is run from a post-receive hook from a remote git push.

Verbose output offers no more information.

I can only assume that the post-receive hook system in git does not store/carry over an environment variable that is required for a drush to perform a two-step git operation on the single project. Is this a known issue?

I recognize this hurdle can be avoided by defining the project in the makefile as a 'get' download and providing the github download URL (instead of using the git functionality). Being pedantic, however, I'd like to narrow down where the problem is, and report it as a bug if appropriate.

I can repeat this on a fresh install.

But has anyone run into this? Solutions would be welcomed with elation.

# Answer
> 1 votes
Your tag `7.x-1.01` could be the problem ... In most Drupal projects the tag would be `7.x-1.1` (Without the zero)

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


# Question
Title: Drupal_add_js is not working inside hook submit
I have alter and hook submit for webform. I would like to pop a modal if form is successfully submitted. But drupal\_add\_js seemed to be not working inside the hook submit.

```
function myModule_form_alter(&$form, &$form_state, $form_id) {

    if($form_id == 'webform_client_form_9') {
        $form['#submit'][] = 'myForm_submit';
    }

}

function myForm_submit($form, &$form_state) {
    drupal_add_js(drupal_get_path('module', 'myModule') . '/misc/custom.js');
}

```

# Answer
> 1 votes
You should do this with #attached.

Like,

```
if (!empty($form_state['values'])) {
  $form['#attached']['css'] = array(
    drupal_get_path('module', 'ajax_example') . '/ajax_example.css',
  );
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
  );
}

```

# Answer
> 0 votes
Aneek Mukhopadhyay is on the right track but if you need it only for submit you should add the code inside an IF statement:

```
if( isset($form_state["values"]) ) {
  $form['#attached']['css'] = array(
    drupal_get_path('module', 'ajax_example') . '/ajax_example.css',
  );
  $form['#attached']['js'] = array(
    drupal_get_path('module', 'ajax_example') . '/ajax_example.js',
  );
}

```

Hope it helps.

# Answer
> -1 votes
I think so a javascript file is added when a page loads.In this case page loads after hook\_submit gets called.Why dont you try to add the js the time a page loads in hook\_init and try.

Thanks, Keep calm and clear the cache.

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


title: Drush within Multisites

text:
# Question
Title: Drush within Multisites
I am using drush on ubuntu 14.04. I have more than 20 site on my localhost /var/www with virtualHost setting. I have a question that whenever i go to /var/www/site1 and run drush dl module\_name. It download the module in sites/all/modules directory in site1 folder. Now i cd to /var/www/site2 and run drush dl module\_name. It will again download the module in site2 module directory.

In every site i have to do drush dl for same module. Is there any method so that i don't need to do drush dl every time. I just do drush dl module, it will check from all other sites for particular module, if not found then will download from internet. I already doing cp and scp for same module. But i want to do with drush. I am very greedy to save my internet bandwidth.

Thanks in Advance.

# Answer
> 1 votes
you can use:

```
drush dl modulename --cache

```

From `drush help dl`:

```
Download Drupal core or projects from drupal.org (Drupal core, modules, themes or profiles) and other sources. It will automatically figure out which project version you want based on its recommended release,
or you may specify a particular version.

...

Examples:

 drush dl webform --cache                  Download webform. Fetch and populate the download cache as needed.

Options:
 --cache                                   Cache release XML and tarballs or git clones. Git clones use git's --reference option.
   --cache-duration-releasexml             Expire duration (in seconds) for release XML. Defaults to 86400 (24 hours).
...

```

# Answer
> 0 votes
What you could do is a "common" directory with a link to the parent site.

So will be /var/ww/site1/sites/all/modules/common (the parent)

then: ln -sv /var/www/site1/sites/all/modules/common /var/www/site2/sites/all/modules/common

With this you only do one 'drush dl module\_name' for commons modules.

Other way to manage if you don't want to create links in folders you could use the drush aliases.

Create a file in you .drush directory ~/.drush/aliases.drushrc.php

Then you will be able to do this things

drush @dev1,@dev2 dl modulename drush @dev1,@dev2 cc all drush @dev1,@dev2 updb

Hope some of this tips help you.

---
Tags: drush
---


# Question
Title: Conflicting realm variables when using i18_variable
I'm using i18\_variable, and I'm using the hook\_variable\_info, hook\_variable\_group\_info....I enabled the custom variables I defined after that from the admin/config/regional/i18n/variable page.

But I'm getting this error on the variable configuration page in the module

There are conflicting realm variables in the form. The variable New Name is enabled for more than one realm. Review your realm settings

Any particular reason on what could be triggering it?

Here is the relevant code.

```
function embed_form_menu() {

    $items = array();
    $items['embed-form-configuration'] = array(
        'page callback' => 'drupal_get_form',
        'page arguments' => array('get_embed_form_configuration'),
        'access arguments' => array('Embed Form Configuration Permission'),
        'access callback' => TRUE
      );
    return $items;
}

function get_embed_form_configuration() {
  return drupal_get_form('variable_module_form', 'embed_form');
}

function embed_form_variable_info($options) {

  $variable['embed_form_newname'] = array(
    'title' => t('New Name', array(), $options),
    'description' => t('Enter your new name, please.', array(), $options),
    'type' => 'string',
    'default' => t('Drupal user', array(), $options),
    'group' => 'embed_form',
    'localize' => TRUE,

  );

  return $variable;
}

/**
 * Implements hook_variable_group_info().
 */
function embed_form_variable_group_info() {
  $groups['embed_form'] = array(
    'title' => t('Embed Form'),
    'description' => t('Embed Form Config'),
    'access' => 'Embed Form Configuration Permission',
    'path' => array('admin/config/system/embed-form'),
  );
  return $groups;
}

function get_embed_form_configuration() {
  return drupal_get_form('variable_module_form', 'embed_form');
}

```

# Answer
Found the fix thanks to some help from @piyuesh

```
  $items['embed-form-configuration'] = array(
    'page callback' => array('get_embed_form_configuration'),
    'access arguments' => array('Embed Form Configuration Permission'),
    'access callback' => TRUE
  );

```

It was silly in hindsight, as my page callback was a drupal get form, and in the callback function I was returning a drupal get form as well. THat is why multiple realms.
> 0 votes

---
Tags: 7, i18n-l10n
---


title: drush sql-sanitize: exclude user #1?

text:
# Question
Title: drush sql-sanitize: exclude user #1?
When I run `drush sql-sanitize`, is there a way to exclude user #1 (or specific other users, for that matter) so his email address and password are not changed?

# Answer
> 5 votes
There's no such option in drush, all users are sanitized.

As a workaround you can save the user 1 data (or any other user you want) with drush sqlq and restore after sanitization.

Using bash:

```
user_data=$(drush sqlq "SELECT pass, mail FROM users WHERE uid = 1"| tail -n1)
user_pass=$(echo $user_data | cut -f1 -d" ")
user_mail=$(echo $user_data | cut -f2 -d" ")

drush sql-sanitize ...

drush sqlq "UPDATE users SET pass='$user_pass', mail='$user_mail' WHERE uid = 1"

```

---
Tags: drush
---


# Question
Title: How to insert block into Article content type?
I haven't found any option or module to achieve this yet.

I started to think I should do this by inserting code directly into article, but this would not be really good/easy solution on regular basis, for Adsense for example....

# Answer
Have you tried Insert Block?

> Sidebar blocks contain all sorts of nifty stuff, but sometimes you want to include or embed that stuff into the body of your node. Instead of using PHP snippets (a possible security hole on public sites), you can use this module. When it's activated...
>
> \[block:name of module=delta of block\]
>
> ...will insert the contents of a rendered sidebar block into the body of your node. If no delta is specified, the default block for that module will be displayed.

There's only dev releases for this module, but it has almost 6.000 installations.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Add autoupload property after page load using plupload
In a form I have added a field for images, set the file source to "Advanced upload widget (Plupload)" ( all other checkboxes are unchecked ) and I get the interface. I want to make it autoupload images after being drag and droped or selected via the add image link. The form is loaded in a custom created page using a personal made module. I tried to set

```
$form['field_image_article1']['#autoupload']=TRUE

```

in myModule\_form\_alter and also called a myModule\_after\_build. None of the situations work and I can't figure out where or better sayd when should I set this value. Here is the code for the module :

```
function add_new_article_menu() {
  $items['addAnnouncement'] = array(
  'title' => 'Adauga anunt',
  'page callback' => 'add_new_article_simple_page',
  'access callback' => TRUE,
  );
return $items;
}

function add_new_article_simple_page() {
form_load_include($form_state, 'inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'announcement';
$node_form->language = LANGUAGE_NONE;
$form = drupal_get_form('announcement_node_form', $node_form);
return $form;
}
function add_new_article_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='announcement_node_form'){
    $form['#after_build'][]='add_new_article_after_build';
    return $form;
  }
}
function add_new_article_after_build($form, &$form_state) {
  $form['field_image_article1']['#autoupload']=TRUE;
  return $form;
}

```

Modules installed for plupload : FileField Sources Plupload, File Field Sources , Plupload integration module

Any help is most appreciated.

# Answer
> 0 votes
Drupal's plupload module does not support `'#autoupload'`. Or at least that's what I experienced. I wrote my own behavior for this:

```
(function($) {

Drupal.plupload = Drupal.plupload || {};

/**
 * Attaches the Plupload behavior to each Plupload form element.
 */
Drupal.behaviors.mymodule_plupload = {
  attach: function (context, settings) {
    $(".plupload-element", context).once('mymodule-plupload-init', function () {
      var uploader = $(this).pluploadQueue();
      if(uploader !== undefined) {
        uploader.bind('FilesAdded', function(up, files) {
          $('.form-submit').prop( "disabled", true );
          uploader.start();
        });
        uploader.bind('UploadComplete', function() {
          if (uploader.files.length == (uploader.total.uploaded + uploader.total.failed)) {
            // If nothing is being uploaded right now:
            $('.form-submit').prop( "disabled", false );
          }
        });
      }
    });
  }
};

})(jQuery);

```

I based it on codes and hints from the Internet, but I can't recall exact sources. I'll be happy to fix that and add reference links if someone recognizes parts of this.

---
Tags: 7, forms
---


# Question
Title: Password Gets Reset when executing user_save
I have a function that sets a user to confirmed after they login to my site for the first time. However, whenever I run this function and I log out and try to log back in the password doesn't work anymore and I have to do a manual reset in the database. I can't seem to find what would cause a change in the password. Any advice?

Note that I am using mongodb.

```
function update_profile($uid,$attribute_name,$attribute_value,$arrayaction=NULL)
{
    // update some user property
    $existing = user_load($uid);
    $edit = (array) $existing;

    //Update profile iformation
    if(!empty($arrayaction))
    {
        if(strtolower($arrayaction) == 'push')
        {
            array_push($edit[$attribute_name]['und'][0],$attribute_value);
        }
        else if (strtolower($arrayaction) == 'unset')
        {
            if(($key = array_search($attribute_value, $edit[$attribute_name]['und'][0])) !== false) {
               unset($edit[$attribute_name]['und'][0][$key]);
            }
        }
    }
    else
    {
        $edit[$attribute_name]['und'][0] = $attribute_value;
    }

    //Make the changes to the user
    user_save($existing, $edit);
}

function module_user_login(&$edit,$account) {
    if ($account->access == 0) {
        update_profile($account->uid,'field_confirmed',array('value'=>1),NULL);
    }
}

```

# Answer
> 1 votes
Be sure to

```
unset($edit['pass']);

```

if you don't want to edit password. Generally creating `$edit` from `$existing` shouldn't be needed. You do not need to re-save all fields, you only put into $edit what you know you want to change. You should, usually, be able to start with empty array, without seeding it first.

---
Tags: users, database
---


# Question
Title: How to change views pager with View All links
I am using the full pager in views module. I am displaying 40 items per page. The full pager display links like this

1 2 3 4 5 next last I want to change it to this

View All 1 2 3 4

How will I do this? Any idea about this?

# Answer
> 0 votes
The only way I can think of you achieving such a thing would be to create another display page in addition to the display page which already has a pager. And using html/CSS add a link to the footer of the views with pager called View all linking to the display page you created that shows all content.

---
Tags: views, paging
---


# Question
Title: How to override node comment form template?
I usually override a form template this way.

```
/**
 * Implementation of hook_theme().
 */
function MODULE_theme() {
  return array(
    'user_login' => array(
      'render element' => 'form',
      'template' => 'user_login',
      'path' => drupal_get_path('module', 'MODULE').'/templates',
    ),
  );
}

```

I create templates/user\_login.tpl.php in my module folder; then, I can override the form.

I tried overriding a node comment form this way, but it didn't work: The node comment form didn't use my custom template file.

I have googled a lot, but I got nothing about overriding a node comment form template.

How can I force Drupal to use a template file for the node comment form?

# Answer
> 1 votes
In Drupal 7, and in the case of the user login form, your trick works because the form doesn't set the #theme property; in that case, Drupal will use the theme function whose *machine name* is equal to the form ID. (For the login for, that is user\_login.)
That is not true for the comment form, for which its form build (comment\_form()) sets the #theme property.

```
$form['#theme'] = array('comment_form__node_' . $node->type, 'comment_form');

```

There isn't a match between the *machine name* of the theme the form builder wants to use, and the comment-edit form ID; the latter is comment\_node\_CONTENT\_TYPE\_form, not comment\_form\__node\_CONTENT\_TYPE. If you were defining a comment\_form theme function, that should work.

In Drupal 6, there is no #theme property for comment\_form, which is the form ID of the comment edit form.

# Answer
> 0 votes
Following code will allow you to use comment-form--node-forum.tpl.php template:

```
/**
 * Implements hook_theme().
 */
function hook_theme($existing, $type, $theme, $path) {
  return array(
    "comment_form__node_forum" => array(
      'render element' => 'form',
      'template' => "comment-form--node-forum"
    )
  );
}

```

Replace 'forum' to your content type.

---
Tags: forms, theming, comments
---


title: Select users with only one role

text:
# Question
Title: Select users with only one role
How can i select all users wich have only 1 role. For example i got 4 users:

**User 1:**

Role 1, Role 2

**User 2:**

Role 1

**User 3:**

Role 1, Role 2

**User 4:**

Role 1

How can i retrieve a list of users wich only got Role 1? But not Role 2.

```
$query = db_select('users', 'u');
$query->leftJoin('users_roles', 'ur', 'u.uid = ur.uid');
$query->leftJoin('field_data_field_full_name', 'n', 'u.uid = n.entity_id');
$query->condition(...);
$query->fields('u', array('uid','name','picture'));
$query->fields('n', array('field_full_name_value'));
$result = $query->execute()->fetchAll()

```

EDIT:

```
SELECT
u.uid AS uid,
u.name AS name,
u.picture AS picture,
n.field_full_name_value AS field_full_name_value,
f.field_function_value AS field_function_value,
pi.field_phone_intern__value AS field_phone_intern__value,
ur.rid AS rid,
COUNT(*) AS rolecount
FROM `dev_drupal_wurth-intranet`.users u
LEFT OUTER JOIN `dev_drupal_wurth-intranet`.users_roles ur ON u.uid = ur.uid
LEFT OUTER JOIN `dev_drupal_wurth-intranet`.field_data_field_full_name n ON u.uid = n.entity_id
LEFT OUTER JOIN `dev_drupal_wurth-intranet`.field_data_field_function f ON u.uid = f.entity_id
LEFT OUTER JOIN `dev_drupal_wurth-intranet`.field_data_field_phone_intern_ pi ON u.uid = pi.entity_id
GROUP BY u.uid;

```

This give me the result all the users and their number of roles. Now i tried to filter on this role count with 'WHERE rolecount = 1' but this just gives and sql error.

I'm not very advanced in sql :), still learning.

Thx

# Answer
You can try this one:

```
  $sub_query1 = db_select('users_roles', 'ur')
    ->fields('ur', array('uid'))
    ->condition('ur.rid', '3'); // Role 1

  $sub_query2 = db_select('users_roles', 'ur')
    ->fields('ur', array('uid'))
    ->condition('ur.rid', '4'); // Role 2

  $query = db_select('users', 'u');
  $query->leftJoin('users_roles', 'ur', 'u.uid = ur.uid');
  $query->leftJoin('field_data_field_full_name', 'n', 'u.uid = n.entity_id');

  $query->condition('ur.uid', $sub_query1, 'IN');
  $query->condition('ur.uid', $sub_query2, 'NOT IN');

  $query->fields('u', array('uid','name','picture'));
  $query->fields('n', array('field_full_name_value'));
  $result = $query->execute()->fetchAll();

```
> 1 votes

# Answer
If I were you (and with my poor level), I would proceed in 2 steps:

1. Get all the users with the role that interests you. Maybe inspire yourself for the query here: Get all users with specific roles using EntityFieldQuery
2. Browse the query result by loading each user and check if `$user->roles` has another role than the one you are looking for.
3. Push the final results in another array.

I don't know if it is a good way to proceed or if there is another way to achieve this, but I think it could do the trick.
> 0 votes

---
Tags: 7, database
---


title: Images don't show in Drupal 7

text:
# Question
Title: Images don't show in Drupal 7
I've created a content type with some custom fields, one of which is an image. When I try to render a node that contains some images uploaded like this the route is messed up, like this:

```
http://localhost/gisele-drupal//var/www/gisele-drupal/sites/default/files/contract.png

```

What can I do to configure this right?

# Answer
There is something wrong with you basepath.

in your .htaccess file make sure you uncomment this line

```
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

```

and in your settings.php file you may have to change your $base\_url

```
 $base_url = 'http://localhost/gisele-drupal';  // NO trailing slash!

```

let me know if that helps
> 4 votes

# Answer
i had the same issue but slightly different. Actually i had a site and working from few months on that, was working perfectly. today morning i saw some warning in report status in drupal 7.

so as per the guidance on a drupal official page i uploaded an .htaccess file.

after that i noticed this issue.

after a long googling i noticed a line in .htaccess file inside default/files directory.

i.e. Deny from all so i commented out this line with # only.

and my site is working fine now.
> 0 votes

---
Tags: 7, media
---


# Question
Title: Ubercart show Prices without Tax For specific Role
I need to show prices without tax for specific user role. Other available roles should see prices with included tax. How I can achieve this behavior?

# Answer
ubercart adds taxes in hook\_entity\_view\_alter( uc\_taxes\_entity\_view\_alter)

So I implement hook\_entity\_view\_alter in my module

```
function mymodule_entity_view_alter(&$build, $entity_type) {
  global $user;

  if($user && in_array(constant('SOME_USER_ROLE'), $user->roles)) {
    return;
  }

  // ...
}

```

Also unimplement uc\_taxes implemetation of hook\_entity\_view\_alter using hook\_module\_implements\_alter

```
function mymodule_module_implements_alter(&$implementations, $hook) {
  if (in_array($hook, array( 'entity_view_alter'))) {
    unset($implementations['uc_taxes']);
  }
}

```
> 0 votes

---
Tags: 7, ubercart, users
---


title: Issues with the entity field output

text:
# Question
Title: Issues with the entity field output
Suppose, we have an entity "song", that has a required field, called "authors":

In the list of songs in the admin panel I want to output the list of all the authors in the search block:

```
//search form
$form['search'] = array(
  '#type' => 'fieldset',
  '#title' => t('Basic Search'),
  '#collapsible' => TRUE,
  '#collapsed' => !empty($search_term) ? FALSE : TRUE,
);

//song name
$form['search']['search_text'] = array(
  '#type' => 'textfield',
  '#title' => t('Search Term'),
  '#default_value' => !empty($search_term) ? $search_term : '',
);

//authors
field_attach_form('song', null, $form['search'], $form_state, NULL, array(
                      'field_name' => 'field_authors',
                      ));

//submit button
$form['search']['search_submit'] = array(
  '#type' => 'submit',
  '#value' => t('Search'),
);

```

In the output I get this:

1. How can I make the checkboxes group non-required for the search form?
2. Why is the order of the fields broken? I added authors before the submit button, but in the output it's below the button.

# Answer
If I may, you're not doing this in the most optimal way.

The best solution would be to implement `hook_views_data()`, and describe your custom entity's base table to Views. Then you can use Views to build your page through the UI, and all of your entity's properties and fields will be available to output as fields, filter by (exposed or not), and sort by.

You get all of the flexibility you're used to with Views for nodes, and it's easy to write custom field/filter/sort handlers for your custom properties if they need a bit more functionality than the default.

To answer your original questions (in case you don't want to go down the Views path):

1. Remove the required attribute after the call to `field_attach_form()`, e.g. `unset($form['field_foo'][LANGUAGE_NONE]['value']['#required']);`
2. The order isn't broken, it's exactly what you've asked for. If you want the fields to appear before the search, but `field_attach_form()` before the definition of `$form['search']`.
> 1 votes

---
Tags: entities
---


title: Simulating TYPO3-Template-Engine

text:
# Question
Title: Simulating TYPO3-Template-Engine
For my next drupal project I need more flexibility in content-styling, than the standard approach allows. I need to be able to build the content-body for every single node from different elements. Like in TYPO3 I need a sandbox of pre-styled elements (e.g. full screen image, two column text, 3 boxes side by side, etc) and be able du add as many different elements as I want. The markup and styles should be saved in my theme, so there should not be any html in the content fields.

e.g.

**EDIT 1: Its basicly something like the Form builder what I am searching for. (see comments)**

Usualy I have used an WYSIWYG editor whith shortcodes, insert module and predefined styles, but I learned that it is not a good practice.

My approach which atm only work in the theory:

1. I use Field collection module for being able to add unlimited blocks of the collection.
2. Whithin the field collection I have one select-box where I define the template\_name for the collection.
3. Than I add all the fields I need (e.g. text, image, backgroundimage, date) to the collection
4. With the Conditional Fields module I controll which fields are needed/shown for every single template (see select box).

Screenshot 1 // Screenshot 2
5. The theming is done in my field-collection-template file (if template\_name == x, render this whithin particular markup)

Unfortunately this is really complicated ( I have to make a dependies for every single field in any template).

is there any better solution?

# Answer
The solution ist called Paragraphs!

It is still in the development, but looks pretty stable. even works with features!!
> 0 votes

# Answer
What about using entity references. You mention the field-collection approach, which has the same overhead as using entity references.

Basically you create a few node types that each conform to a different block element that you require. Then you create a master node with an entity reference field and select all of your block element node types as candidates, and set the filed count to unlimited. Then also use the inline entity form.

This will work but has a heavy server load.
> 0 votes

---
Tags: 7, theming, entities
---


# Question
Title: Modular Drupal content-type (variable sections)
I'm trying to build a modular and quite dynamic backend. I'm using Drupal for the task but haven't been able to spin my head around how to make it happen.

I need ideas on how I might solve this rather complex task.

---

To explain what I would like to end up with, I've faked a screenshot showing in steps what I would like the end result to look like.

**Step 1**

**Step 2**

---

My client wants to display his different cases. To make each case different, he wants a system where he can pick and choose how parts of his content is displayed. I suggested a modular approach where he can choose a "module type" in a dropdown, and fill in the needed fields.

There are plenty more, but for the sake of this questions, lets just stick with those.

---

**Needs:**

1. Possible amount of modules should be infinite.
2. Possible to fill in all information on the different 'modules' on the 'case' page.

Do you have any idea on how this might be solved?

# Answer
> 0 votes
You can do this with the Field Collection module.

Add a field collection to your Case node and then add then add fields of the types you require to the field collection restricted to the amount of images or videos you want to display. An with the correct image styles assigned.

You could use the Field Group module to collapse the fields to improve the admin interface.

Edit:

Another option would be use Conditional fields module and add image fields to the case content type set the the amount of images to be displayed in each and the image style required. Then add a list field to the case content type with option on 1 image, 2 images, 3 images etc and then use Conditional fields to link this to display and hide the image fields.

# Answer
> 0 votes
You might be interested in this usage of Display Suite example video from Drupal Camp 2011 LA a few years back:

http://replay.uci.edu/clients/drupal/Advanced\_Display\_Suite\_-*Flash*(Large)\_-\_20110806\_01.59.54PM.html

If you watch the video he has dozen such templates for the client to choose how a page is displayed. I believe he had a way to set like the template from a field choice when building the node.

Of course you the programmer need to define the templates -- but using DS + Views as he does makes this easier to manage (in code).

# Answer
> 0 votes
There is finaly a module which does the work: Paragraphs

Same here

---
Tags: 7, nodes
---


# Question
Title: MEGA MENU please help trying to assign it the right region but no luck :(
Hey can you guys please help me out iv tried researching and asking other but unfortunately have screwed it up many times and cant seem to get an answer out of anyone. Can someone please help me understand how to create a new region? I have mega-menu atm but when it was created in the files it went driectly under the menu bar which is not desirable... all im trying to do is put the mega-menu "menu" over the default one so it looks nice and professional anyone that can help me out, thanks.

# Answer
It depends a bit on your theme but for bartik here is answer:

In theme info file add this:

```
regions[my_custom_region] = My Custom Region

```

Then copy page.tpl.php from the base theme, or else from modules/system directory into your theme's folder. Open it up, and look for the bit where it prints out the main menu. It will be something like this:

```
<?php if ($main_menu || $secondary_menu): ?>
      <div id="navigation"><div class="section">
        <?php print theme('links__system_main_menu', array('links' => $main_menu,
'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline',
'clearfix')), 'heading' => t('Main menu'))); ?>
        <?php print theme('links__system_secondary_menu', array('links' =>
$secondary_menu, 'attributes' => array('id' => 'secondary-menu', 'class' =>
array('links', 'inline', 'clearfix')), 'heading' => t('Secondary menu'))); ?>
      </div></div> <!-- /.section, /#navigation -->
<?php endif; ?>

```

Remove this bit, then add this in its place:

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

```

Now clear your cache and place your block inside it.

Rename the my\_custom\_region to whatever you like, but make sure it is same in info file and page.tpl file.

If you don't want to replace the main menu then you can just paste the new code underneath the main menu, and in the menu settings UI select no main menu to hide it.
> 0 votes

---
Tags: theming
---


# Question
Title: How to make all images in Views display at same dimensions
My preview (thumbnail) images won't seem to display on my Views 3\*16 grid page and my edits in the image Filed don't seem to make a different. How do I ensure and force the Field image (cell) in the said Views page to show all the image content consistent in size? The image is a link to the actual page Node content. I'm probably missing something trivial, but you help would much appreciated.

(I'm using Bootstrap 3, Views 3.7 on Drupal 7.28).

Thanks.

# Answer
> 3 votes
You have to chose an image style for your images. Set up your grid image style first under admin/config/media/image-styles

---
Tags: views, theming
---


title: Submit form when field value changed

text:
# Question
Title: Submit form when field value changed
I have a simple form with method GET as follow...

```
function MYMODULE_form($form, &$form_state) {
  $form['#method'] = 'get';
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
    '#default_value' => isset($params['cat']) ? $params['cat'] : '',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
}

```

GET actuly bypasses the default submit and validation functions, which is ok for me. I want to submit this form without submit button, when value in 'Categories' field is changed.

```
function MYMODULE_form($form, &$form_state) {
  $form['#method'] = 'get';
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
    '#default_value' => isset($params['cat']) ? $params['cat'] : '',
    '#ajax' => array(
      'callback' => 'MYMODULE_form_submit',
    ),
  );
}

```

How should I do this?

# Answer
Here is how I was able to do this using attributes...

```
'#attributes' => array('onchange' => 'this.form.submit();'),

```

So it was just simple ....

```
function MYMODULE_form($form, &$form_state) {
  $form['#method'] = 'get';
  $params = drupal_get_query_parameters();
  $form['cat'] = array(
    '#type' => 'select',
    '#title' => t('Categories'),
    '#options' => $categories,
    '#default_value' => isset($params['cat']) ? $params['cat'] : '',
    '#attributes' => array('onchange' => 'this.form.submit();'),
  );
}

```

Now I am able to submit form when field is changed.
> 6 votes

# Answer
Like this?

css:

```
MY_FORM_SELECTOR input[type="submit"] {display:none;}

```

without `#ajax` property:

JS:

```
$('CAT_SELECT').change(function() {
   $(this).closest('form').submit();
});

```

or with `#ajax` property on submit field:

```
$('CAT_SELECT').change(function() {
   $(this).closest('form').find('input[type=submit]').click();
});

```

**UPDATE:**

* Create a JS file in theme directory
* Open MYTHEME.info file and add `scripts[] = JSFILENAME.js`
* Open JS file and put it something like this:

code:

```
(function ($) {
  Drupal.behaviors.SomeUniqueName = {
    attach: function (context, settings) {
      $('CAT_SELECT').change(function() {
        $(this).closest('form').submit();
      });
    }
  };
})(jQuery);

```

clear the cache, that's it;

ps:// if you want to submit the form with AJAX, this gist can help you
> 2 votes

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


# Question
Title: Form Alter Foreach Loop changes not sticking
I'm trying to modify my exposed filter block to put each of the controls inside fieldsets, and make other modifications to them.

However, when I try to utilize a foreach loop to do this, none of my changes are 'sticking'.

```
foreach($form_state['input'] as $delta => $input) {
    $collapsed = (empty($input) ? TRUE : FALSE);

    $form[$delta . '_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t($form['#info']['filter-' . $delta]['label']),
        '#collapsible' => TRUE,
        '#collapsed' => $collapsed,
    );

    $form[$delta . '_fieldset'][$delta] = $form[$delta];
    unset($form[$delta]);
    unset($form['#info']['filter-' . $delta]);

}

```

This wont work, but this will:

```
$delta = 'field_resource_type_tid';
$collapsed = (empty($form_state[$input][$delta]) ? TRUE : FALSE);

$form[$delta . '_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t($form['#info']['filter-' . $delta]['label']),
    '#collapsible' => TRUE,
    '#collapsed' => $collapsed,
);

$form[$delta . '_fieldset'][$delta] = $form[$delta];
unset($form[$delta]);
unset($form['#info']['filter-' . $delta]);

```

I've been trying to find out why this wont work, but I can't for the life of my figure out what the form modifications wont stick when done inside this foreach loop.

# Answer
> 0 votes
I've finally managed to resolve my issue, but I'm not sure why. I decided to change what array I was using to iterate through the filter fields on my form. By switching to iterating through the form array instead of form\_state, any changes I make to it now are sticking.

```
foreach($form['#info'] as $delta => $input) {
    $filtername = $input['value'];
    $collapsed = (empty($form_state['input'][$filtername]) ? TRUE : FALSE);

    $form[$filtername . '_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t($form['#info']['filter-' . $filtername]['label']),
        '#collapsible' => TRUE,
        '#collapsed' => $collapsed,
    );

    $form[$filtername . '_fieldset']['' . $filtername] = $form[$filtername];
    unset($form[$filtername]);
    unset($form['#info']['filter-' . $filtername]);

}

```

# Answer
> -1 votes
Try passing the $vars by reference by prefixing with "&":

```
foreach(&$form_state['input'] as $delta => $input)

```

---
Tags: theming, views, forms
---


# Question
Title: Get a list of revision IDs for any given entity?
What's the most uniform method for getting a list of revision IDs for any given entity, programmatically?

# Answer
> 2 votes
Figured it out. I'll leave it here because it might be useful to someone down the road.

You can use this function to get a list of all revisions ids for any given entity.

```
/**
 * Get a revision id list for a particular entity.
 */
function get_entity_revision_list($type, $entity) {
  $info = entity_get_info($type);
  if (!isset($info['revision table'])) {
    // If this entity does not track revisions then return FALSE.
    return FALSE;
  }
  if (!isset($info['entity keys']['revision'])) {
    // If for whatever reason a revision table was defined, but no revision key
    // then also return FALSE.
    return FALSE;
  }
  $revisions = db_select($info['revision table'], 'r')
    ->fields('r', array($info['entity keys']['revision']))
    ->condition($info['entity keys']['id'], $entity->{$info['entity keys']['id']})
    ->execute()
    ->fetchAllAssoc($info['entity keys']['revision']);
  return array_keys($revisions);
}

```

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


# Question
Title: Upgraded to 7.31 but getting "no pending updates" message
After copying over the files for 7.31 (was 7.26), minus the /sites folder, and running update.php, the result is "no pending updates." I followed the instructions at https://www.drupal.org/node/1494290 properly - any thoughts about what to do next? Thanks.

# Answer
> 0 votes
Go to '\[your-website\]/admin/reports/status' and if there you see that Drupal version is 7.31 (which you probably will see), if there is no some other errors and everything works fine on website you successfully did update.

It is not necessary to always have database update if you are updating some module or Drupal itself.

---
Tags: 7, upgrading
---


# Question
Title: User profile layout vs. contact form option
On the user profile I have some 12 fields for the users to enter their contact information and other details about themselves. The option to activate/deactivate the personal contact form is somwhere between the fouth and the fith field.

I would like to have to personal contact form option to be on a position I intend it to be on – e.g. the first position, before all other fields, since it's an option – and not a field. Disabling the drag'n'drop i can actually rearrange the fields in the intended order. But when I switch drag'n'drop field sorting back on, the checkbox jumps back down somewhere between field four and five.

Any suggestions anybody? Thanks!!

# Answer
> 0 votes
found the answer / an answer to my question: Installing and enabling the module profile2 helped. The missing fields ("Contact user element") showed up in the fields list and became sortable through drag'n'drop.

---
Tags: users, emails
---


# Question
Title: Use user/register instead of default login page for anonymous users
This sounds simple enough but I can't make it work.

Only registered users can view the site content, but instead of the login block, I want users to go to the user/register page (with the 'login' and 'request new password' tabs also there), and after registering then be taken to the frontpage.

I've tried the login redirect and login destination modules, but they don't help setting user/register as the defult page for anonymous users. I tried setting 'user/register' as the homepage in config/system/site-information and force logged-in users to the actual frontpage, but not surprisingly that didn't work. I tried disabling 'view published content' permission for anonymous users, and then set the 403 page to user/register, but nothing. I tried creating a rule (first time using rules) as follows:

Event: drupal is initializing

Condition: user has anonymous role

Page redirect: user/register

And other variations I could think of, but to no avail.

I don't think it's that difficult and I'm probably missing something. Can someone please advise?

# Answer
> 1 votes
Solved it. In case someone looks for something similar, to the rule above I added another condition:

```
NOT Text comparison - Parameter: Text: [site:current-page:url], Matching text: user

```

---
Tags: 7, users
---


# Question
Title: How can I extend a module and it's library with custom functionality?
My client requested a modification to their slider that will enable two captions. I'm using the Views Nivo Slider module and believe I can accomplish what I want by modifying the module"s code and extending the Nivo js file. But because I am still learning Drupal, I'm not very familiar with the details of how modules work with JavaScript libraries.

I have gathered that in order to extend a Drupal Module it needs to expose hooks. But it doesn't look like this module does that, so I assume that I'll create a custom module with this modules code as the basis. I know hacking up an existing module code is not the "Drupal way", and I won't if there is another way. Is there?

Also, if I wanted to add another function to an existing library like this one, is there a method through the Drupal module framework to extend the js file without messing with the libray code?

**Edit** Title changed to be more general.

I've tried the suggestion by @James Kirby and the field doesn't appear to be included in the markup when I inspect with firebug. Curious, how does the field get included to the slideshow output in your implementation if the fields are normally assigned through the "Views Nivo Slider" format settings? It doesn't look like I can assign divs or classes to the field through it's settings.

Here is what I am trying to achieve if possible. Example

Should I be researching my original approach?

# Answer
> 0 votes
i usually do this by adding fields to the sliders content type, then displaying them out through views then use css to position the text over the images

---
Tags: 7, javascript
---


title: Node id in views template

text:
# Question
Title: Node id in views template
Sorry if this question has been answered already but I couldn't find an exact answer. Maybe I'm missing something.

Context of my issue:

I have a view that lists fields of certain content type. One of the fields is the nid. I need to do some validation in the view template before printing anything. So I need to call a function and check something using the nid as parameter. In my views-view-fields.tpl.php I do something like:

```
<?php foreach ($fields as $id => $field): ?>
    <?php if ($id == "nid"): ?>
        <?php my_function_here($field->content); ?>
    <?php endif; ?>
<?php endforeach; ?>

```

As you might expect, $field-\>content is a string and if I do something like this in my function, it just won't work.

```
function my_function_here($nid) {
    var_dump(node_load($nid));
}

```

I tried casting the value to integer, but still no luck (casting returns 0):

```
function my_function_here($nid) {
    $nid = (int)$nid;
    var_dump(node_load($nid));
}

```

and

```
function my_function_here($nid) {
    $nid = intval($nid);
    var_dump(node_load($nid));
}

```

So my question is: how do I get the nid in that view template?

Big thanks in advance!

# Answer
From a similar issue - you can find details here (or just search for views preprocessor):

A preprocessor will give you access to the data, instead of rendered html which you find in the tpl file.

> There aren't dynamically generated preprocess functions; instead, all of the theme functions use the base preprocessor automatically. So views-view--my-first-view.tpl.php still uses template\_preprocess\_views\_view(&$vars) as its preprocessor function.
>
> You can add preprocess functions for specific views with the exact same naming conventions. Note that that it's named **preprocess* not preprocessor\_.
>
> Note that currently Drupal's design requires that you have the .tpl.php file in order to have the preprocess function (though you could drop in a generic preprocess function and do switches based upon information contained within the $vars\['view'\] variable. There's an issue for this which is fairly easily found by going to the Drupal queue and searching in the 'theme system' queue.
> 2 votes

---
Tags: views, nodes
---


# Question
Title: Can a taxonomy term be loaded into an EntityMetadataWrapper?
I want to load term fields in my application. Can I use entity metadata wrapper with reference to terms?

# Answer
Yes. Like so:

```
$term_w = entity_metadata_wrapper('taxonomy_term', taxonomy_term_load(TERM_ID));

```

The first parameter is the entity type ID. If you visit MODULE\_NAME\_entity\_info(), you can see the key of the definition will match the ID you need to load it.
> 14 votes

# Answer
Sam152 is right, but you don't actually need to convert the term\_id to an object, it will work with just the term\_id being passed as is:

```
$term_w = entity_metadata_wrapper('taxonomy_term', TERM_ID);

```
> 10 votes

---
Tags: entities
---


# Question
Title: Trying to modify Main menu by testing $vars['heading']['text'] == 'Main menu',
I'm trying to modify the code for the main menu only. below is my sorry code, which is not working. it attempts to see if $variables\['heading'\]\['text'\] equal 'Main menu'

```
function myTheme_link($variables) {
if($variables['heading']['text'] == 'Main menu') {
//put my mods here
} else {
  return '<a href="' . check_plain(url($variables['path'],     $variables['options'])) . '"' . drupal_attributes($variables['options']    ['attributes']) . '>' . ($variables['options']['html'] ? $variables['text'] :     check_plain($variables['text'])) . '</a>';
}
}

```

this must be close, no? i would greatly appreciate if someone could advise

# Answer
> 0 votes
How about a pure CSS solution:

```
#block-system-main-menu ul li:after {
    content:'*';
    padding:20px;
}
#block-system-main-menu ul li.last:after {
    content:'';
}

```

Or something to that effect.

To get support for IE7 look here.

# Answer
> 0 votes
You can do it by using this code in template.php file of your active theme.

```
function mytheme_links__system_main_menu($variables) {
  $html = "<div class='myclass'>";
  $html .= "  <ul>";
  foreach ($variables['links'] as $link) {
    $html .= "<li>".l($link['title'], $link['path'], $link)."</li>";
  }
  $html .= "  </ul>";
  $html .= "</div>";

  return $html;
}

```

or you can add customization in $variables also if we have do minor customization to do. Here replace mytheme with name of your theme. Clear you cache after using this code.

Hope it will help you!

---
Tags: theming, routes
---


title: Taxonomy term URL to eternity

text:
# Question
Title: Taxonomy term URL to eternity
What are you doing with URL's for Taxonomy terms, which tend to go in eternity, i.e.

/zen/taxonomy/term/4/615

which is identical with all

term/1 term/2 term/n etc....

They all show the same page?!

---

**Edit:**

So, yeah, people, this appears a way bigger issue with Drupal as I initially assumed...

I found a few more discussions on this topic, dated 5 and 2 years ago and without any real solution. And the possible problem is - hundreds and thousands of duplicate content pages, strictly banned by Google and other search engines....

So here is my 2 cents:

1. My first assumption was that I could do some simple re-direct....I would take this Match Redirect Module, which supports Wildcard redirects and do a few redirects like this:

node/ \*/ * to front

taxonomy/term/ \*/ * to front

taxonomy/term/ \*/feed/ * to front

-- But the Problem now is:

* It makes impossible to Edit Nodes, which are by path....

node/\*/edit

---\> So I need Exclusion -\> but it's not supported in module....

---

So - I am still with problem....

I don't know .htaccess regex so good to write it, I will search around and learn again....

But if there are some people who could write this for us - it would be appreciated very much...

# Answer
A taxonomy term page is reached through

```
taxonomy/term/%taxonomy_term

```

In taxonomy\_menu it is defined as:

```
 $items['taxonomy/term/%taxonomy_term'] = array(
    'title' => 'Taxonomy term',
    'title callback' => 'taxonomy_term_title',
    'title arguments' => array(2),
    'page callback' => 'taxonomy_term_page',
    'page arguments' => array(2),
    'access arguments' => array('access content'),
    'file' => 'taxonomy.pages.inc',
  );

```

The page argument is set to the 2nd term counting from 0, which is %taxonomy\_term.

It is therefore expecting to pass on one argument.

The page callback has this signature:

```
function taxonomy_term_page($term)

```

It also is expecting one argument (a loaded taxonomy object).

If you provide any extra arguments they are simply ignored as there is **no better fit**. However, if you look up a path such as:

```
taxonomy/term/%taxonomy_term/edit

```

then you are taken to the edit page because such a path actually exists and is the best fit. And if you look up a path such as:

```
taxonomy/term/%taxonomy_term/edit/blah/blah/blah

```

then you will be taken to the ancestor that fits best, which will be the edit page again.

It has nothing to do with taxonomy terms per se, but with the way a menu callback expects arguments.

Read more here: hook\_menu and Wildcard, ancestors and fitness
> 1 votes

---
Tags: redirection, uri
---


# Question
Title: Combining views slideshow and views gallery on single page
I have a views Slideshow on one page. I also have a views Gallery on another page. I want the views gallery to appear below the views slideshow on a single page. Please could anyone help me out. I have been trying a lot, but I'm unable to do this.

# Answer
> 0 votes
try the following:

* create a copy of one of the views as a BLOCK instead of a page
* under block configuration (admin/structure/blocks) for that view, limit it by page to ONLY show for the view still set as a page, and place it in the content or content bottom region

# Answer
> 0 votes
You could also use the Panels module. This module allows you to create partitions in a page & place content (such as Views or blocks or menus) within the desired partitions.

**!Note:** Make sure you specify different Pager ID (Edit View \> Page in middle column of the Edit view page \> Pager settings where you specify number of links to show, previous & next options, etc) for each of the views.

---
Tags: views, javascript, media
---


# Question
Title: Build page from content type course - use views or custom code
I'm looking to build a page like the wireframe below and need help to decide if I should use views or custom code. I haven't really used views before but looks like it could be a nice way to build up the page and add additional functionality (filtering, paging, searching etc) at a later stage.

My concern is the layout and also the links. One titled 'learn more' that links to the actual node and the other 'enrol' which is a course module link.

Should I use view or just custom code in a module?

# Answer
It's unclear from your post on your knowledge of Views. However if your referring to the 4 content boxes being shown in the sketch then Views is a great tool for doing this.

Regarding layout there is the functionality to return all fields you require in divs / classes etc and will be able to generate the look you wish.

Also links are no problem; in fields call up \[content:path\] - you can then add a 'custom text' field with your link

```
<a href='[path]' class="mybbutton">Link</a>

```

Views can general be viewed as a way of returning data from the database and present it how you wish. enjoy!
> 1 votes

# Answer
It seems you can achieve that using the Panels module

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.
> 0 votes

# Answer
You can acheive this easily by using views using grid layout of 2 items in grid .you can also use grouping for grouping your fields and for learn more you can use Global: Custom text type learn more in text field use replacement pattern output this field as a link using node/\[nid\] but you have to include nid field also excluding from display
> 0 votes

# Answer
As you are new to view I would suggest you to go with combination of views and Pannel 3 modules here is the tutorial to guide you: https://www.drupal.org/node/206792

one benefit of using views module in your scenario is you can customize html code inside a block by overwriting its theme file. Which gives you freedom to format your site look in the way you want.
> 0 votes

# Answer
Display all the fields you want to show in the course view page and "exclude" all the fields except the last one present in the display list.

Go to "Rewrite Results" section of last field which is not exclude from display. Check "Rewrite the output of this field". Use the "replacement patterns" and design your view as you want.

Enjoy...
> 0 votes

---
Tags: views
---


# Question
Title: How to filter a view to show current month
I am building a Church Management System. I have a contact type for individuals. One field they have is D.O.B. which is a date popup field.

I want to create a block that lists people and their D.O.B. and have it filtered to only show those whose birthdays are in the current month.

I created the block and have it showing the people and their D.O.B. but how do I get it to filter to show only the people in current month?

Thanks

# Answer
> 1 votes
in the view select filter type your dob field select apply then another popup opens in which you have to select "Date selection form element" as popup (Provided you have enabled the Date Popup module in Date API package) then "Filter granularity" by month select apply operator should be equal to and in front of that theirs a option select a date .. you have to select enter a relative date and in relative date type now.apply and save

# Answer
> 0 votes
Go for "Filter criteria" section add a condition to compare with current month. But first you need custom format DOB field values.

---
Tags: views
---


# Question
Title: Change function view_unformatted to work with format HTML list
I have function in template.php which check if image fields exists (has content) and it adds classes if image exists (has\_field) and if image does not exist (has\_no\_field).

This function now works with Unformatted format, but I need it to work with HTML list format. I already tried it with function theme\_views\_pre\_render(&$view) but could not get it to work.

```
function theme_preprocess_views_view_unformatted(&$vars) {
  $view = $vars['view'];
  $rows = $vars['rows'];

  foreach ($vars['view']->result as $id => $row) {

    if (!empty($row->field_field_image) || !empty($row->field_field_image_2) || !empty($row->field_field_image_3)) {
      $vars['classes_array'][$id] .= ' has_field';
    }
    else {
      $vars['classes_array'][$id] .= ' has_no_field';
    }
  }

}

```

How to make this work with HTML list format?

# Answer
I think the hook name you are looking for is template\_preprocess\_views\_view\_list that applies to HTML list views.
> 1 votes

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


title: List all nodequeues a node belongs to

text:
# Question
Title: List all nodequeues a node belongs to
Given I have a node, how to programmatically find out all the nodequeues it belongs to? Is there any ready functionality in Drupal 6 or do I just have query this from the DB myself?

# Answer
Here is what I ended up using:

```
$queues = nodequeue_load_queues(array_keys(nodequeue_get_all_qids())); // Cached by default
$subqueues = nodequeue_get_subqueues_by_node($queues, $node);
nodequeue_set_subqueue_positions($subqueues, $node->nid);
$nodequeues = array();

if (is_array($subqueues)) {
  foreach ($subqueues as $sqid => $subqueue) {
    if (!empty($subqueue->position)) {
      $nodequeues[] = $sqid;
    }
  }
}

```
> 1 votes

# Answer
Given that you have loaded the node in `$node` you can do:

```
$queues = nodequeue_load_queues_by_type($node->type, 'links');
$subqueues = nodequeue_get_subqueues_by_node($queues, $node);

```
> 1 votes

---
Tags: 6, nodes
---


title: Customizing user module output

text:
# Question
Title: Customizing user module output
I am using Drupal 7 to develop a REST API to create an iPhone app. The basic feature for this app user login and logout process. I am using the User module. The authentication process involved is session authentication. JSON is the output format used for the API.

How do I customize the JSON output from the login service? I am getting a bunch of other information which I don't require. I am not sure how to add more tags to the JSON format. Can anyone point me to the files where the information is?

For example, for a wrong username and password I get the following output:

> Status 401 Unauthorized - Wrong username or password
>
> \["Wrong username or password."\]

I would like to change the output to have something like `{status: 0, message: 'Wrong username and passowrd'}`.

Can anyone help me?

# Answer
> 0 votes
Use this for errors:

```
/**
 * Implements hook_rest_server_execute_errors_alter().
 *
 * Reformat error output.
 */
function up_coaching_rest_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {
  $error_alter_array['body_data'] = array(
    'success' => FALSE,
    'error' => $error_alter_array['body_data'],
  );
}

```

For success output you need clone needed resources from user resource definition.

---
Tags: 7, users
---


# Question
Title: Permission Issue with created actions and VBO
I’ve created a new action in a custom module using hook\_action\_info()

```
/**
 * Implementation of hook_action_info().
 */
function recruiteractions_action_info() {
  return array(
    'applicationentity_recruiterfillposition' => array(
      'type' => 'application', // <-- New entity type here
      'label' => t('Application Postion Fill Action'),
      'behavior' => array('changes_property'), //<-- Triggers an entity save.
      'configurable' => FALSE,
      'vbo_configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}
function applicationentity_recruiterfillposition(&$entity, $context = array()) {
  $app_wrapper = entity_metadata_wrapper('application', $entity);

 $app_wrapper->field_job_status->set(‘1');
 $app_wrapper->save();

}

```

After enabling in VBO this all works fine and as it should. The issue being when i set this to the role I need it to be set on.

the ‘Actions permissions (VBO) module is activated. and I can see the action; and have ticked the roles needed but with no joy.

I’ve also checked the ‘field\_job\_status’ permissions for the role I wish to allow to make changes.

On Drupal hook\_action\_info page https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_action\_info/7 there is a post regarding 'behavior's impact on permissions and specifically mentions VBO. however I'm not sure on what I need to do. Has anyone got any examples for this.

# Answer
> 2 votes
The solution here was to set the permission I want in the access\_callback of the custom entity itself.

so in my case the hook\_entity\_info

```
'access callback' => 'myentity_access_callback',

```

then added this in a function

```
function myentity_access_callback($roles = array()) {  // $op, $application = NULL, $account = NULL
 global $user;
 $roles = array(
   'administrator', 'anotheradminrole',
 );
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}

```

---
Tags: views, actions
---


# Question
Title: Webform validation are working but they some error
When I login and page redirects to home page, it shows this notice:

> Notice: Undefined index: submitted in web\_alter\_form\_validate() at line 19

Here is my code:

```
function web_alter_form_alter(&$form, &$form_state, $form_id){

    if($form_id) //Change webform id according to you webformid
      {
        $form['#validate'][]='web_alter_form_validate';
        return $form;
      }

}

function web_alter_form_validate($form,&$form_state){

    if($form_state['values']['submitted']['title']){

      $val_title = $form_state['values']['submitted']['title'];
      if(preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $val_title) !== 0){
        form_set_error('title', 'Special character are not allowed in form title.');
      }
    }
    // Then use regular expression to validate it.
    // In above example i have check if phonefield is empty or not.
}

```

I have set validations on webform title.

# Answer
> 0 votes
This line:

```
if($form_id)

```

is doing nothing. Form ID is never something that will be considered `FALSE`. PHP Manual says:

> When converting to boolean, the following values are considered FALSE:
>
> * the boolean FALSE itself
> * the integer 0 (zero)
> * the float 0.0 (zero)
> * the empty string, and the string "0"
> * an array with zero elements
> * an object with zero member variables (PHP 4 only)
> * the special type NULL (including unset variables)
> * SimpleXML objects created from empty tags

Form ID is a string, name of a function really, and as such can never be empty or `"0"`.

This means your function **always enters the code block** under `if`, and appends your validator to all forms. Most forms does not have *submitted* index defined, hence warning.

You probably wanted something like

```
if($form_id == 'some_form_ID_you_know_and_I_do_not')

```

and in validator something like

```
if( isset($form_state['values']['submitted']) and !empty($form_state['values']['submitted']['title']) ){

```

---
Tags: forms, webforms
---


# Question
Title: Add module-generated pages to Drupal 7's search index
I have a custom module that provides pages via hook\_menu(). The *page callback* returns HTML-formatted output that is then displayed. The information is fetched from an external database, so it is not a node/custom content type.

Since the displayed information is somehow the heart of this Drupal site, I want to add the information to Drupal's search index.

How can I facilitate this?

# Answer
1. Implement `hook_search_info()` to describe your new search type.
2. Implement `hook_update_index()`, build up the content you wanted to be indexed, and throw it over to `search_index()` (see the example in `hook_update_index()`).
3. Profit.

Be sure to follow all the advice in the comments in the linked functions, and check out the core node and user modules' implementations of these hooks for examples of exactly what you need to do. The comments for `hook_search_execute()` should also prove pretty helpful.
> 1 votes

---
Tags: search, routes
---