# Question
Title: What is the difference between hook_field_attach_validate() and hook_field_validate()?
I'm a bit confused as for the difference between these two hooks, and which one I should use for custom validation of attached fields in my code.

Is there a better way to define a custom validation for an attached field (I am attaching the field programatically if that helps)?

EDIT: Looking more into it, I don't really get all that much information in `hook_field_attach_validate()`. All I'm pretty much getting is the entity\_type, entity object and an errors array.

Whereas with `hook_field_validate()`, I get the field I'm actually validating against, which, I'm assuming is where I need to put the bulk of my custom field validation logic. The only issue I'm having now is that I'm unable to find a function that will invoke this method for me. Should I manually invoke this function or is there an API function I can use in this instance?

# Answer
hook\_field\_validate() Should be used to validate the form for your modules fields.

hook\_field\_attach\_validate() works on field\_attach\_validate() which is more for back end validation.

> This function does not perform field widget validation on form submissions. It is intended to be called during API save operations. Use field\_attach\_form\_validate() to validate form submissions.

Are the fields ones which your modules is creating, or are they fields from a third party module?

The #element\_validate property may be what you need to validate another modules fields.
> 2 votes

# Answer
In case anyone else like me finds this old question, here is a bit more information based on my own experiments and searching.

* There is now a D7 module Field Validation.
* It looks as if hook\_field\_validate() is only called for the module that defines the field, so that's no good for a standard field.
* If you use #element\_validate I think it would only affect the standard edit form - so for example not edits via View Bulk Operations. Maybe this doesn't matter to many people.
* You can use hook\_field\_attach\_validate(), as it is called from form validation in field\_attach\_form\_validate(). This hook is what the Field Validation module uses. Everything you need is inside the entity parameter.

Sample code below validates a phone number for the UK.

```
function XXX_field_attach_validate($entity_type, $entity, &$errors) {
  if (!empty($entity->field_telephone_number)) {
    foreach ($entity->field_telephone_number as $langcode => $items) {
      foreach ($items as $delta => $item) {
        if (!preg_match('/^0(\s*\d){9,10}$/', $item['value'])) {
          $errors ['field_telephone_number'][$langcode][$delta][] = array(
            'error' => 'XXX_telephone_number',
            'message' => t('Telephone number must be 10 or 11 digits starting with 0.'),
          );
        }
      }
    }
  }
}

```
> 0 votes

---
Tags: hooks
---


# Question
Title: How can I add a field to a content type which will accept a price value in the format of a currency?
I need to have price field which will display a price field. This field is a number with the dollar sign (i.e. $200). In my view, this price field will be used for sorting also.

I have installed and enabled the currency module and the currency API.

Via `structure > content type > manage fields >` I tried to add a new field. But the list of field types do not have the 'currency option'. So I am not sure how I should add the currency field **with a dollar sign**.

My question: How can I add a field to a content type which will accept a price value in the format of a currency?

# Answer
> 0 votes
# UPDATED ANSWER:

## using Views field rewrite:

on the field in the view setup, in the "rewrite results" section of the editing modal select the checkbox "Rewrite the output of this field" then scroll down and open the fieldset "REPLACEMENT PATTERNS" and use the pattern there to rewrite your field in the above textarea. as an example to put a "$" in front of the users uid I used `$[uid]`

## CCK field prefix:

You may just want to use a field that is for currency but doesn't actually include the currency symbol, so it can be saved as a number, which allows for better sorting. Then using views you can set a prefix to a displayed field of the desired currency symbol. This may only work with CCK fields.

---
Tags: views
---


# Question
Title: Disable emails turned into links but keep urls turned into links
Some users on social sites still enter their email addresses on comment fields. I'm trying to prevent spammers from harvesting them by replacing the @ character with a graphic. That's really easy to do using the smiley module.

However, I use the text filter option "Convert URLs into links" which turns the email into a mailto link. The smiley filter now breaks the HTML.

I would like to not turn emails into links but keep turning urls into links. How could I do that?

# Answer
> 2 votes
The easiest way is to creat your own input filter. Do a PREG and obfuscate the email address. Assign this filter to your input formats, and make sure it runs before the URL-to-link one.

# Answer
> 0 votes
Spamfree email module replaces email address with mailto links and obfuscates to js code for js supporting browsers and to image for non js browser thus preventing email harvest bots.

https://www.drupal.org/sandbox/abhiklpm/2465593

---
Tags: emails, navigation
---


# Question
Title: How show time period in one concrete time unit?
How can I show "time period" in one concrete time unit?

E.g.: I have a movie node type with "length" field with display formatted by time period. But if you put more then 60 minutes into it then it's displayed as "1h XX m".

I've tried to tweak this widget in settings but there is only "Granularity." which allows me to limit display to one hour ("1h") without minutes.

How can I format time period only in one time unit (e.g.: in only hours or in only minutes or in only seconds)?

# Answer
Perhaps it would be simplest to just use an integer field?

* Set the field type to Integer
* Click save, and then on the following page you should be able to set a "Suffix" of 'mins' or 'minutes' as you prefer.
* If you want a space between the number and minutes, be sure to type that at the start of the suffix field.
> 1 votes

# Answer
The time period module is in beta and minimally maintained. I would suggest using the Interval Module:

> Interval field gives you a simple field and widget to allow users to enter interval values eg
>
> * 2 months
> * 3 days
> * 4 years
> 1 votes

---
Tags: entities
---


title: Number of calls of hook_node_access

text:
# Question
Title: Number of calls of hook_node_access
I use hook\_node\_access() to redirect users, if they don't have the right attributes to see a specific node.

While programming I used dpm() to check some variables and was wondering, that dpm() is called 9 times although I just opened a single node.

Well, my question is: Is it normal, that hook\_node\_access is called several times for one node, so I should use drupal\_static() to avoid duplicate calculations or do I have some disadvantageous loops in my code that I should detect and remove (in hook\_node\_access are no loops, I mean somewhere else)?

I would welcome every advise!

Thanks, Daniel

# Answer
> 1 votes
Note that drupal\_static only operates within the scope of a single page request.

> All functions requiring a static variable to persist or cache data within a single page request are encouraged to use this function unless it is absolutely certain that the static variable will not need to be reset during the page request.

I tend to think that using drupal\_static might not help you, unless you can see that Drupal is calling your hook multiple times for the same node within a single page request.

I would say it **is** common to see a lot of calls to your hook. For example, Drupal needs to check access for any link you put on a menu - if access is not allowed, then the menu item is hidden.

Another possible approach is to use hook\_node\_access\_records(). Drupal caches the result of this call in the node\_access table, so your function will only get called when the node is saved. See the node access example.

# Answer
> 1 votes
Next time I should look into the docs first...

According to node\_access(), it doesn't consider the returned value NODE\_ACCESS\_IGNORE, which I return, if the user doesn't violate my permissions, so that other modules still can deny access, if their permissions might be violated.

So the answer of my question is: I should use drupal\_static() to avoid duplicate calculations.

---
Tags: 7, users
---


# Question
Title: File upload error "Files must be less than x MB" despite file being smaller than x
I have a `file` field called `Video` for a content type called `Tutorial Video`.

My settings are thus:

> **Allowed file extensions:** txt, mp4
>
> **Maximum upload size:** \[empty\]

The maximum upload section also has this text:

> Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP's maximum post and file upload sizes (current limit **100 MB**).

When I try to upload a 62MB MP4 video the `Video` field has (underneath the File Upload button) the following text:

> Files must be less than **100 MB**.
>
> Allowed file types: **txt mp4**.

After I select the file and hit upload I get the following error message:

> An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (100 MB) that this server supports.

I have requested my host upgrade my limits. They said they have set it to 250mb. I edited my php.ini and changed that to 500mb. I'm lost...

# Answer
The `upload_max_filesize` parameter in php.ini (or accessed elsewhere) must follow the file size naming that PHP understands:

```
upload_max_filesize = 100MB  // NO
upload_max_filesize = 100 MB // NO
upload_max_filesize = 100 M  // NO
upload_max_filesize = 100M   // YES

```

Also keep in mind that many shared hosts will cap this value at a higher level. So ask your host and use something reasonable like 25M or 50M - just putting in a ridiculously high value like 500M won't necessarily help you.
> 1 votes

# Answer
After contacting my hosting company they said it was a problem with my php.ini file and they resolved it. I did not get any further explanations.
> 0 votes

---
Tags: files
---


title: Where to declare an API key?

text:
# Question
Title: Where to declare an API key?
I'm confused about the following:

I'm working on a module that creates a interactive Google Maps background, I've added the Javascript to my module ( which is run at hook\_init), but when I try to load the page, the maps background doesn't show up.

Before I decided to create a module, I used the same Javascript code which was called on page load through the header-section (through script\>src) in my page.tpl.php file, and everything worked as it was supposed to.

So I'm suspecting that, because I call the module with hook\_init, my Javascript cannot show up because the API key hasn't yet been validated/declared by the page.

What's the best way to tackle this problem? Can I declare the API key in my .module file? or even my module.js file? Or should I change the hooks to something else, in that case, is there a hook that lets me call the module.js file after the head of my page is loaded?

```
<?php function maps_markers_init() {
$markerAantal = 0;
$latitudes = db_query('SELECT field_latitude_value FROM {field_data_field_latitude}')->fetchCol();
$longitudes = db_query('SELECT field_longitude_value FROM {field_data_field_longitude}')->fetchCol();

json_encode($latitudes);
echo "<br>";
json_encode($longitudes);
};

```

And to load the Javascript:

```
function maps_markers_page_build(){
drupal_add_js(drupal_get_path('module', 'maps_markers') .'/maps_markers.js');
};

```

# Answer
Eventually things got fixed, learned that you can just add a .js file into your module with the HOOK\_init() since they get stored to use at a later stage.

What obviously was causing the problem, was the wrong declaration of the API key, this was fixed by adding the line:

```
drupal_add_js("https://maps.googleapis.com/maps/api/js?key=[MY API KEY]", "external");

```

to the document. After that, I could call the .JS file with:

```
drupal_add_js(drupal_get_path('module', 'maps_markers') .'/maps_markers.js');

```

More information on how everything was fixed can be found here: Module conflicting with JQuery
> 3 votes

---
Tags: 7, hooks, google-maps
---


title: Module conflicting with jQuery

text:
# Question
Title: Module conflicting with jQuery
I've set up a simple `hide-show.js` file for my website and I'm working on a module as well. Problem is, if my module is active, the jQuery for the page doesn't work, is there something I need to do to 'close' my module after writing or anything?

Edit: My console does not show any errors. And with jQuery I mean the functions on the page (i.e. clicking on a hide-show button does nothing).

```
<?php function maps_markers_init() {

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
}  else {
        $latitudes = db_query('SELECT field_latitude_value FROM {field_data_field_latitude}')->fetchCol();
        $longitudes = db_query('SELECT field_longitude_value FROM {field_data_field_longitude}')->fetchCol();

        json_encode($latitudes);
        json_encode($longitudes);

        require(drupal_get_path('module', 'maps_markers') . '/maps_API.php');
    };};?>

```

`maps_API.php` contents:

```
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[api key]"></script>

```

Also, hide-show.js contents:

```
$ = jQuery.noConflict();

($(function(){
        $(".collapse_btn_down").click(function(){
            $(".mid_div").fadeToggle( "800" );
            $('.buurtkiezer').toggleClass('buurtkiezer_solo');
            $('.content_wrap').toggleClass('content_wrap_solo');
            $(this).toggleClass('collapse_btn_up');
            $(".legenda").css("margin-right","20px");
            $(".legenda").css("margin-top","-80px");

        });

}));

```

# Answer
First of all, you need to clean up your code, this could be simply a syntax error:

1. There should be no semicolon after `else` block
2. There should be no semicolon after function block
3. Do not use PHP closing tag in Drupal module files, it can cause weird errors like this one

If this does not help, we need to see what is in the `maps_API.php` file.

EDIT: You cannot load javascript file into PHP, when you use `require()` it has to be PHP code, otherwise you get syntax errors. In your case, you are including HTML `<script>` tag, which means nothing in PHP. Use `drupal_add_js` to include your JS file - documentation on that function here \- this is a Drupal function that saves all scripts to be included, and then when the HTML response is being created it builds the `<script>` tags for you.

The easiest option how you can do it is to include it inline, like this:

```
drupal_add_js("https://maps.googleapis.com/maps/api/js?key=[api key]", "external");

```
> 1 votes

# Answer
Is the issue just with the hide-show js script or is it with jquery in general? In other words, are you experiencing jquery issues all over the site after you enable the module or is it just on the page where your hide show js needs to be activated?

Overall, your question is a little vague. Just include more details and we can give you a better answer.

Lastly have you looked at the developer tools in whatever browser you are in to make sure there are no errors?
> 1 votes

# Answer
The best way to avoid conflict would be using JS injector module. After installing the module, go to `Admin -> config -> Development -> JS injector` and add you `jquery/javascript.`

In the `JS code` section, you can add your jquery. Don't forget the format should be like as follows:

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

====JavaScript/jQuery goes here====
}
};
})(jQuery);

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How to display block to the nodes of specific content type?
I have created a content type "test". I also created a block "Search". I like to display the block only to nodes of the content type.

I configure the block and under Show block on specific pages \> Only the listed pages \> Entered

> test/\*

. It did not work. How can I display the block only to the nodes of the "test" content type?

Thanks, D

# Answer
> 1 votes
In the block configuration page, select the content type like this picture:

---
Tags: blocks
---


# Question
Title: Sharing files privately individual users
I'm trying to create a Drupal 7 feature whereby an admin uploads multiple files that are only visible/downloadable by a specific user. These files would be visible on the user's profile page or (alternative) a document page where a user would only see the files available to them. Ideas?

# Answer
Drupal private files can only be downloaded by someone who has access to the *node* the file is attached to.

So you can set up a content type that allow an unlimited number of files attached to a node. Then you set up an Access Control List to that node, where you make sure only the specific user has access to the node. Let the admin create one node per user, and upload all files to be shared privatly with a specific user to the user's node.

To mange access control lists to nodes, you can use **Flexi Access** module.
> 1 votes

# Answer
Another option, simple as it doesn't require extra nodes:

* Install the Field Permissions module
* Add a File field to the user (admin/config/people/accounts/fields)
* When editing the field you have just added, you should see the config options for Field Permissions in a section titled "Field visibility and permissions". Choose appropriate permissions. You can let the user view their own value, but only admins edit. Or you can let the user edit their own files too.
> 0 votes

---
Tags: 7, users, files
---


# Question
Title: Creating and updateable block on home page of site
I have a 'featured resource' block on the home page of my site. I'd like my very non-technical folks to be able to update this block with a new node every week. Note that it would just display the teaser of the node, with a 'read more' link.

Ideally, it would be easy for them to do this (for example, by just checking a box on the node creation/edit page to add it to the featured resource block).

Anyone have recommendations for the best/easiest way to do this?

# Answer
> 1 votes
Drupal allows a node to be marked as "Promoted to front page" when editing the page (it's at the bottom, under "Publishing options").

You can make your block from a View

* Enable the Views module.
* Add a new view admin/structure/views/add
* Create a block (untick create a page)
* Click "Continue & edit"
* Add a filter by "Promoted to front page"
* Alter "Use pager" to display 1 item.
* You should already have a sort by post date.
* Save changes.
* Add the block to your home page (it sounds like you already know how to do this, but ask if not).

This view will show the most recent item with promoted to front page set.

---
Tags: blocks, nodes
---


# Question
Title: SearchApiQuery - possible to remove a filter?
The query parameter that is passed to `search_api_query_alter` has `SearchApiQueryFilter` member. It contains a protected array of filter elements. I can add to this by calling the `createFilter()` and `filter()` methods, but it does not appear that there is a way to remove a filter through the API. Can this be done?

# Answer
I found the solution, but be careful: it is very tricky! Ideally, it should be special method in the SearchApiQuery class itself, or method in class-wrapper, which will be used everywhere in code...

My solution based on ability to access private members of classes, passed to \__constructor function:

```
class SearchApiQueryFilterAlter extends SearchApiQuery
{
    public $altered_query;
    function __construct(SearchApiIndex $index, array $options = array())
    {
        if (isset($options['original_query']) AND isset($options['filter_alter'])) {
            $options['original_query']->filter = $options['filter_alter'];
            $this->altered_query = $options['original_query'];
        } else {
            parent::__construct($index, $options);
        }
    }
}

```

Property $altered\_query will contain original query with modified filters.

Usage example:

```
function product_list_search_api_ranges_minmax_alter($variables, $order)
{
    /** @var SearchApiQuery $query */
    $query = $variables['query'];
    $filters = $query->getFilter();
    $new_filters = $query->createFilter();
    foreach($filters->getFilters() as $filter){
       if(!$filter->hasTag('facet:field_product:commerce_price:amount_decimal')){
            $new_filters->filter($filter);
        }
    }
    $options = array(
        'original_query' => $query,
        'filter_alter' => $new_filters
    );
    $filter_alter = new \Drupal\product_list\SearchApiQueryFilterAlter(new SearchApiIndex(), $options);
    $variables['query'] = $filter_alter->altered_query;
}

```

In this example all filters has been copied to the $new\_filters, except one with special tag. Then, we pass original query and new filters to class constructor through $variables. And empty SearchApiIndex, which is nesesary. Finally, in $filter\_alter-\>altered\_query we have the query with deleted filter condition.
> 0 votes

---
Tags: 7, search
---


# Question
Title: Scaling and integrating existing disconnected drupal based sytems?
We are currently planning to scale our current digital platforms to support a small number of number franchised businesses operating in different international locations.

Would appreciate a bit of help sense checking.

We are thinking about eventually effectively rebuilding our existing Drupal 7 website as a Drupal 8 site multisite installation -one installation for each business location (assuming that is the logical thing to do considering it is expected to release in the fall??).

We also have a separate Drupal 7 installation that is used as a system for accepting public submissions. I would like to upgrade to Drupal 8 rather than redevelop.

We will also be developing a smart phone app that gives users a view of their account and provides rewards etc... Currently these systems are all effectively disconnected.

We have two groups of existing users (currently residing in the two separate Drupal installations) that we need to migrate to our new system and somehow centralise.

We want to connect all of our systems (Drupal multisite installation, Drupal submission system, smart phone app and a CRM) and implement a single sign on mechanism

The thinking I am currently being sold is that we need to place the CRM system as a kind of central repository of account information that all systems can defer/sync to?

Does this seem logical/possible?

Could anyone provide any thoughts on all that?

---

***just adding some more information...***

The Drupal 8 part was really just based on (obviously incorrect) assumption that D8 was a more advanced stage of development that it currently is. Was trying to avoid the task of having to upgrade all of our work in 12-24 months time if it was built using Drupal 7. Maybe that is unavoidable though and needs to be factored in.

Part of the reason we were looking at a multi-site was for ease of management and administration.

We will be running sites for 9 geographically separated 'members' each of whom will have limited technical resources, plus a submission system, plus a centralised digital asset management system, plus a centralised CRM, plus our smartphone based rewards app.

Single sign on along with a central (hopefull CRM driven) view of user account information and ALL interactions is really the most important feature of what we are trying to achieve. If there is a need for a measure of technical complexity and additional resources to support that, so be it.

---

***just adding a tiny bit more information...***

Thank you so much for taking the time to talk through some potential solutions. I am just beginning to wrap my head around the work that is ahead of us and you have helped me hugely.

We are trying to balance efficiency and ambition for the project. Ultimately our *IT staff* will probably amount to *at most* two people to centrally manage the systems and infrastructure and one part time admin level user in each international location.

I have also been looking at the domain access module as an alternative to multisite (which I am moving further away from the more I read) https://www.drupal.org/project/domain

We've actually used Civicrm and hate it. Our 'Marketing and Comms' departments vision for the CRM is to provide a central system that provides all staff members (globally) with a view of all users (globally) and maintains a record of a logged in users interactions across our entire business (we would seek to integrate the CRM with other external systems like submissions, ticketing, retail POS, ecommerce etc...) it would also provide us with advanced integrated comms, segmentation and targeting tools. We'll likely need lots of custom code and likely an API of some sort too.

I guess the thing is that it's not just Drupal authentication we need to be able to handle. We need users with an account to be able to log in to lots of services or applications (in an ideal world that would include a logging in and viewing account info via a smartphone app, logging into onsite wifi, logging in to some ecommerce system) at every point information is being gathered and collated to provide business intelligence.

As I say there is a fantasy/reality scenario here. As a business, there are things wee need soon (more websites with a single sign on implementation for example) but rest of the tools we want are fairly technically complex to deliver and not exactly matched by the resources that are currently available. We acknowledge that but there is a requirement for us to plan for integration of tools on this scale at some point in the not too distant future.

# Answer
A couple of things to consider:

1. Unless the sites are very simple, or you are intending to use the project as a way to contribute to Drupal 8, Drupal 8 is *not yet ready* (as of this post) for production use. You may find yourself doing a **lot** of bug-fixing, coding, porting of contrib modules etc. But if that's what you want to do, it will be a great boon to the community!
2. Multisite has advantages and disadvantages, there are many blog posts and such discussing this and I'm sure you've probably read some of them. The biggest factors that influenced my decision (we use multisite) were:
    * You only have to update the core files once each time
    * You only have to keep one set of contrib modules up to date (`sites/all/modules`)

If you're making sites for different clients I would caution against multisite because it means you have to update core for *all of your client sites at once*. In most cases this is fine, but what if something goes wrong? **All** of your clients will be on your back at once clamouring for a fix and you'll spend more time calming them than fixing the problem, not to mention that's a bad experience for *all* of your clients, not just one.

Nobody is immune from issues, even if they only happen once in 5 years.

I understand you're working with franchisees... but they're still effectively clients.

Here's the thing - you don't need to share the code-base in order to share certain tables such as the user table (that and a few others when shared make for really easy SSO).

Everything you're suggesting can be done. But, if it's only about accounts, I would keep separate code-bases (doesn't cost any more RAM or CPU as far as I know, just a bit of HD space), and share the user table (and maybe roles).

---

\[Response to extra info:\]

Drupal 7 will be around for years yet, until there's a release Drupal 9, in fact, you will have to upgrade eventually, but now is not the time unless the sites are very simple, and these do not sound like simple sites.

I had further thoughts about my answer above, and the multiple client situation *can* work as long as you've got a good rollback method for upgrades and your IT staff are happy to do upgrades outside the hours the sites need to be operational. The biggest issue with that is when your different clients or members are in different time zones and have different needs regarding down-time.

What sort of interactions are you hoping to log? Sounds like you'll need some custom code for that (duh). If the member sites are all carbon copies you should be able to reuse it across them.

Drupal has a CRM plugin called CiviCRM but it's not really set up for commercial purposes. I'm guessing you're using something like SugarCRM or Zoho or SalesForce, you will have quite a large task on your hands. One of Drupal's core abilities is to manage users, what do you want the CRM to do?

Would it be enough to have your main repository of user account information in Drupal and then push that repository and all relevant events to a CRM? What about an event tracker like Google Analytics or Woopra?

If you're being sold multi-site with a single user repository as an idea, I think Drupal should be the repository, because then you can do this.

---

If you were doing all your user management on Drupal, and all you need is a repository of credentials for logging in to other systems, consider LDAP (docs, project). You can push all changes from Drupal to LDAP and then have your other systems read credentials from there.
> 1 votes

---
Tags: performance, authentication-authorization
---


# Question
Title: Productivity tool to help me add multiple fields at once
Is there any Drupal productivity tool that will help me create multiple fields at the same time? I'm taking about about the actual creation of the fields under /admin/structure/types/manage/node\_type/fields. I have a hundred of fields to create and it seems tedious to keep hitting the save button every time I create one.

# Answer
> 1 votes
Just wondering about the use case for hundreds of fields - this seems a bit bizarre. Maybe consider using Field Collections to group similar fields and combine with use multiple values per field on a field collection.

As for a possible solution (although not recommended since a lot of things could go wrong) - if you have many similar fields you could export some "base" fields using features and copy-paste inside the features' files the relevant fields. Clearing cache or feature-revert would create the relevant fields.

# Answer
> 1 votes
Another path that's different from Moo64c's good suggestion using the Features module, is to use the Drupal API to create the fields programmatically using `field_create_field()` & `field_create_instance()`. Here's an example tutorial. You can find many different examples over the web.

---
Tags: 7, entities
---


title: Hide YouTube Video For Some Countries

text:
# Question
Title: Hide YouTube Video For Some Countries
Hello I Am Making A Website On Drupal And I Am Adding A YouTube Video On Some Page So I Want To Hide These Videos From Some Countries example I Want To In Usa So I Want to hide in india So Which Module Or Way That I Can Do It

# Answer
Try https://www.drupal.org/project/geo\_block. It will allow you to add your video to a block and choose which countries should or should not see it.

Keep in mind however that this, like most other region blocking/detecting tools can be tricked.
> 1 votes

---
Tags: files
---


title: How to hide field if blank

text:
# Question
Title: How to hide field if blank
I have a view created which has a column 'Price'. I also I have another column 'Special Price' in the same view, but '*exclude from display*' is selected.

In views, click the price field \> rewrite results \> Rewrite the output of this field \> I added the below:

> $\[field\_price\]
>
> Special $\[field\_special\_price\]

I would like to display the *special price* only if the special price field has a value. If the special price field has no value, I only want to display the *price* field value. I am not sure how I can modify it ?

Thanks, D

---

I am new to drupal. Sorry if I am not clear. In the views, I would like to put price and special price in the same column. I will add some css to special price. If I un-selected exclude from display for special price, then special price will be in another column which I do not want to do.

Please visit the page and see the price column.

http://bettylist.com/ac/myview

Thanks.

# Answer
Then dont exclude special price from display and customize that field. There's an option @ No results behavior, where you need to check Hide if empty.

THEN, all you need to do is to style the two fields where they're both present.

That's the simplest way. There is another way, where you exclude both from display and add another field at the end "Global text area", where you can play with the tokens and rewrites.
> 0 votes

# Answer
Follow these steps:

1. Rewrite output of `[field_special_price]`
2. Make it `Special $[field_special_price]`
3. Make sure that under no results behavior, "hide rewriting if empty" is checked.
4. Now rewrite the output of `[field_price]`.
5. Make it `[field_price]<br/>[field_special_price]`

Also `[field_special_price]` should have weight less than `[field_price]`. I think you know this well.
> 0 votes

---
Tags: views, entities
---


# Question
Title: New to Drupal 7 and I was wondering if this is possible to do?
I am new to Drupal 7 (it's been years since I touched Drupal 6) and I have a question regarding a concept.

Is it possible to "port" an external web applications into Drupal so it appears to be part of the website, but the app itself actually lives on another server? The external web application will have no dependencies on Drupal other than it's served up via Drupal so it appears to be part of the site.

Example - I build a webform an it lives on Server A, can I server it up via Drupal and keep all of the apps functionality?

Is this possible?

# Answer
> 1 votes
Yes, it is possible. You can port an external web application, and can make it automatically compatible with your div specific properties. I suggest you to use jQuery to get external web application.

To add jquery in drupal 7, you need to install JS injector module. Enable the module and you can add jquery at `admin -> config -> development -> js-injector`. In the JS code section, the syntax is as follows:

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

   =====your jQuery code goes here ==========

}
};
})(jQuery);

```

For porting an external web application, let us assume you have a link/button in a specific div section and when you click on that link/button, I'm going to display that website in a target div section.

HTML should look like this:

```
<div id="sourceDiv">
   <a href="http://example.com"> Click here to port an external website. </a>
</div>

<div id="targetDiv" style="width:720px; height:500px;">

</div>

```

And the jquery to port web application:

```
$('#sourceDiv a').on('click',function(){
    var url = $(this).attr('href');
                                     //returns the targetDiv's height and width
    var height = $('#targetDiv').height();
    var width = $('#targetDiv').width();
                                    //replaces the div with porting the website.
    $('#targetDiv').replaceWith( "'<object data="+url+" width="+width+" height="+height+"/>'" );
    return false;
   });

```

# Answer
> 0 votes
Yeah, it's certainly possible. One easy route is to embed the app as an iframe. Something like this Google Form:

`<iframe src="https://docs.google.com/spreadsheet/embeddedform?formkey=MyFormKey" frameborder="0" width="500" height="300" marginheight="0" marginwidth="0"></iframe>`

Assuming your source web application URL doesn't display a design around around the interface, it should embed fine into a Drupal content page.

If your source web application URL does have a design around the interface, you'll have to do something more complicated where Drupal will act like a proxy around the source web application.

---
Tags: views
---


title: Login programmatically using ajax

text:
# Question
Title: Login programmatically using ajax
I have a button in my custom module

```
  function sign_up_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['captcha']['#suffix'] ='<input type="button" id="test" name="test" value="OK">';

    $form['#attached']['js'][] = array
      (
       'type' => 'file',
       'data' => drupal_get_path('module', 'sign_up') . '/js/sign_up.js',
    );

         $form['actions']['submit'] = array("#type" => "submit", "#value" => "Create Account",
        "#ajax" => array(
        "wrapper" => "formwrapper", "effect" => "fade", "method" => "replace",));
   }

```

Note: Ive removed the callback key of #ajax inorder to avoid page refresh.

In my sign\_up.js I made an ajax call when this button is clicked.

```
  $(function() {

      $("#test").click(function(){

         $.ajax({url:"/path/to/normalphp/page/userLogin.php",success:function(response){

          alert(response);

      }});
    });
  });

```

The onclick is working and the ajax call is also successful.

In my userLogin.php (not a module file.Normal php file) I just hardcode the uid and call user\_login\_submit() .

```
<?php

 chdir($_SERVER['DOCUMENT_ROOT'].'/');
 define('DRUPAL_ROOT', getcwd());
 //Load Drupal
 require_once './includes/bootstrap.inc';
 drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $account = array('uid' => 49); //existing uid
  user_login_submit(array(), $account);

```

The result which I expect is to automatically redirect the user to welcome screen.But this is not happening.When I try to login with this user from the drupal login page its successful. This is just a test as I wanted to customize my registration screen (make ajax calls,jquery validations etc) and then automatically redirects to welcome screen when the validation is success. Note: I have already done the settings in drupal where email notification is not needed. Can someone help me out in this?

# Answer
Instead of using jQuery AJAX, you can achieve this by Drupal Form API AJAX.

You can hide the Actual submit button in the hook\_form\_alter using hide() and add a custom button with AJAX callback.

Or if you still want to practice this using jQuery AJAX, Drupal's way of handling AJAX calls is little different. You may have to first understand the hook\_menu in Drupal. Once you have a clear understanding of this system, you have to create pages using this hook. In drupal, it is not advisable to create custom php files for handling AJAX callbacks. Instead you can create a page using hook\_menu and handle the server callback there. For the JS part, the Drupal way is to use Drupal Behaviors

This is a small example of how it would look like.

Your custom module to handle AJAX login (sign\_up.module)

```
<?php
function sign_up_menu {
    $items = array();
    $items['custom/user-login'] = array(
        'page callback' => 'custom_user_login_callback',
        'type' => MENU_CALLBACK,
        'access callback' => TRUE
    );
    return $items;
}
function custom_user_login_callback(){
    /**
     *  You can validate the User credentials here and provide error message for invalid credentials or send him to welcome page using drupal_goto() for valid credentials
    **/
}

```

## -

The custom JS file (sign\_up.js)

```
Drupal.behaviors.customSignUp = {
    attach: function(context, settings) {
        $("#test", context).once(function(){
            $(this).click(function(){
                $.ajax({
                      url: Drupal.settings.basePath + 'custom/user-login',
                      type: 'POST',
                      data: {
                        username: /** Pass the User Name **/
                        password: /** Pass the Password **/
                      },
                      success: function(response) {
                        $('#ajax-response-wrapper').html(response);
                        Drupal.attachBehaviors();
                      }
                });
            });
        });
    }
};

```
> 2 votes

---
Tags: ajax, users, redirection
---


title: Views Page Title Based on URL

text:
# Question
Title: Views Page Title Based on URL
I have a view that has a generic title, but uses contextual filters to show the data. I would like to contextually update the title, but am not seeing a solution to this. Is this possible?

Page URL: /person/jon-doe/roster

Page Title: Jon Doe (based on %2)

# Answer
Since you're using Views and the user name. All you need to do is:

1. Add a Contextual Filter, User: Name
2. Under it's settings pane, under WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED, check Override title
3. Then just input %2

So now /person/jon-doe/roster would display as jon-doe as the page title.

If you would want the user's normal name like Jon Doe, then you could follow Immanuel Paul's answer because you aren't basing the page title literally from the URL.
> 3 votes

# Answer
You can set the Title based on the URL using the drupal function *drupal\_set\_title*

in any of the Template preprocess functions such as ***template\_preprocess\_views\_view*** or ***template\_preprocess\_page***
> 0 votes

---
Tags: 7, views
---


title: How to connect 2 forms in drupal 7?

text:
# Question
Title: How to connect 2 forms in drupal 7?
I have 2 forms in drupal 7 and I want to connect these 2 form.. Means when I will fill first form with some values then this form should be submit with ajax.After submit new form should be show.

# Answer
You might need MultiStep form using ajax enabled. Just implement `#ajax` on the buttons of form as in the given link.

```
    $form['buttons'] = array(
      '#type' => 'container',
    );
    if($form_state['step'] !== 1) {
      $form['buttons']['back'] = array(
        '#type' => 'submit',
        '#value' => t('Back'),
        '#limit_validation_errors' => array(),
        '#submit' => array('ajax_form_multistep_form_back_submit'),
        '#ajax' => array(
          // We pass in the wrapper we created at the start of the form
          'wrapper' => 'ajax_form_multistep_form',
          // We pass a callback function we will use later to render the form for the user
          'callback' => 'ajax_form_multistep_form_ajax_callback',
        ),
      );
    }
    if($form_state['step'] !== 3) {
      $form['buttons']['forward'] = array(
        '#type' => 'submit',
        '#value' => t('Next'),
        '#ajax' => array(
          'wrapper' => 'ajax_form_multistep_form',
          'callback' => 'ajax_form_multistep_form_ajax_callback',
        ),
      );
    }
    else {
      $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#ajax' => array(
          'wrapper' => 'ajax_form_multistep_form',
          'callback' => 'ajax_form_multistep_form_ajax_callback',
        ),
      );
    }

```
> 0 votes

# Answer
You might find this helpful .. Node Save Redirect

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

---
Tags: 7
---


# Question
Title: Building form and saving as a content type
I have designed a site. In this site there is a content type for our experts. Also we need to design a form to employ more experts. We need people send form and admin see their forms, edit and then publish as our content type. Problem is, webform is not suitable for this. Is it possible using CCK as a webform? Is there another solution for this? Is it possible saving webform as a content type?

Thank You

# Answer
What you need is the workflow module. You would create your content type with all of the same fields as your current webform but set it to default 'unpublished.'

Enable the workflow and create new workflow states for 'draft' and 'reviewed'. Set your actions to mark it in draft when the node is created by the user and then allow your editors to approve and publish.
> 2 votes

# Answer
`Maestro module` provides the `workflow control` for `drupal`,For your content you are free to use `content type` or `web form` If you are using `content type` no additional module is needed to install but if you are planning to use `web form` then you have to use `maestro_webform_task` module to integrate your `web form` with `maestro`.Also if you are using `web form` you need to provide the permission to different users to see the `web form`.

Maestro module
> 0 votes

---
Tags: 7, entities, webforms
---


# Question
Title: Use a form instead of content type in maestro drupal module
I am working on `maestro module` of `Drupal 7`, the module uses `content type` to add the form fields ,but instead of `content type` i want to use simple form which i have created using `php` , can anyone please help me , it is very urgent. Thanks a lot in advance

# Answer
> 1 votes
**for those who are still searching the answer for this question**

We can use `webform` instead of `content type` with `maestro`, for that we need `maestro_webform_task` module, the module will integrates both web form and `maestro` and provides the list of already created web forms in `web form` `task->edit->select web form to use`

maestro\_webform\_task

---
Tags: 7, nodes
---


# Question
Title: How to implement User roles for specific taxonomies?
# Some info about what I'm working on:

* I have a taxonomy on my site called 'countries'.
* I have three 'countries' terms: "UK", "USA", "AUS"
* I have created a new user role in Drupal 7 called 'countries\_admin'.

# What I am trying to achieve:

* I want to be able to add three countries\_admins and assign each one a country (and be able to easily add more users when I add more terms).
* The user should only be able to create/view/edit/delete nodes which are in this term.

# My question:

Any suggestions about how to do this?

**Note**: I have tried Taxonomy Access Control but it seems that I'd have to create a new user role for each country, which isn't really what I wanted.

# Answer
> 1 votes
It appears to me that there are 2 ways to answer your question. Read on for more details ...

### Option 1: The Organic Groups module

Organic Groups is a possible answer to your question. It is probably the module that most users are familiar with.

If you're not familiar (enough/yet) with Organic Groups, then reviewing the amazing set of (free) videos to Learn Organic Groups might help.

### Option 2: The Group module

Maybe you want to give it a try to use the Group module, which is like an alternative for Organic Groups. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

Resources:

### Comparing both modules

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?".

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


# Question
Title: How do I override an endpoint provided by a module in a feature?
I am using the Services module and Drupalgap, which provides a service endpoint by default. I want to make changes to the available services on the *drupalgap* endpoint, and I manage configuration on my site using Features, so I want to override the endpoint provided by Drupalgap.

However, if I check the box in the Features UI, it doesn't add the drupalgap endpoint because it's already "owned" by the Drupalgap module.

I dug into the code and the Drupalgap endpoint is provided by **drupalgap\_default\_services\_endpoint()**. I tried adding the exported service configuration in **mymodule\_drupalgap\_default\_services\_endpoint()** and clearing the cache but it doesn't look like this gets picked up.

So, how can I override a service endpoint in a module's code with my own code for that endpoint? If there's no way to do it, I guess I can cut and paste the exported, updated code over the endpoint in the Drupalgap module, but that seems like the wrong approach.

# Answer
> 0 votes
I found a smooth way to do this without overriding anything.

1. Create a new services endpoint by cloning the Drupalgap endpoint.
2. Add the new endpoint to a feature to keep it in code.
3. In Drupalgap's *settings.js*, change the endpoint to the new custom endpoint. The relevant line is:

// Default Services Endpoint Path

Drupal.settings.endpoint = 'drupalgap';

---
Tags: services, features, javascript
---


title: hook_preprocess_html in my module

text:
# Question
Title: hook_preprocess_html in my module
I am having a content type with fields select list, js, css, and body. In the select box it list a number of templates to apply on the current node. I have these custom templates in the templates folder of the active theme, in the format

```
my-module-blank.tpl.php, my-module-custom1.tpl.php
```

And on select list I have blank and custom1 as options. In the hook\_preprocess\_node, using theme\_hook\_suggestions I have did the same,

```
  $variables['theme_hook_suggestions'][] = 'my_module_' . $field_template_list;

```

But it is not taking the template, In addition I need to use hook\_preprocess\_html to include the custom css and js added to fields of content type to the header portion. I didn't find any proper documentation on it.

Please show me a better documentation so that I could implement.

# Answer
> 2 votes
`hook_preprocess_page()` is called before `hook_preprocess_html()`. `hook_preprocess_html()` would probably be the last one that's run in a page build.

If you want your CSS and JavaScript when displaying a node, you can add the files it in the preprocess function for the node template.

```
function THEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full') {
    $node =& $variables['node'];
    if ($node->type == 'something') {
      $path = drupal_get_path('theme', 'THEME');
      drupal_add_css($path . '/misc/jquery.fancybox-1.3.4.css');
      drupal_add_js($path . '/misc/jquery.mousewheel-3.0.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-1.3.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-calls.js', array('type' => 'file', 'scope' => 'header'));
    }
  }
}

```

You can add a custom template for any content type like:

```
node--[node-type].tpl.php

```

I would suggest you to use `hook_preprocess_page` at `template.php` for this:

```
function MYTHEME_preprocess_page(&$variables, $hook) {
    if (isset($variables['node'])) {
        if ($variables['node']->type == 'something') {
            $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->type;
        }
    }
}

```

**Note:** Don't forget to clear your cache after this :)

---
Tags: theming
---


# Question
Title: How to add a preview image to a content type?
Is there a functionality in Drupal to add a preview image to a content type (for example in the info file). The idea is, that an editor who doesn't know which content type to choose for his content would see a 'preview image' in addition to the description text and then know what content type he would need to use. I can't find anything like this in the system and no module which would provide this functionality.

# Answer
No, this functionality is not in Drupal core.

It could (at least in principle) be added through a contributed module, but AFAIK, there is currently no contributed module offering this.

It may not be trivial to add this feature in a meaningful way. It is not unusual for Drupal sites to have content types that uses the same visual layout - but different workflows and access rules - for different use cases. A "preview image" would not distinguish them from each other in such cases.

While the idea of different content types for different purposes is at the core of the "Drupal way" of building a site, I've noted that many ordinary users, editors and even admins struggle with this particular idea. The problem you mention: "the editor who doesn't know which content type to choose for his content" is a real one.

I've not found a really good solution to this. In the real world helpful content type descriptions are often not read by users/editors/admins.

My solution so far is to offer a very restricted number of content types to end users, and use very descriptive names for the types they're exposed to (e.g. "Personal blog post", "Embedded video").
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: View's row style output is NULL, template file not found in ./
I'm theming a block view that displays content that is related to the current node. When I preview the view results they show up fine, but the content doesn't render in my theme.

When I examined more, I noticed the **views-view-unformatted** template renders correctly and contains three `rows` as expected, but each of the `rows` just contains the value NULL.

The theme information tool in Views gives the following error regarding row style output:

> **Row style output:** views-view-fields.tpl.php, views-view-fields--read-next.tpl.php, views-view-fields--default.tpl.php, views-view-fields--default.tpl.php, views-view-fields--block.tpl.php, **views-view-fields--read-next--block.tpl.php (File not found, in folder ./)**

I created the file **views-view-fields--read-next--block.tpl.php** with the following content:

```
<?php foreach ($fields as $id => $field): ?>
    <?php print $field->content; ?>
<?php endforeach; ?>

```

Unfortunately that did not help. The file is still not found and nothing is rendered. Other things I've tried:

* Disabling devel\_themer
* Clearing all caches
* Restarting Apache
* Checking file permissions
* Changing the view formatting back and forth a few times
* **Edit:** Rescanning the template files

What can be the problem? I don't know where to look next. I'm using **Views 7.x-3.10**.

# Answer
> 0 votes
I finally found out the cause of this - I had previously defined the function `mytheme_views_view_fields__read_next__block()` in **template.php** and forgot to return a value. Views module's theming information gives a confusing error message when templates are defined in **template.php** instead of the **templates** directory.

# Answer
> 0 votes
After creating a new tpl file for views to pick up you need to hit the button called " rescan template files" at the bottom of the window. So that your new tpl gets highlighted.

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


title: Translating only Field labels

text:
# Question
Title: Translating only Field labels
I'm using Entity Translation and I've enabled "Enabled, with field translation" in a content type but don't want to translate each individual field.

It seems "Field translation" of i18n suit does it and in translate interface at admin/config/regional/translate/translate we can translate the field labels.

But the problem (as in the photo) is that it shows the same field text for all the content types sharing same field with same label. That is for same label I should be able to translate once only.

Is there any more simple way to translate field labels at once?

A similar question is here: How to translate Boolean field labels? but seems to be more specific.

# Answer
You need to download internationalization module and enable `field_translation` module which comes in this package. How to translate the field labels:

1. Go to manage fields. For ex. Articles, the path will be admin/structure/types/manage/article/fields/
2. Click edit for field\_tags.
3. You'll see a translate tab there. I have attached the screenshot.
4. Translate field name and description there. It works.
> 2 votes

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


# Question
Title: Why does Drupal not register Menus Nor Links?
One of the website that I manage the menu system is not working. I have installed many modules (including the commerce modules) and are not being displayed on the menu. However, all modules links (and commerce) works, if I type it on the URL.

After troubleshooting a little bit more I figure out that this is not only for commerce. I created a new content type and is not been display on the `node/add` page or in the admin\_menu. And once again I'm able to go to the page if I type the URL.

I click on rebuild menu, I flush all caches and still not been register. I do not see any Drupal logs errors.

How can I address this problem ? I cannot expect the sysadmin to know all the URL.

**Update 3/27/2015**

I'm now using the latest Drupal (v7.35) and I noticed this at first on 7.34.

Like I mentioned before it is not only on the menu. So I do not think the admin\_menu is the problem. I remove the module admin\_menu and use the toolbar module. But there are missing links on the pages that are been created for the latest module that I have installed. So any module that I enable from now on it would not register the pages.

**Update 4/3/2015**

I'm now using the latest Drupal (v7.36) and I noticed this at first on 7.34.

I disable/uninstall and enable drupal core menu module and still not fix this issue. Someone from the Google + community suggested that this issue may be cause by the jquery updated I try to used different jQuery version and still have issues. In addition, I try to follow this How to completely wipe and rebuild drupal menus? and to rebuild all my menu and did not work.

I strongly believe is need to be something with the hook\_menu not working on my Drupal website.

**Update 4/4/2015**

I notice that if I add a new content type it would not appear the links on the `node/add` nor under the content menu. However, it appear in the page `admin/structure/types` and in the menu under structure -- \> Content Type.

Some more updates to address one of the suggested answers to try to get my issue reolved:

* This is single site installation.
* I do not think is because of the memory\_limit. Because I have managed bigger sites that does not have this issue. I did try it out and it did not help. I.e in my setting.php I set it up to 300M and on my php.ini as well. After that I cleared caches, run cron, restart the webserver. And still nothing.

# Answer
> 1 votes
It would be interesting to see if your problems could be related to the "memory limit", which might not be high enough (anymore), especially since in the OP it says "I have many modules enabled".

I'm assuming that this is NOT a multi site. So therefor consider editing your /sites/default/settings.php, and change the line to set the memory limit. If it is a multi site, then edit the settings.php file related to the site where you are experiencing the problem.

That line in settings.php should look similar to this:

```
ini_set('memory_limit', '100M');

```

The '100M' in it might be some other number. Whatever the number is, try to increase it with like 50%, or maybe even double it to see what happens after you do so (of course do not forget to save the file after increasing that number).

Curious to hear if that helps somehow ...

Here are a few other thoughts that might ring a bell in the right direction (if you haven't tried them yet):

* temporary turn of all caching, to see what the impact is of doing so. Of course that cannot be the real solution in most cases, but at least it might give some indication like "it seems to be caching related".
* what about compression of JavaScripts and/or CSS? If you have turned them on, what happens if you (temporary) disable them?

# Answer
> 0 votes
The fact that items aren't showing on the node/add page is very strange and doesn't seem related to admin\_menu at all. I'd suggest as a first step, to look in the menu\_links table and seeing if there is an entry for the content type that's missing. in the link\_path column you can see this if a node/add/ entry is there. If there is, it should also show up if you go to structure -\> menu's -\> navigation menu in the list.

Can you check this please?

# Answer
> 0 votes
Some things to try:

1. Are there any errors in watchdog or the server itself, especially when the cache is emptied?
2. Can you manually empty any database tables prefixed with cache\_?
3. Is site-wide caching enabled, if so can you disable?
4. Is there any caching mechanism installed on the server, e.g. Varnish, Memcached, APC, etc.
5. Are you logged in as user 1 or some other user, if some other user have you checked the permissions?

# Answer
> 0 votes
I had run into this issue, fixed with these steps.

1. Disable caching by adding this code to your `settings.php`

```
<?php
$conf['admin_menu_cache_client'] = FALSE;
?>

```
2. Turn off `php page compression` and `javascript aggregation` at `admin/config/development/`
3. Comment out the following lines in admin\_menu.module file in admin\_menu\_js\_cache function:

```
header('Content-Encoding: ' . $encoding);
$content = gzencode($content, 9, FORCE_GZIP);

```
4. If the above doesn't work, try to change compression in PHP.ini file as
> `zlib.output_compression = On` replace on with `Off`

I remember, I got this issue when I was using `Drupal 7.33`. But it should work for `7.34`, assuming there are no `custom module.` If there are any custom modules, please check if any of the `.module` files have misconfigured php tags.

# Answer
> 0 votes
Sounds to me like one of your modules is causing a conflict in a hook\_menu call and thus the menu is not being updated. To find the culprit follow standard module debugging technique:

(On a development copy):

1. Turn off all contributed modules.
2. Turn them on one by one until the error appears.
3. Look for the offending code, probably in the module's `hook_menu` function. Check submodules and .inc files too.

An alternative is to turn modules *off* one by one until the error goes away, sometimes this is easier, especially if you have custom modules, you should definitely test those first.

# Answer
> -1 votes
I think this is problem with admin menu caching. Go to `admin/config/administration/admin_menu` Under performance vertical tab uncheck the option to cache menu in client-side browser. See if it works, otherwise try uninstalling admin\_menu module completely and clearing drupal's cache and browser's cache. Also try it opening in another browser.

---
Tags: routes
---


# Question
Title: How do i create nested tabs in drupal 7 view?
I am trying to create an image gallery from view.

I have a content type called "Photo-Gallery" with fields ***title of event,year,month and images***

I have created a view with this content type and created page with Unformatted list.I am trying to make a gallery based on the following layout. How can i code custom view template?I want this by Year wise and then Month .

Unfortunately i am stuck on half way. Could you please suggest me a proper way to code the view to get the exact result.

Awaiting quick replies.

# Answer
> 0 votes
You could use Quick Tabs Module along with Views Module to achieve this result.

A simple overview to achieve this might be:

> Since Quicktabs uses blocks as tabs, If you create a views blocks for each single items of a content type and then add them to quick tabs manually.

Look through this http://mtt.desk.com/customer/portal/articles/992921-how-to-add-quick-tabs-with-multiple-view-blocks-inside-a-specific-page to get an idea.

---
Tags: views, media
---


title: How to implement Taxonomy as Role?

text:
# Question
Title: How to implement Taxonomy as Role?
I am building an application for a university where teachers will submit questions(MCQs) into Topics(Vocabulary) containing many terms infact in hundreds.

Our business logic is so that teachers will be allowed to submit questions only of their respective **academic field**, so we need to limit the list of topics to teachers based on their area of field. For example computer science teachers will submit questions in computer science term and its children.

So basically what I want it, something like one role per taxonomy term, I tried the Taxonomy Access Control module and the user permission module, but to no avail.

Is there a better solution for limiting taxonomy terms per user? Not per role or should I then create a role against every taxonomy term?

# Answer
> 0 votes
The Taxonomy Term Permissions module is what you are looking for.

From the project page description:

> This module allows taxonomy administrators the ability to restrict setting individual terms on nodes by user or role.

# Answer
> 0 votes
How about considering this question as yet another variation of either of those questions:

If you agree, my answer to this question is similar to what I answered in How to implement User roles for specific taxonomies?. I.e. that it appears to me that organic groups seems your best bet to answer your question (in this case the question is about "**academic fields**" instead of "**cities**" or "**countries**").

Also take into account the "maintenance / development status" of any module you're considering, as explained in my answer in the 2nd question above, about "Maintenance Scorecards". E.g. when considering Taxonomy Term Permissions, as suggested in another answer here: for D7 there is no official version yet (only a beta2 release from about 2,5 year ago). Similar for Taxonomy Access Control, suggested as a possible alternative in one of the other questions mentioned before (only a RC1 release for D7, from about 3,5 year ago).

Disclosure: I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph),
I hope this does not violate the site's policy on self-promotion.

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


title: Drush commands in migrate do nothing

text:
# Question
Title: Drush commands in migrate do nothing
Every time i try to run and drush migrate commands I get the same output on the console. What is this about?

When I run the command locally it lists all available migrations but when I run it on the dev environment it just acts useless. All required modules are enabled and ither users can run these commands on dev.

Local drush version 5.10 Dev drush version 5.11

Any idea why?

```
$ drush @something.dev migrate-status
tput: unknown terminal "unknown"
Execute a drush command. Run `drush help [command]` to view command-specific
help.  Run `drush topic` to read even more documentation.

Global options (see `drush topic core-global-options` for the full list):
 -d, --debug                               Display even more information,
                                           including internal messages.
 -h, --help                                This help system.
 -ia, --interactive                        Force interactive mode for commands
                                           run on multiple targets (e.g. `drush
                                           @site1,@site2 cc --ia`).
 -n, --no                                  Assume 'no' as answer to all
                                           prompts.
 --php=</path/to/file>                     The absolute path to your PHP
                                           intepreter, if not 'php' in the
                                           path.
 -p, --pipe                                Emit a compact representation of the
                                           command for scripting.
 -r <path>, --root=<path>                  Drupal root directory to use
                                           (default: current directory).
 -s, --simulate                            Simulate all relevant actions (don't
                                           actually change the system).
 -l <http://example.com:8888>,             URI of the drupal site to use (only
 --uri=<http://example.com:8888>           needed in multisite environments or
                                           when running on an alternate port).
 -v, --verbose                             Display extra information about the
                                           command.
 --version                                 Show drush version.
 -y, --yes                                 Assume 'yes' as answer to all
                                           prompts.

Core drush commands: (core)
 archive-dump (ard,    Backup your code, files, and database into a single
 archive-backup, arb)  file.
 archive-restore       Expand a site archive into a Drupal web site.
 (arr)
 cache-clear (cc)      Clear a specific cache, or all drupal caches.
 cache-get (cg)        Fetch a cached object and display it.
 cache-set (cs)        Cache an object expressed in JSON or var_export()
                       format.
 check (ck)            Check common site configuration issues.
 core-config (conf,    Edit drushrc, site alias, and Drupal settings.php files.
 config)
 core-cron (cron)      Run all cron hooks in all active modules for specified
                       site.
 core-execute (exec,   Execute a shell command. Usually used with a site alias.
 execute)
 core-quick-drupal     Download, install, serve and login to Drupal with
 (qd)                  minimal configuration and dependencies.
 core-requirements     Provides information about things that may be wrong in
 (status-report, rq)   your Drupal installation, if any.
 core-rsync (rsync)    Rsync the Drupal tree to/from another server using ssh.
 core-status (status,  Provides a birds-eye view of the current Drupal
 st)                   installation, if any.
 core-topic (topic)    Read detailed documentation on a given topic.
 drupal-directory      Return path to a given module/theme directory.
 (dd)
 help                  Print this help message. See `drush help help` for more
                       options.
 image-flush           Flush all derived images for a given style.
 php-eval (eval, ev)   Evaluate arbitrary php code after bootstrapping Drupal
                       (if available).
 php-script (scr)      Run php script(s).
 queue-list            Returns a list of all defined queues
 queue-run             Run a specific queue by name
 search-index          Index the remaining search items without wiping the
                       index.
 search-reindex        Force the search index to be rebuilt.
 search-status         Show how many items remain to be indexed out of the
                       total.
 self-update           Check to see if there is a newer Drush release
 (selfupdate)          available.
 shell-alias (sha)     Print all known shell alias records.
 site-alias (sa)       Print site alias records for all known site aliases and
                       local sites.
 site-install (si)     Install Drupal along with modules/themes/configuration
                       using the specified install profile.
 site-reset            Reset a persistently set site.
 site-set (use)        Set a site alias to work on that will persist for the
                       current session.
 site-ssh (ssh)        Connect to a Drupal site's server via SSH for an
                       interactive session or to run a shell command
 test-clean            Clean temporary tables and files.
 test-run              Run tests. Note that you must use the --uri option.
 updatedb (updb)       Apply any database updates required (as with running
                       update.php).
 usage-send (usend)    Send anonymous Drush usage information to statistics
                       logging site.  Usage statistics contain the Drush
                       command name and the Drush option names, but no
                       arguments or option values.
 usage-show (ushow)    Show Drush usage information that has been logged but
                       not sent.  Usage statistics contain the Drush command
                       name and the Drush option names, but no arguments or
                       option values.
 variable-delete       Delete a variable.
 (vdel)
 variable-get (vget)   Get a list of some or all site variables and values.
 variable-set (vset)   Set a variable.
 version               Show drush version.
 watchdog-delete       Delete watchdog messages.
 (wd-del, wd-delete)
 watchdog-list         Show available message types and severity levels. A
 (wd-list)             prompt will ask for a choice to show watchdog messages.
 watchdog-show         Show watchdog messages.
 (wd-show, ws)

CTools commands: (ctools)
 ctools-export (ctex)  Export multiple CTools exportable objects directly to
                       code.
 ctools-export-disabl  Disable CTools exportables.
 e (cted)
 ctools-export-enable  Enable CTools exportables.
 (ctee)
 ctools-export-info    Show available CTools exportable objects.
 (ctei)
 ctools-export-revert  Revert CTools exportables from changes overridden in the
 (cter)                database.
 ctools-export-view    View CTools exportable object code output.
 (ctev)

Runserver commands: (runserver)
 runserver (rs)        Runs a lightweight built in http server for development.

Acquia Purge commands: (acquia_purge)
 ap-diagnosis (apd)    Perform a series of diagnostic self-tests.
 ap-domains (apdo)     List all domains Acquia Purge will purge against.
 ap-forget (apf)       Forget all scheduled purges and empty the queue.
 ap-list (apl)         List all the items that are in the queue.
 ap-process (appr)     Purge all queued items from the command line.
 ap-purge (app)        Purge a specified path from your balancers.

Field commands: (field)
 field-clone           Clone a field and all its instances.
 field-create          Create fields and instances. Returns urls for field
                       editing.
 field-delete          Delete a field and its instances.
 field-info            View information about fields, field_types, and widgets.
 field-update          Return URL for field editing web page.

All commands in migrate: (migrate)
 migrate-analyze       Analyze the source fields for a migration.
 (maz)
 migrate-audit (ma)    View information on problems in a migration.
 migrate-auto-registe  Register any newly-defined migration classes
 r (mar)
 migrate-deregister    Remove all tracking of a migration
 migrate-fields-desti  List the fields available for mapping in a destination.
 nation (mfd)
 migrate-fields-sourc  List the fields available for mapping from a source.
 e (mfs)
 migrate-import (mi)   Perform one or more migration processes
 migrate-mappings      View information on all field mappings in a migration.
 (mm)
 migrate-messages      View any messages associated with a migration.
 (mmsg)
 migrate-reset-status  Reset a active migration's status to idle
 (mrs)
 migrate-rollback      Roll back the destination objects from a given migration
 (mr)
 migrate-status (ms)   List all migrations with current status.
 migrate-stop (mst)    Stop an active migration operation
 migrate-wipe (mw)     Delete all nodes from specified content types.

 e

```

# Answer
I was using Drush 5.10; upgrading to Drush 6 fixed this issue.
> 0 votes

---
Tags: drush, migrations
---


# Question
Title: Response comes after 6 min while creating user using services module of Drupal 7?
I have a client side application developed in angularJS. As i am sending POST request to Drupal to create user, user is getting created without any delay if i check in Backend. But i get response after 6minutes!. The request just goes on and on!! Any advice what i am doing wrong?

# Answer
> 1 votes
It's unlikely that your site needs 6 minutes of CPU time to create a user but you can confirm that checking the system load during the process.

When I've faced that kind of problems the reason was one or more timeouts when trying to connect to an external service from the server.

For example, imagine that when you create the user the site querys an external database via an HTTP connection checking for the user usual nickname (Abigail → Abbie, Peter → Pete, etc). If that external service is down your site happily will launch the connection, waiting patiently the answer until the timeout is reached and connection is closed. If your site tries to connect six times and system timeut is 30 seconds then there you have your six minutes for use creation.

Check your installation for modules that may conenct to external services, check dblog for timeouts errors messages, check system log for similar messages. Disable any suspicious module and try to create a user.

If this only happens when using Services (not in the regular user creation form) narrow your search to any Services related modules or custom code.

---
Tags: services
---


title: DS and theme hook suggestion

text:
# Question
Title: DS and theme hook suggestion
in my site I have update DS to the last versione 7.x-2.7 and now theme-hook\_suggestions does not works. Drupal is update to the last version, too.

I, via mytheme\_preprocess\_node() function, insert some hook\_suggestions for my node, based on node type and a field value.

Via devel themer I can see this:

Candidate template files: ds-1col--node-article-full.tpl.php \< ds-1col--node-article.tpl.php \< ds-1col--node-full.tpl.php \< ds-1col--node.tpl.php \< ds-1col.tpl.php

```
theme_hook_suggestions (Array, 9 elements)
0 (String, 13 characters ) node__article
1 (String, 11 characters ) node__59325
2 (String, 31 characters ) ds_1col__node_article_cartoline
3 (String, 31 characters ) ds_1col__node_article_cartoline
4 (String, 7 characters ) ds_1col
5 (String, 13 characters ) ds_1col__node
6 (String, 18 characters ) ds_1col__node_full
7 (String, 21 characters ) ds_1col__node_article
8 (String, 26 characters ) ds_1col__node_article_full

```

Note that element nr 2 is my suggestion, so my function is correct. (items 2 and 3 are identical because I have tried to insert the same template function code in a module function code to see if there was some type of problem with my templates).

Why my file (ds\_1col\__node\_article\_cartoline -\> ds-1col--node-article-cartoline.tpl.php) in my "templates" directory in my theme is not used ? If I write a simple ds-1col.tpl.php in my "templates" directory file this file is used.

I have tried to change one of my module "weight" from 0 to 2 or from 0 to -1 (ds weight is 1) but without luck.

Where is the problem ?

Thanks.

# Answer
> 0 votes
I have 3 suggestions:

1. Might just be a typo on your behalf but the tpl file should be ds-1col--node-article-cartoline.tpl.php rather than ds-1col--node-article-immagini.tpl.php
2. Could it be that because you've specified ds\_1col it's being affected by display suite's naming convention, try using your theme name instead.
3. There is some sort of inheritance that can be hard to spot, for example to override node--article.tpl.php you need node.tpl.php present in your theme

---
Tags: 7, display-suite, theming
---


title: change time field to select list

text:
# Question
Title: change time field to select list
I am using a date field in a content type. I want to make it work similar to the date/time input in facebook events. When I use date field as a Pop-up calendar it appears like this:

For *date input* it is fine as it is – but for the *time imput* I would prefer to have a drop down field (select list) with the *date input* as pop-up calender here. When I try this...

```
$dropdown_time_array = array('12:00 pm','12:15 pm','12:30 pm','12:45 pm', );
if($form_id == $form_id_node){
$form['field_date'] = array(
     '#type' => 'select',
     '#default_value' => '1',
     '#options' => $dropdown_time_array,
  );
}

```

…it actually overrides the whole field – including the *date input*.

Any suggestions how I can do this?

# Answer
You can tell the Pop-up date widget to use wvega-timepicker depending whether you're using a Date field or custom module there are different ways of using it.
> 1 votes

# Answer
What I would do to find out what you need to type is to insert a debug statement.

Enable the devel module and then just before the code you have added above add in dpm($form);

This will show you the structure of the array. You will need to change your code to something like this, but please don't just copy what I did, it's not exactly right - get the actual name of the sub-field from looking at the array (if you are not sure, post your debug output).

```
$form['field_date']['time'] = array(

```

Once you have the answer, of course you remove the debug code and turn of devel again.
> 0 votes

---
Tags: datetime
---


# Question
Title: implementing user has password in hook menu
we are implementing a web service for a Drupal 7 site (the web service code is not part of drupal installation folder).

one of the web services needs to sign up the user on the site. the main hurdle was getting a hashed password that Drupal will also recognize.

for that , am following a suggestion made on stack overflow to Implement a REST service inside drupal and call that from the outside service code . (that part also seems possible and achieveable).

have implemented a password hashing service with following code:

```
function GetHashedPassword($string)
{
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

    $hashedpw = user_hash_password($string);

    $data = array(
        'password' => $hashedpw
    );

    header("Access-Control-Allow-Origin: *");

    drupal_json_output($data);
    drupal_exit();
}

```

the main issue now is that whenever this service is called even with same string , it returns a new hashed value each time..

kindly assist if what we need is actually even possible and if so, then what could be fixed in the above code

any help appreciated

# Answer
If you check the functions being called, you'll there's a randomness in generating the hash for security reasons. I think that is not a problem. Have you tried using that as the stored password and logging in afterwards?
> 0 votes

---
Tags: 7
---


# Question
Title: Image style don't create thumb image and it get error "Division by zero"
My site is Drupal 7.36

Image style cann't create all images and it get 2 error messages

> Division by zero in theme\_image\_style\_preview() (line 804 of /Users/snappy/Sites/betterpack/modules/image/image.admin.inc)
>
> array\_intersect\_key(): Argument #1 is not an array in theme\_image\_style\_preview() (line 806 of /Users/snappy/Sites/betterpack/modules/image/image.admin.inc)

and I did:

> sudo chmod -R 777 sites/default/files/styles

It not work

Help me please.

Thank you everyone and sorry I write weak in English but I can read good English.

## ls command in sites/default/files/styles

> ls -l
>
> total 0
>
> drwxrwxrwx 3 \_www staff 102 Jun 7 2014 cover\_article
>
> drwxrwxrwx 3 \_www staff 102 Mar 28 19:47 cover\_product
>
> drwxrwxrwx 3 \_www staff 102 May 9 2014 large
>
> drwxrwxrwx 3 \_www staff 102 Jun 5 2014 medium
>
> drwxrwxrwx 3 \_www staff 102 Jun 6 2014 node\_porduct
>
> drwxrwxrwx 3 \_www staff 102 Jun 6 2014 related\_product
>
> drwxrwxrwx 3 \_www staff 102 Jun 7 2014 thumb\_gallery\_article
>
> drwxrwxrwx 3 \_www staff 102 May 9 2014 thumbnail

# Answer
> 0 votes
It would appear that your image toolkit is not working properly. On the status page (admin/reports/status) are there any errors, etc.?

---
Tags: media
---


# Question
Title: Maisystem module not saving my custom class on production server
I have an issue with Mailsystem. I want to use the Mailjet module to send my emails, and the HTMLmail module to format them. I did it on my development server and it worked fine. I did the following : On Mailjet administration page : admin/config/system/mailsystem New class : Class to use for the format() method \>\> Htmlmail Class to use for the mail() method \>\> MailjetSmtpMailSystem Then i saved the configuration, and in "Site-wde default MailSystemInterface", the new class showed up : HTMLMailSystem\__MailjetSmtpMailSystem.

Then i tried to do it on my production server. It doesn't work. When i try to create a new class and hit "save" the new class is not saved. I found the following error in my logs : The specified file temporary://files5RLHj could not be copied to sites/default/files/mailsystem/HTMLMailSystem\__MailjetSmtpMailSystem.mail.inc.

So of course i checked the rights. I do have all the rights on the files folder and on the mailsystem folder. I also have the rights on the tmp folder.

I checked with my ISP and he said he tried everything too and doesn't know what he can do.

I tried to copy manually the temporary file to its destination, but Mailsystem doesn't seem to realize it's there.

Please, tell me you have an idea where this problem comes from.

Thank you

# Answer
http://php.net/manual/en/features.safe-mode.php notes

> This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

So in general it is not very useful feature and turns out to be causing issues with some applications when they try to write to the file system.
> 1 votes

# Answer
Well my ISP finally found the origin of the problem. They disabled PHP safe mode and it worked. Of course once the file is created we can enable safe mode again. It's a bit tedious to do this each time we want to change the Mailsystem configuration, but at least it works. FYI we are still on PHP 5.3 so probably this problem doesn't occur on higher versions, or else i would have found someone who encountered the same problem.
> 0 votes

---
Tags: emails
---


# Question
Title: Adding a "three line" character (☰) or image to TB Mega Menu dropdown button
I'm currently developing a website with TB Mega Menu using a Zen subtheme. The problem is that the default TB Mega Menu button (the one that replaces the 'normal' horizontal menu on smaller screens) is just an empty white button without any signs. I want to make it more understandable for users by adding an industry-standart "three line" character (☰) or an image. Does anyone know how this can be done?

# Answer
> 3 votes
element:before {content: "☰";} should do the trick. I'm seeing some other problem in there actually. The presence of `<i></i>` element means there should be a font icon on load, with the i:before reacting as your three bars. Sirate theme, for example, doesn't have it, so it has to be a bug.

Could you provide a live site so we could give you a solution based on it? TB Megamenu could be different as markup depending on the theme. Or your CSS could be changed, based on some Zen stuff.

---
Tags: routes, theming, navigation
---


title: Custom views query - pager dosn't work

text:
# Question
Title: Custom views query - pager dosn't work
I am trying to modify view query, basically I build my custom query and assigned it to:

```
$view->build_info['query'] = $query;
$view->build_info['count_query'] = $query;

```

everything has been done in hook\_views\_pre\_execute. I tried to do the same in hook\_views\_query\_alter but I wasn't able to construct more complex where clause.

Everything works fine apart from a pager. I noticed that I get pager but main query is not modified with LIMIT option so when I click on particular number of pager my result has not being updated. Below is a query which I need:

```
SELECT DISTINCT
  dat.field_date_and_time_value AS field_date_and_time_value,
  n.created AS created,
  n.nid AS nid FROM node n
LEFT OUTER JOIN og_membership pb
ON n.nid = pb.etid
AND pb.entity_type = :entity_type
LEFT OUTER JOIN field_data_field_date_and_time dat
ON n.nid = dat.entity_id
AND (dat.entity_type = :entity_type AND dat.deleted = :deleted)
LEFT OUTER JOIN field_data_field_og_public_to pt
ON n.nid = pt.entity_id
AND (pt.entity_type = :entity_type AND pt.deleted = :deleted) WHERE
(n.type = :db_condition_placeholder_0)
AND
(n.status = :db_condition_placeholder_1)
AND
(dat.field_date_and_time_value >= NOW())
AND
(
    (pb.gid = :db_condition_placeholder_2)
    OR
    (pt.field_og_public_to_target_id = :db_condition_placeholder_3)
    OR
    (
        (pt.field_og_public_to_target_id = :db_condition_placeholder_4)
        AND
        (pb.gid IS NULL )
    )
)
ORDER BY dat.field_date_and_time_value ASC, n.created DESC

```

I created it like that:

```
$query = db_select('node', 'n');
$query->distinct();
$query->fields('dat', array('field_date_and_time_value'));
$query->fields('n', array('created', 'nid'));
$query->leftJoin('og_membership', 'pb', 'n.nid = pb.etid AND pb.entity_type = :entity_type', array(':entity_type' => 'node'));
$query->leftJoin('field_data_field_date_and_time', 'dat', 'n.nid = dat.entity_id AND (dat.entity_type = :entity_type AND dat.deleted = :deleted)', array(':entity_type' => 'node', ':deleted' => '0'));
$query->leftJoin('field_data_field_og_public_to', 'pt', 'n.nid = pt.entity_id AND (pt.entity_type = :entity_type AND pt.deleted = :deleted)', array(':entity_type' => 'node', ':deleted' => '0'));

$query->condition('n.type', $view->argument['type']->argument);
$query->condition('n.status', $view->filter['status']->value);
$query->where('dat.field_date_and_time_value >= NOW()');
$subcondition = db_or()
->condition('pb.gid', $view->argument['gid']->argument)
->condition('pt.field_og_public_to_target_id', $view->argument['gid']->argument)
->condition(db_and()->condition('pt.field_og_public_to_target_id', $view->argument['gid']->argument)->isNull('pb.gid'));
$query->condition($subcondition);

$query->orderBy('dat.field_date_and_time_value', 'ASC');
$query->orderBy('n.created', 'DESC');

```

Any idea why pager doesn't work?

# Answer
> 1 votes
Ok, I resolved the issue with the **hook\_views\_query\_alter** using **add\_where\_expression** method. It allows you to create complex where conditions. Below is example

```
// Delete current where conditions created by view and replace it by custom ones.
unset($query->where);
$query->add_where_expression(0,'node.type = :node_type', array(':node_type' => $node_type));
$query->add_where_expression(0,'node.status = :node_status', array(':node_status' => $node_status));
$query->add_where_expression(0,"(CASE node.type WHEN 'event' THEN field_data_field_date_and_time.field_date_and_time_value WHEN 'training_course' THEN field_data_field_date_and_time.field_date_and_time_value ELSE NOW() END) >= NOW()");

$or_conditions = array();

$or_conditions[] = '(og_membership.gid = :public_by_gid)';
$or_conditions[] = '(field_data_field_og_public_to.field_og_public_to_target_id = :public_to_gid)';
$or_conditions[] = '((field_data_field_og_public_to.field_og_public_to_target_id = :public_to_gid) AND (og_membership.gid IS NULL))';

$or_condition = implode(' OR ', $or_conditions);

$query->add_where_expression(0, $or_condition, array(':public_by_gid' => $public_by_gid, ':public_to_gid' => $public_to_gid));

```

I hope it was useful for someone.

---
Tags: views, database
---


# Question
Title: Change Add To Cart To Buy Now drupal Commerce
Hello currently I am making a online e store using drupal Commerce so i want to change add to cart button to Buy Now So Ho Can I able To Do Help It Out

# Answer
> 2 votes
If you want to alter the text for a particular form you can alter it using `hook_form_alter`

Get the ID of the form for the product display where you are trying to change the text & do something like this:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id){//replace your module name with MYMODULE
  if(strpos($form_id, 'commerce-cart-add-to-cart-form-65') !== false){//my form ID is "commerce-cart-add-to-cart-form-65", replace it with your form ID.
    $form['submit']['#value'] = t('Buy Now');//Put the text which you want to make appear instead of "Add to cart".
  }
}

```

You could also use String Overrides Module to achieve the same.

---
Tags: commerce
---


# Question
Title: displaying content using entityfieldquery
I want to display content based on term ids using below method.If I include the below code in for loop it works but thats not appropriate way to call loop for each index value.Here `$all_children[]` contains term ids. Can anyone please tell me what is wrong with below code , or any suggestions?

```
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'escorts_product');
$query->propertyCondition('status', 1);
for($i=0;$i<=20;$i++)
  {
   $query->fieldCondition('field_product_sub_cat', 'tid', $all_children[$i],'=');
  }
$result = $query->execute();
if (isset($result['node']))
  {
    print "nomeer";
    $nids =  array_keys($result['node']);
    nodes = node_load(array_keys($result['node']));
    if ((node_load($nids, NULL, TRUE)))
      {
       foreach($nids as $nid)
         {
          //content
         }
      }
   }

```

# Answer
I think this is the right way because it works for me. Error was in below line.

```
$query->fieldCondition('field_product_sub_cat', 'tid', $all_children[$i],'=');

```

Correct way to compare with `array` is:

```
 $query->fieldCondition('field_product_sub_cat', 'tid', array("$your_array_variable"));

```
> 0 votes

---
Tags: database
---


# Question
Title: How to access a contributed module Information from drupal.org
1. Is there any API to access Information about a contributed module from drupal.org site?
2. How does Update Manager access information from drupal.org?

By finding this I think I too could access other data similarly and I also need **Hook API documents** to be accessed from drupal.org in my site.

*Did anyone do this before? If so please guide me.*

# Answer
> 3 votes
An update URL is formatted as:

```
http://updates.drupal.org/release-history/[project-name]/[api-version]

```

So for Views v7, for example, that would be:

```
http://updates.drupal.org/release-history/views/7.x

```

I think that's as much information as Drupal.org makes available about modules via its API. You won't find a structured way to query information about hooks, for the same reasons we talked about in your similar recent question

---
Tags: 7, community-official-site
---


# Question
Title: 'block/plugin' show a selected node. When editing the available nodes are filtered by type (or views)
There is a way to put a 'block/plugin' in a panel which, when edited by an admin, would have a list (using views if possible) of nodes to choose?

The idea is to place this 'block/plugin' in a pane of 'services', for example, and allow the admin to easily change the viewed 'node of type services' in a easy list. Something like node\_pane, but not exactly the same.

With this I can say something like 'here will be a highlighted news, there will be 3 highlighted services' and so on.

Thanks in advance =)

# Answer
Ok, isn't exactly what I was looking for, but does the job. I created a content "News Holder", then added a field using entity reference and multiple selects. This field I set to have the number of "News Content" that I want and them a just need to place this content (used panels in this case). This field can be configured to show a list (select list) of entities that the entity reference can reference.

So, using this way the user with admin privileges viewing the page can click the cog icon and edit, to edit this node. In the edit page he have direct access to the selects of the news content. It's direct and easy to use.

If someone still manage to do something similar or better, I would love to read =)
> 0 votes

---
Tags: 7, panels
---


# Question
Title: Can I make Text Field accept filtered_html?
I have a content type where a field is the common name for a USA president. In examing a legacy database I'm importing some presidents have (simple) HTML in their name. For example `Dwight Eisenhower <i>Ike</i>`.

I would like to support this on a content type field `field_people_common_name` which is a `textfield` created in the Field UI.

Following these directions:

I've created a simple form alter hook to allow the input format of `filtered_html` on this form element:

```
function prez_people_form_people_node_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
  $form['field_people_common_name']['und'][0]['value']['#type'] = 'text_format';
  $form['field_people_common_name']['und'][0]['value']['#base_type'] = 'textfield';
  $form['field_people_common_name']['und'][0]['value']['#format'] = 'filtered_html';
  $form['field_people_common_name']['und'][0]['value']['#settings'] = array('text_processing ' => '1');
}

```

This appears to well, work or function:

But upon previewing the edit I get these errors:

```
Warning: mb_strlen() expects parameter 1 to be string, array given in drupal_strlen() (line 482 of ../htdocs/includes/unicode.inc).

Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1583 of ../htdocs/includes/bootstrap.inc).

Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1583 of ../htdocs/includes/bootstrap.inc).

```

Any idea how to get this to work. I'm trying to avoid embedding a `text_area` for simple textfield value (a name will **never** require a massive textarea .... yes I know I could make the textarea 1 row tall ....)

# Answer
You shouldn't need to use hook\_form\_alter to allow the user to specify an input format for a textfield. On the content type page, you can edit a fields settings and there is an option titled "Text Processing" that you will want to use instead.

Then when I look at my node form I see the following:
> 4 votes

---
Tags: entities, input-formats
---