# Question
Title: Getting information from database and giving it to javascript
The main thing I want to achieve is that my module makes a google map with markers.

For now im doing this:

```
drupal_add_js('https://maps.googleapis.com/maps/api/js?key=AIzaSyDcl28Qcn9GTi02rRtQaLgVS4GWZbGcQ8E', 'external');

$locations = db_query('SELECT * FROM {locations}')->execute();

$script = '<script>
     function initialize() {

    var mapOptions = {
      center: { lat: 56.9714744, lng: 24.1291624},
      zoom: 9
    };
    var map = new google.maps.Map(document.getElementById(\'map-canvas\'),
        mapOptions);

    var locations = [';

    for($i = 0; $i < $locations->length;$i++){
        $string = '['.$locations[$i]['locationsTitle'].','.$locations[$i]['locationsLat'].','.$locations[$i]['locationLng'].'],';
        $script = $script.$string;
    }

    $script = $script.'];
    for (var i = 0; i < locations.length; i++) {

      var loc = new google.maps.LatLng(locations[i][1], locations[i][2]);

      var marker = new google.maps.Marker({
        position: loc,
        map: map,
        title: locations[i][0]
      });
    };

  }

  google.maps.event.addDomListener(window, \'load\', initialize);

</script>
';

$html = '
<div id="map-wrapper" style="width:100%;height:500px;margin:auto">
    <ul id="map-list"></ul>
    <div id="map-canvas" style="width:100%;height:100%;margin:auto></div>
</div>
';

return array('#markup' => $script.$html);

```

As you can see in the third line of code im trying to get information from the database that I have saved. The problem is I dont know how would i get it properly. And then I want to pass it down in the var locations part in the script..

I have tried finding some tutorials where they explain how would this work but most of them is just how to show some posts or somthing like that and that doesnt help me.

Thanks for help already! :)

// EDIT

This is the script that i have now in js file

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

          function initialize() {

          var mapOptions = {
             center: { lat: 56.9714744, lng: 24.1291624},
             zoom: 9
          };
          var map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);

    var locations = [
                    ['Mājas',56.956344, 24.197409],
                    ['Domina',56.966058, 24.162004]
                    ];

    for (var i = 0; i < locations.length; i++) {

      var loc = new google.maps.LatLng(locations[i][1], locations[i][2]);

      var marker = new google.maps.Marker({
        position: loc,
        map: map,
        title: locations[i][0]
      });
    };

  }

  //google.maps.event.addDomListener(window, 'load', initialize);

}

```

} )(jQuery);

I have the "google.maps.event.addDomListener(window, 'load', initialize);" commented becouse I think i dont need it..? And becouse there is no function initialize anymore? Or should i add that back?

The problem now is that my script seems to be added.. But it doesnt seem to be run becouse the google map dosnt show up..

# Answer
> 1 votes
You should never need to build javascript with PHP, there's just no need (especially in Drupal, which already has a mechanism).

What you should do instead is put your JS in an external file, then use Drupal's JS settings to pass the data. So the JS file might look like:

```
(function($) {
  Drupal.behaviors.myModule = {
    attach: function(context, settings) {
      var locations = Drupal.settings.myModule.locations;
      // Do something with the locations var.
    }
  }
)(jQuery);

```

And in your page callback or whatever:

```
$settings['myModule']['location'] = db_query('SELECT * FROM {locations}')->fetchAll();
drupal_add_js($settings, 'setting');

```

---
Tags: database
---


# Question
Title: Custom Field Type is missing in Feeds Importer
I've got a problem with feeds importer. I've created a custom field type, and added a field with this field type to my content. If I try to import data via feeds importer, in mapping, this field is missing. Do I have to tell my custom field type that it is useable within feeds-importer?

# Answer
> 0 votes
You might need to create a target for your custom field type with the help of hook\_feeds\_processor\_targets\_alter and here is a code sample for doing so:

```
<?php
function MYMODULE_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name)
{
    foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance)
    {
        $info = field_info_field($name);
        unset($callback);
        if ($info['type']=='MYFIELDTYPE1')
        {
            //The callback for this field type goes here.
            $callback = 'TARGET_SETTER_FOR_MYFIELDTYPE1';
        }

        if ($info['type']=='MYFIELDTYPE2')
        {
            //The callback for this field type goes here.
            $callback = 'TARGET_SETTER_FOR_MYFIELDTYPE2';
        }
        //Add cases for each field type here
        //...

        if (isset($callback))
        {
            $targets[$name] =array(
                'name'=>check_plain($instance['label']),
                'callback' => $callback,
                'description' => t('The @label field of the node.', array('@label' => $instance['label'])),
            );
        }
    }
}
?>

```

---
Tags: entities, importing-exporting
---


title: Admin Menu Extra Items and Errors

text:
# Question
Title: Admin Menu Extra Items and Errors
Not quite sure how to explain this, but I will go through what I did, and when the errors started happening.

I have enabled the default taxonomy view in Views, changed it to fields, and added a grouped filter.

After saving, I see the error `"Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain() (line 1583 .../html/includes/bootstrap.inc)."` AND suddenly the admin menu has loads of new items in it?

I read up on it, but cant see any fixes, so try disabling and re-enabling the taxonomy view, and also admin menu.

Now the error message has gone, everything works fine, but I am left with all of these extra menu items in the admin menu.

I have logged in as other lower level users, and their admin menus are fine, yet as the super user (with all permissions) I have about 20 or 30 menu items added to the menu before the usual entries.

I have no idea where to start looking with this. The error above seems to happen when a module passes an array through check\_plain(), so it usually a module error rather than core. But in this case, it seems to be the taxonomy view that has triggered it, unless its a coincidence.

Can anyone offer guidance?

**EDIT:** Also tried flushing cache. And worst comes to worse can revert to a backup 5 days ago, but will lose a fair bit of content, so want to avoid this.

**EDIT**: Looking phpmyadmin, I can see that all of these new menu items have indeed been added to the menu\_links table, but do not appear in the structure \> menus \> management list.

# Answer
> 0 votes
Reverting the taxonomy view back to its original state, and then rebuilding the changes again made the errors disappear from watchdog, but the management menu and admin menu were still completely messed up.

To fix this, I installed Devel module, and the ran a SQL query to delete all menu rows added by system.

```
mysql> delete from menu_links where module='system';

```

I then navigated to `/devel/menu/reset`

This successfully re-built the management menu, and everything went back to normal.

Note: I also used backup and migrate to quickly clone the website onto a local server and test the changes before making the changes on the production environment.

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


# Question
Title: Add product fields to cart form through line items
So I have a Product field called "Quantity Per Box". It's a field that says how many items (in this case, screws, nuts, and bolts) come in each box. I want to display this number in the view when the customer goes to cart.

I have the field as part of the product already. What I have done so far is added the existing field to line items, and checked the box to add that field to the cart. Then I edited the view to add that item. The label shows up "Quantity Per Box" but there is no value in the field from the product. I've tried this several different ways with no success. Can someone help me out here, what am I missing?

# Answer
> 0 votes
To be absolutely clear, you want the "Quantity Per Box" field present on product entities to display on the cart view? For that you'll need to add I believe the "Commerce Line Item: Referenced Products" relationship in the view. That should give you access to the product fields, with no need to copy a field from product entities to line item entities.

Since the cart is a Commerce Order view: Relationships needed to reach products can be visualized as: **commerce\_order**-\>**commerce\_line\_items**-\>**commerce\_product**

---
Tags: views, commerce
---


title: How to remove Taxonomy term Title

text:
# Question
Title: How to remove Taxonomy term Title
Can anyone please guide me how to remove the title of the Taxonomy terms.

I would like to give the title along with the description so i want to remove the default title.

Thanks for your help

# Answer
> 1 votes
If I understand your question correctly, I think you need the Auto Entity Label module. Using this module, you can automatically generate labels by a given pattern for the taxonomy term names.

---
Tags: taxonomy-terms
---


# Question
Title: Different checkout form based on user or role
As described, in the docs Checkout Form Builder. This is how you modify the checkout flow. Is it possible to have different checkout flows based on role or user?

For example;

* If a teller is logged in. There is no need to collect show account information, or billing.
* If a customer is logged in. It will display those panes.

# Answer
i think something along the lines of this should work. If you have a whole load of these I'd put them in custom module. Otherwise template.php

```
/***
* Implements hook_form_FORM_ID_alter
*/

function myform_form_theformid_form_alter(&$form, &$form_state, $form_id){
  global $user;
  if (in_array('teller', $user->roles)) {
  unset($form['account_information']);
  }
 }

```
> 1 votes

# Answer
Probably by implementing hook\_form\_alter(), you could check for the currently logged-in user's role and make form changes depending on what role.
> 0 votes

---
Tags: 7, commerce
---


# Question
Title: How do I modify the "view" link in a view?
I'm sure this is a simple question when you know what you're doing, but I'm a bit puzzled.

At the moment, I have a view, from the views module, listing published articles on the front page of my site. After each article, there is a link "view" or "voir" (depending on the language being used) which takes you to the article. This is simply an anchor tag generated by thte Views module containing a link to the article node appended to the end of the item.

However, the person for whom I am making the site wants this link to be styled in a specific way, with an icon and the text to read "Read more" or "Savoir plus". How or where can I modify the HTML markup and text content for this particular element of the View module output?

# Answer
In the 'Add fields' on your View, you can select 'Content: Link', which generates a simple link to your content. When configuring this 'field' you can set the 'Text to display' property and under 'Style settings' specify any CSS classes you want (see screenshot below).
> 2 votes

---
Tags: 7, views
---


# Question
Title: Commerce Allows User to Edit Cart After Completion of Checkout
I recently found a problem where a customer can edit their cart and re-checkout after checkout has been completed and payment has been made. This results in a single order record (the latter one) and two payments.

Re-creation of this issue: 1. Start a cart 2. Open the cart in a second window (You should have two windows/tabs open with the same cart) 3. Checkout on the first screen 4. Once checkout is completed and payment has been made, remove or update an item in your cart using the second screen

This places the cart back in a Shopping Cart status (per Drupal Commerce rules) and you have the same order/cart number since they share a table (which is another problem for another day). You can now checkout again and you will have two order confirmation emails with the same order number. Drupal Commerce will show only one order (the second order) but two payments. There is no way to recover the first order.

This only happens when the customer leaves the shopping cart open in multiple window(s) and tries to edit it after checkout.

Is there a fix to dis-allow editing of a cart after it changes over to an order? I would like it to throw an error and force a refresh of the page causing it to create a new shopping cart.

# Answer
> 0 votes
Hmmm, this is definitely something that deserves to be fixed in Commerce itself. I'm going to open an issue there and outline a strategy that essentially adds a form alter hook to the Cart module to redirect back to /cart in the event that the shopping cart form is being built / submitted for an order that is in an unsupported status. I can't say exactly how I'd do it yet, but I suppose it would involve iterating through the checkout pages to allow shopping cart form submissions for any order that hasn't yet passed a checkout page that doesn't have back buttons (e.g. the Payment and Completed pages).

---
Tags: commerce
---


# Question
Title: Form inputs being disabed during the Ajax request
I'm working on a module where I have a *form* inside of a *block*, I'm using `Ajax` to submit the form, but I noticed that the form's inputs are disabled when sending a request with Ajax. Well in my case I want to keep using the form's input (keyup event) and displaying the result for each request.

```
// my current code
$form['combine'] = array(
    '#type'       => 'textfield',
    '#size'       => 255,
    '#maxlength'  => 128,
    '#attributes' => array('placeholder' => 'Search'),
    '#ajax'     => array(
        'callback'  => 'ajax_filter_callback',
        'effect'    => 'fade',
        'wrapper'   => 'result-content',
        'event'     => 'keyup',
    ),
);

```

# Answer
That functionality is built-in so you'll need to monkey-patch `Drupal.ajax.prototype.beforeSend` (found in misc/ajax.js).

Copy the entire code, but remove/modify this line:

```
$(this.element).addClass('progress-disabled').attr('disabled', true);

```

So in your module or theme's JS file:

```
Drupal.ajax.prototype.beforeSend = function(xmlhttprequest, options) {
  // Place all code from the original function here, except the line above.
}

```

YMMV, you may unwittingly introduce unexpected behaviour by not waiting for each request to complete.
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: Moving or creating many product variations
Problem:
many, many product variations. Think of it as a product configuration tool to customize your item.

I tried this: https://www.drupal.org/project/commerce\_bpc

It did create variations, however there seems to be some issue where they exist only as variations, they don't get attached to a product (if that makes sense). Basically, I can only see them under the admin list of variations.

Question 1: What's the most effective way to auto-generate many variations of a product?

Question 2: Can I somehow attach these variations to a product now that they're generated? Happy to do this directly in the database and/or create a standalone script to do so.

I may very well be missing something obvious, this "many variations" problem must be quite common.

# Answer
# Question 1:

until some awesome person posts a different answer, I'm afraid the answer to this is to use "commerce\_bpc" to generate all your variations, and then attach your variations to the product by writing a standalone script. See below.

# Question 2:

you can attach variations to a product after they've been created with "commerce\_bpc".

field\_data\_field\_product is the table that links variations to products.

Adding new rows where "field\_product\_product\_id" is the variation you want to attach to a product will attach the variation to the product.

also, add the same row to: field\_revision\_field\_product and clear cache.
> 0 votes

---
Tags: 7, commerce
---


title: Scope javascripts to be outside admin

text:
# Question
Title: Scope javascripts to be outside admin
Now when we are almost there using purely YML files to include JavaScript, is it possible to include javascripts everywhere except for in the Drupal administration? Beta 4 does not allow the #attached property anymore, so this solution would be best suited in a YML setup.

# Answer
> 5 votes
Sure. Drupal 8 still allows #attached, the difference is just that you specify a library instead of a specific javascript file, but that is irrelevant for your question.

You can implement hook\_page\_attachments() and ask the route context if this is an admin route.

```
/**
 * Implements hook_page_attachments().
 */
function yourmodule_page_attachments(&$page) {
  // This returns TRUE for admin paths.
  if (!\Drupal::service('router.admin_context')->isAdminRoute()) {
    $page['#attached']['library'][] = 'yourmodule/yourlibrary';
  }
}

```

---
Tags: javascript, 8
---


# Question
Title: display suite: limit field - determine what bundle values?
In display suite, there's a field to limit which bundle it's being displayed on.

How do you know what bundle / value to enter?

Is there a way to list all available values or find out all the values? Or does it go by the machine name?

# Answer
> 5 votes
It's the machine name. You can think of the bundle as the specific settings for a specific entity. So, DS is asking you for the machine name associated with the individual content type, vocabulary, etc. that you'd like to target.

For example, say you've created node configurations (Structure \> Content Types) called "Article," "Store Location," and "Job Openings." If you'd like to make your DS custom code only available in the display settings for "Job Openings," you'd put in...

```
job_openings|*

```

...or you could limit it to a specific view mode by specifying which one in place of that wildcard, such as...

```
job_openings|teaser

```

Easiest way to find the machine name is to look at the edit url for your entity and/or view mode.

# Answer
> 0 votes
The following is hard to find: If you need to limit the field to a DS view you need to use the following syntax on the "Limit field" field in the field configuration:

```
products-page|default

```

Where "products" is the name of the view and "page" is the display name.

---
Tags: display-suite
---


# Question
Title: Views Exposed Filter Form Submit handler
I have a Views with an exposed filter block and put the block on the front page.

I use the following code to add a custom submit handler.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'views_exposed_form' )
  {
    array_unshift($form['#submit'], 'manage_custom_filters');
  }
}

function manage_custom_filters($form, &$form_state) {
 dpm($form['#id']);  // output views name
}

```

Here is the question, whenever i load the front page, the manage\_custom\_filters get called, i suppose it will be called only when i submit the exposed filter form?

I did the same thing for node form submit, it does not behave like the views exposed filter form. manage\_custom\_filters only get called when i submit the form.

Is this the correct behavior of views exposed filter form?

How do i differentiate the manage\_custom\_filters is get called by 'on load' or submit action?

# Answer
The views exposed form will be submitted every time you view it. If you check the `render_exposed_form()` you can see they are setting the `$form_state['always_process'] => TRUE`, this means that the form will be submitted always while processing it. And this is understanable because submitting the exposed form and passing the argument in `$GET` are the same in view.
> 3 votes

# Answer
As stated above, the form is submitted as soon as you load a page. You have a couple of workarounds here:

1. If you are using Ajax, you could add a custom JavaScript function only fired on submit (so when you load the page it won't occur). Something like this:

```
Drupal.behaviors.mymoduleAjaxView = {
  attach: function(context, settings) {
    this.form.submit = customFunction();
    function customFunction() {
        alert('Fired when form is submitted');
    }
}};

```
2. If you don't wish / have to use JavaScript, you could check for a field in your form that, on page load has no value (is empty) but when submitted by a human has a value. E.g.

```
function manage_custom_filters($form, &$form_state) {
    if(!empty($form_state['values']['field_name_here']) {
      // Form was human submitted.
    }
}

```

Compare $form\_state when the page loads and when you submit the form, to spot this. I know that probably this is not the ideal way, but it has worked for me.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How to login to my site again after all users were deleted?
I was inside `/admin` on my site looking at users. I noticed a lot of what looked like robot made users and I decided to delete them. I clicked the box for delete all on this page. What happened then is that all users were deleted and now I cannot login at all.

All clients linked with whitelabel show error message.

What can I do?

# Answer
> 5 votes
If you have backups then restore from backup then delete users again without deleting the ones you want to keep.

If you don't have a backup then you will need at least user 0 (anonymous) and user 1 (superuser).

I am assuming Drupal 7 because you didn't specify version.

You will have to add those back into the database either via database access in your hosting administration area or from the command line.

Note: I am adding the basic MySQL queries here but you should read these whole linked pages for more information.

The process is similar for both users. You should read Restore user 0 for more detailed information but here are the SQL queries:

**User 0 (anonymous):**

```
INSERT INTO users (name, pass, mail, theme, signature, language, init, timezone) VALUES ('', '', '', '', '', '', '', '');
UPDATE users SET uid = 1 WHERE name = '';

```

**User 1 (superuser):** You can change "admin to whatever user name you want to use. I recommend not using "admin" because attackers will try that first if trying to work out your password.

```
INSERT INTO users (name, pass, mail, theme, signature, language, init, timezone) VALUES ('admin', '', 'youremail@example.com', '', '', '', 'youremail@example.com', '');
UPDATE users SET uid = 0 WHERE name = 'admin';

```

Then you will need to do a password reset for the user 1 account.

**Other users** Other users can be added just with the first insert statement without the update statement after however you will lose settings like user picture, signature etc. if there is data in those fields (or unless you know what the data should be and ad it back in).

Those users would also not get roles so you would have to assign roles to them after.

They also wouldn't have the same UID as before so in the uncommon case that you have code that specifically references a user ID that will need consideration.

**Note** that some modules that change the behavior of Drupal users may change the way you need to add these users back.

For example if you user the "User revisions" module then there is also a user\_revision database table that needs to be considered when doing these queries.

---
Tags: users
---


# Question
Title: How to print parent taxonomy term name in a block?
Using Drupal 7, I want to create a simple block that will be on all taxonomy term pages that will show the first parent of the current term (there will be a tree of parents, but I want just the next highest).

The below code works to pull the current term name, but I'm unsure how to go about pulling the parent term of this term page.

```
$current = taxonomy_term_load(arg(2));
if ($current):
echo $current->name;
endif;

```

Any suggestions?

# Answer
> 2 votes
I had to create a new question to get the answer (PHP is not my strong point).

$parent is actually an array, so it's output is a little different. There's likely many ways of doing it, but

```
echo reset($parent)->name;

```

worked for me.

# Answer
> 1 votes
You get the parent term with taxonomy\_get\_parents($tid). So you can just add:

```
$parent = taxonomy_get_parents($current->tid);
if ($parent){
  echo $parent->name;
}

```

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


# Question
Title: Entity Reference create problem with REST server using Services
i'm building a web services and now i'm writing the documentation for the mobile developer.

When i want to create/modify an entity reference Services 3 ask a stucture like this

```
"field_organization": {
    "und":[{
        "target_id":"Organization name (69)"
    }]
  }

```

for a field like this

but, there is another way to give only the nid without the node title? It could be more handy.

I read something like

```
"field_organization":[{
     "target_id":{
                "target_id":"[nid:69]"
          }
   }]

```

or like

```
   "field_organization": {
       "und":[{
             "target_id":{
                 "target_id":"[nid:69]"
               }
           }]
     }

```

on the official documentation but it didn't work.

Can someone know a method to give only the nid of a Entity reference field?

# Answer
I found the solution! The required data structure depends on the input widget, since Services uses the form submit handlers (which may be a major design flaw). For "Autocomplete/Tagging" the `label (id)` thingy is necessary. But if you switch to checkboxes it reads `"field_reference": { 1:1, 2:2, ... ,nid:nid}` and for select box `"field_reference": [1,2,3 ... nid]`.

The REST-API depends on the widgets the frontend uses ... but at least it works. I guess its upside is that REST-posts are validated just as normal form inputs are. I'll also have a look at the approach implemented http://drupal.org/project/restws
> 4 votes

# Answer
I tried Philipp's way but no luck. In my case (widget type is select and services-7.x-3.3)

```
    "field_reference": {"und": "977"}

```

works. Where 977 is a nid.
> 2 votes

# Answer
I was using select list as a widget in order to get the service working but due to a big number of nodes being referenced in the entity reference field (~9000) I had timeout problems. I couldn't even open the edit node form.

So, I switched to the autocomplete field which loads way faster. To overcome the 'NAME (NID)' problem I realised that the NAME part doesn't have to be the correct one. Only the NID matters. So, sendind something like 'Dummyname (123)' with 123 being the nid of a node titled 'My node' will actually save the correct reference.
> 1 votes

# Answer
I had a similar problem using an entity reference field with the checkbox/radio-button widget. Ultimately, the issue in my particular scenario was that I was using the Field Group module to hide all administrative fields on a node type (using a form alter, set access to false for all fields within a specified field group). To get the services POST working correctly, I had to take the entity reference field out of the field group. The JSON that worked after that was:

```
{
 ...

 "field_entity_ref":{"und":"nid"}

 ...
}

```
> 0 votes

---
Tags: 7, entities, services
---


# Question
Title: Views Bulk Operations Modify entity values on one form
I am trying to use VBO to update order status on entities. When using "Modify entity values" it shows 'Modify entity values' on vbo dropdown and then it redirects to a page with dropdown with all the options.

How to make it all on one form so I could check rows and then select (eg.) an order status option?

Is there any module or do I have to go programmatically through this journey?

Thanks

# Answer
Try creating a custom action in Rules that sets the entity value to the one you want rather than prompting for the value. Then activate that action in your VBO view.

You can make new rules components at `mysite/admin/config/workflow/rules/components/add`
> 1 votes

---
Tags: views
---


title: Advanced Search (Search Api Solr)

text:
# Question
Title: Advanced Search (Search Api Solr)
I'm trying to build a advanced search for a eRecruiting site build with the recruiter distribution. The Recruiter Distribution comes with 3 different search two for applicant that are What ? (Job Search) and Where (Job Location). The another one is to search for applicants. However they are a lot data on the job description and on the applicant that I wanted to used to be more specific .

For instance, the recruiters should be able to search for be able to search for the following items:

* Keyword
* Location
* Specialty
* Employment type

Currently, I have some facets that helps me to make my search more friendly. But when it comes to search many items (such as locations nationwide) it becomes to crowded.

I'm aiming for something similar to Google Advanced Search but a little bit more simpler.

According to a post Building an advanced multicriteria search one the solution to complete this job is the search api solr module. And I have this part working however he did not explain how to do it. There is another post (Create advanced search) that talks very similar of what I'm asking but nobody replay.

I try to use the Search API Combined module but to be honest is lack of documentation. And it does seem to be clear how to used this module.

What is the best approach to created an Advanced Search (multicriteria search) with search api solr ?

# Answer
> 1 votes
I found a module that allows you to this Search API multi-index search.

# Answer
> 1 votes
I built a form like this for a website. If I wanted to I'm pretty sure I could use the same principle to build a form like Google Advanced Search. Whether it's the best approach or not I'm not sure.

Which sits on the front page of the websites and then sends to the search page from there.

What I'm doing is recreating the URL thats being created on the search page. like 'search/applications?f\[0\]=field\_location%3A2439'

* I created a Custom Module
* used hook\_block\_info to create a block
* used hook\_block\_view to create a block view - assigned the form to its content
* Example of the form code -\>

```
function search_applications_form($form, &$form_state) {
$locations = db_query("SELECT tid, name FROM {taxonomy_term_data} WHERE vid     = 5")->fetchAllKeyed();  // vid will be the id of the location taxonomy data

$form['locations'] = array(
   "#type" => "select",
   '#multiple' => TRUE,
   "#title" => t(""),
   '#required' => FALSE,
   '#default_value' => 'Select Application Locations',
   '#options' => $locations,
   );
 return $form;
 }

```

And in the submit

```
function search_applications_submit($form, &$form_state) {
     global $base_url;

     $search = $form_state['values']['search_applications'];

     $i = 0;

     if($form_state['values']['locations'] != NULL && $form_state['values']['searchlocations'] != '0' && $form_state['values']['locations'] != 'none'){

     $tid = $form_state['values']['locations'];

     $addlocationsearch = '&f['.$i.']=field_job_location%3A'.$tid;
      $i++;
     }
     else {
     $addlocationsearch = NULL;
     }

     $searchUrl = $base_url.'/search/applications?'.$addlocationsearch;

     $form_state['redirect'] = $searchUrl;
     }

```

I think the logic used here could be used to make a much better module. If you've a plan for some development I'd be happy to join in a project.

---
Tags: search
---


# Question
Title: indexing first letter of items to make an A-Z type glossary, using solr backed and search api
I am using the search\_api and the solr backend. It is possible to index first letter of content so I can use solr to create an A-Z style filter?

# Answer
> 2 votes
OK, it's a little late. But yes, you can index a glossary. I've build an A-Z-Filter in SOLR based on custom entity-fields like `surname` here http://www.autorenwelt.de/verzeichnis/menschen My filter based on the following description: https://drupal.org/node/2069005

I need only this functions to build a field in the SOLR index:

```
/**
 * Apachesolr index name for this module.
 *
 * Dynamically creates name as expected by Solr.
 */
function _MODULENAME_search_index_key($key) {
  $index = array(
    'name' => $key,
    'multiple' => FALSE,
    'index_type' => 'string',
  );
  return apachesolr_index_key($index);
}

/**
 * Implementation of hook_apachesolr_index_document_build()
 *
 * Alters what is sent to Solr in $document.
 */
function MODULENAME_apachesolr_index_document_build($document, $entity, $entity_type, $env_id) {
    $glossary_key = _MODULENAME_search_index_key('custom_glossary');
    // We want to index the first letter of the title for use in our glossary
    $key = strtoupper($entity->title[0]);
    // Build a custom glossary of profile2 entities
    if ('profile_main' == $entity->type) {
        $key = strtoupper($entity->field_profile_surname['und'][0]['safe_value'][0]);
    }

    $indexed = '0 - 9';
    switch ($key) {
        case 'A':
        case 'B':
        case 'C':
        case 'D':
        case 'E':
            $indexed = 'A - E';
            break;
        case 'F':
        case 'G':
        case 'H':
        case 'I':
        case 'J':
            $indexed = 'F - J';
            break;
        case 'K':
        case 'L':
        case 'M':
        case 'N':
        case 'O':
            $indexed = 'K - O';
            break;
        case 'P':
        case 'Q':
        case 'R':
        case 'S':
        case 'T':
            $indexed = 'P - T';
            break;
        case 'U':
        case 'V':
        case 'W':
        case 'X':
        case 'Y':
        case 'Z':
            $indexed = 'U - Z';
            break;
    }
    $document->{$glossary_key} = $indexed;
}

```

And I use `hook_facetapi_facet_info_alter` to register this facet:

```
/**
 * Implementation of hook_facetapi_facet_info_alter().
 **/
function MODULENAME_facetapi_facet_info(array $searcher_info) {
    $facets = array();
    // Facets are usually associated with the type of content stored in the index.
    if (isset($searcher_info['types']['node'])) {
        $facets['ss_custom_glossary'] = array(
            'default widget' => 'links',
            'name' => 'ss_custom_glossary',
            'label' => t('A - Z Glossar'),
            'dependency plugins' => array('role'),
            'description' => t('Glossar basierend auf dem ersten Buchstaben des Node-Titles.'),
            'field' => 'ss_custom_glossary',
            'field_alias' => 'ss_custom_glossary',
            'weight' => -50
        );
    }

    return $facets;
}

```

Ciao Ralf

# Answer
> 0 votes
drupal itself provide glossary module by default go to views-\>search with glossary-\>enable and you get something like this http://www.dna2life.com/a-z-index

still if you want to index manually and want to show indexing in single page http://drupal.org/node/1895352

# Answer
> 0 votes
I used the code below with search\_api/search\_api\_solr.

```
<?php
/**
 * @file
 * Index First letter of title to make a Glossary
 * and provides new fields to index.
 */

/**
 * Implements hook_entity_property_info_alter().
 */
function YOUR_MODULE_entity_property_info_alter(&$info) {

    $info['node']['properties']['lexical'] = array(
        'type' => 'string',
        'label' => t('1st Letter of the title'),
        'sanitized' => TRUE,
        'getter callback' => 'YOUR_MODULE_lexical_getter_callback',
    );

}

/**
 * Getter callback for lexical property.
 */
function YOUR_MODULE_lexical_getter_callback($item) {
    return strtoupper($item->title[0]);
}

```

---
Tags: search
---


# Question
Title: Building an advanced multicriteria search
I'm kinda new to Drupal and I would like some advises.

I have a Drupal website, with a few nodes (1000 - 5000) of a particular content type, let's say a "House".

This "House" content type has a few properties (20) like `price`, `location`, `number of rooms`, etc.

In order to allow my end users to find those nodes, I've build an advanced search with the Finder module.

However, this module is no longer maintained and it is not really appropriate to search through many nodes.

> Finder does not work like a typical search module, it does not base it's functionality on search indexes, and therefore is not an efficient choice for searching body content, though it can technically do that. It is more suitable for filtering on short field values.

What are the **best options to build an advanced multi criteria search with Drupal 7** ? Do I need to do it by hand ? What are the modules out there that could help achieving that ?

Is Facet API the way to go ?

# Answer
> 3 votes
I think facets are a great way to do advanced searching. Facet API is a great module that is flexible.

You can use it with core drupal search using Faceted Navigation for Search or Search API, which can use the drupal database to search.

However, due to the queries that are run in the calculation of facet data, there are performance implications of using faceted search with drupal SQL based searching.

If you have a lot of content, are using a lot of different facets, or have high traffic, I would definitely recommend using a better search engine.

Apache solr, is great and is pretty easy to get set up these days.

You main options are the Apache Solr Search Integration module and the Search API module, in conjunction with the Search API Solr search module.

Both those integrate with the facet API module.

Solr is not really shared host friendly though. Generally you will have to find a host that will provide apache solr hosting, or use a VPS or dedicated server that allows you to install solr yourself.

# Answer
> 0 votes
Building an advanced multicriteria search can be easily done with Search API multi-index searches.

---
Tags: 7, views, forms, search
---


title: How do I test my code in Drupal 8?

text:
# Question
Title: How do I test my code in Drupal 8?
I created a Drupal 8 module and I would like know what is the best practice for testing my code?

For example, if I use **hook\_user\_login()**, how I can try my code without login/logout every time and how do I display my var\_dump() result? (var\_dump result not displayed due to redirection after login)

# Answer
> 3 votes
Use Devel for most of the (There is a dev version for Drupal 8) visual testing and seeing output of most of the render arrays (DPM function will retain the array if there is redirect so it will output in those cases). Plus other variables can be output. You can use the old school `tail -f drupal_debug.txt` by using `dd()` or just output in Krumo to the screen with `dpm()`. You can find out more about Devel by visiting the project page.

Also you can run tests using Drupal SimpleTest and find out more about how to implement SimpleTest in the Drupal Examples which does have tests examples for 7 and 8.

---
Tags: 8
---


# Question
Title: how to print google map field value in a page tpl
I am trying to print a value of submitted for a google map field in a page.tpl.php file. I used below code to print but got a error message. I am able to print other field types using similar code but unable to do the same for map filed. Please help

```
<?php
  $node=node_load(41);
  print "<div id='map'>".$node->field_add_map['und'][0]['GoogleMapField']."</div>";// print styled image
?>

```

# Answer
> 1 votes
For a start don't load the node in the template file like that.

If you want to load a node do it in a template preprocess function in your theme's template.php file, like this for example:

```
/**
 * Variable preprocess function for the page template.
 */
function THEMENAME_preprocess_page(&$variables, $hook) {
  // Load a node and save it to the variables array.
  // This will then be available in the variable $node, in the page.tpl.php template.
  $variables['node'] = node_load(41);
}

```

However don't use `$variables['node']` in the page template because it is already in use. If you are on a node page then that variable will already be populated with the node object of the current page, so in your template you can access it using `$node`.

If you are aloading a node that isn't the current page node then you can do it your way but give the variable a different name, like `$variables['map_node']` for example, which would then be available in the template file as $map\_node.

On to the field printing.

The problem is you are trying to print the GoogleMapField property of the field value, which as far as I know doesn't exist.

The values in this field type are:

* lat
* lon
* map\_width
* map\_height
* zoom
* name

So doing what you are doing you could print those out, however I'm thinking you probably don't want those either.

So you want to print the rendered field item. There are a few ways this can be done but a good option is using the field\_view\_field() function like this:

```
/**
 * Variable preprocess function for the page template.
 */
function THEMENAME_preprocess_page(&$variables, $hook) {
  // Load a node and save it to the variables array.
  // This will then be available in the variable $node, in the page.tpl.php template.
  $variables['map_node'] = node_load(41);
  // Get the rendered markup for the map field to print in the template.
  $variables['rendered_map'] = field_view_field('node', $map_node, 'field_add_map', 'full');
}

```

That example uses whatever display configuration you have set on the "full" display mode for your node type for that field. You could use "teaser" or some other view mode if you prefer. You could even add a custom view mode specifically for this if it suits your use case.

Then in your page template you could do something like this to print the map using the render() function:

```
if ($rendered_map) {
  print render($rendered_map);
}

```

---
Tags: theming, entities, google-maps
---


# Question
Title: Add <a href> link around each row in views
So basically i want to add a link to original node around each row in views. I have added the following code to the style and row template override in views. Both come up with the same result.

```
<?php $image = file_create_url($row->field_field_display_image[0]['rendered']['#item']['uri']); ?>
<a href="www.google.com"/>
  <div class="block__inner" style="background-image: url('<?php echo $image; ?>');">
    <?php foreach ($fields as $id => $field): ?>
      <?php if (!empty($field->separator)): ?>
      <?php print $field->separator; ?>
    <?php endif; ?>
  </div>
</a>

```

Now the issue that i am having is that the link is added to each field element that is outputted for some reason, and not just the link around the whole row and each field.

I cannot use custom field as that is making the same issue. It seems views is auto closing the a tag.

Any known workarounds?

# Answer
> 8 votes
I usually remove all default formatting from every field, then hide all of my fields from display apart from the last field in views, and also remove all formatting, making the hidden fields plain text where possible.

Then in that last fields settings, rewrite the results, and input all of the fields as tokens from the replacement patterns.

Then instead of div elements, I use span which plays better inside an anchor, and just add unique classes for each span element.

So an example rewrite results might be...

```
<a href="[path]">
<span class="title">[title]</span>
<span class="body">[body]</span>
</a>

```

**This should not suffer the same issue if you go to each hidden field, and under the style fieldset, make sure than no default wrapper or classes are applied, and also that each field is plain text. This will strip all formatting and place it inside the rewritten span elements. Like @BeeBee says, div and p will break the anchor wrapper.**

# Answer
> 2 votes
Override views template for `Style output`

```
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <h3><?php print $title; ?></h3>
<?php endif; ?>
<?php $i = 0;?>
<?php foreach ($rows as $id => $row): ?>
  <a href="node/<?php print $view->result[$i]->nid;?>">
  <?php $i++;?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
  </div>
  </a>
<?php endforeach; ?>

```

Make sure there are no inner links (title with link to original content for instance).

# Answer
> 1 votes
I have found that the best control for changing markup on views (by row) is to set the view to be an unformatted list.

See here: https://api.drupal.org/api/views/theme!views-view-unformatted.tpl.php/7

Also, test carefully when you wrap elements in your anchor tag. with older versions of IE specifically, but any browser really. anchors don't play well with a bunch of other markup inside them.

---
Tags: views, theming
---


# Question
Title: Add class to a views field depending on image's being vertical or horizontal
I have a view that outputs an image field. I would like to add a class to the `.views-field` div (for example, actually a `views-row` would also do the job) depending on whether the image is vertical (length \> height) or horizontal (height \> width).

I tried making a custom `views-view-field-tpl.php` for outputting the view's field, but I have no idea how to access the image or the image data.

EDIT: I've found that `$field` contains `additional_fields`, which in turns includes `field_photo_width` and `field_photo_height`. Those are arrays, though, and I have no idea how to get an actual value from them.

# Answer
> 3 votes
The answer could be approached from various angles. Simpler perhaps would be to target the template\_preprocess\_image itself, and add a div wrapper around it with the class, or just add the class on the img tag. I chose to do it via template\_preprocess\_field.

```
function THEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_IMAGE_NAME') {
    foreach($vars['items'] as $key => $item){
      if (_add_image_proportions_class($item)) {
        if ($item['#item']['width'] > $item['#item']['height']) {
          $vars['classes_array'][] = 'landscape';
        }
        else if ($item['#item']['width'] < $item['#item']['height']) {
          $vars['classes_array'][] = 'portrait';
        }
        else {
          $vars['classes_array'][] = 'square';
        }
      }
    }
  }
}

function _add_image_proportions_class($item) {
  return $item['#image_style'] == 'medium';
}

```

\_add\_image\_proportions\_class() is just a function you implement to test whether you want to add the class or not. In my example, I targeted the image style that is applied to the image. You could for instance create a specific image style that is used only for that view, and target it specifically. Or you could test the path you are on, etc.

---
Tags: views, theming, media
---


# Question
Title: Calendar widget translate problem on Drupal 7
I am experiencing issues with the translation of the Date/calendar Widget for Drupal 7 and I wonder if there is a solution for this problem without mixing with the source code for the date/calendar module, or if maybe I am missing some point here.

Here are the initials for the week days in the little calendar in English:

```
M - Monday
T - Tuesday
W - Wednesday
T - Thursday
F - Friday
S - Saturday
S - Sunday

```

In Portuguese, the same week days are:

```
S - Segunda-feira
T - Terça-feira
Q - Quarta-feira
Q - Quinta-feira
S - Sexta-feira
S - Sábado
D - Domingo

```

The problem is that when I translate the 'T' (Thursday) to 'Q' (corresponding to "Quinta-feira"), both days starting with a 'T' in English are translated as 'Q' in Portuguese. Both Tuesday and Thursday are shown with a 'Q' on top, and that of course is plain wrong for displaying the calendar in Portuguese.

Is there some built-in localization/translation feature for the calendar that doesn't use the Drupal translation tool that does not seem to work in this case?

Thank you.

# Answer
If you by date widget means the JS popup, then that part is not actually translatable in Drupal. Instead you need to activate a load a language js file for the jQuery plugin which will translate the widget for you. If those translations are wrong, you should file a bug report with the jQuery team.

I searched the data module and couldn't find the text strings that you mention above. Drupal 7 allows modules when creating translatable strings to provide a context. I see that the date module does that several places:

```
t($date->format('F'), array(), array('context' => 'Long month name', 'langcode' => $langcode));

```

Doing this will create an extra translatable strings. An example use would be:

```
t('Order', array('context' => 'the order of items');
t('Order', array('context' => 'an e-commerce order');

```

The word is the same but the meaning is different, by doing the above it will allow translators to translate the strings differently. If a Drupal module provides the text strings for your widget, they will need to do something similar: fx

```
 t('T', array('context' => 'Tuesday');
 t('T', array('context' => 'Thursday');

```

If the module haven't done this, your best bet is to submit a patch for the module and explain why they need to do this. This is generally a good practice to do when you create translatable string that aren't unique.
> 2 votes

# Answer
Below link helped me. Add what ever you want in the PO file & import it.

Translate Date pop-up
> 1 votes

---
Tags: datetime
---


# Question
Title: Select data from database when submitting a form
I'm trying to learn how to make select queries with Drupal, so I made a form, and when I submit the form I try to query the database and get some results, but instead I'm redirected to an error page, here's how I select nodes from DB :

```
function my_module_form_submit($form, &$form_state)
{
    $query = db_select('node', 'n')->extend('PagerDefault');
    $query->condition('type', 'myContentType');
    $result = $query->execute();
}

```

# Answer
> 1 votes
You have missed fields() & fetch type -- fetchAll().

Below is the working example. You can find more details here (db\_select API)

```
$query = db_select('node', 'n')->extend('PagerDefault');
$query->fields('n'); // This is like select *. You can retrieve specific fields too.
$query->condition('type', 'article');
$result = $query->execute()->fetchAll(); // you can fetch by object, array, etc...
print_r($result);

```

# Answer
> 0 votes
I don't know exactly what was the issue with the code I used before, but using a more advanced query resolved the problem ( being redirected to an error page ) :

```
$query = db_select("node", "n");
$query->fields("n", array("nid"));
$query->fields("n", array("created"));
$query->fields("n", array("type"));

$query->fields("f1", array('field_f1_value'));
$query->fields("f2", array('field_f2_value'));
//...

$query->leftJoin('field_data_f1', 'f1', 'f1.entity_id = n.nid');
$query->leftJoin('field_data_f2', 'f2', 'f2.entity_id = n.nid');
// ...

$query->condition('n.type', 'voitures_d_occasion', '=');
$query = $query->orderBy('n.created', 'DESC');
$query = $query->extend('TableSort')->extend('PagerDefault')->limit(10);
$result = $query->execute();

```

---
Tags: database
---


# Question
Title: Using a different administration theme according to the role
Is there a way to use different administration themes according to the roles assigned to users?
I have two roles (admin, editor), and I want that, when creating content, users with the admin role use the garland theme, while users with the editor role use another theme.

# Answer
The ThemeKey module lets you set the theme using many different tests. While it doesn't specifically set admin theme in the usual way, it will certainly let you set a theme for a role and a path, achieving the same result. Some more details about this module (from its project page):

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules
> 6 votes

# Answer
The Sections module can handle that for you.

Here is a quote about it (from the module's project page):

> ... allows you to create sections within your site. Each section has an installed template, theme or style attached to it.
>
> Sections are shown based on:
>
> * Node specific visibility settings
> * Role specific visibility settings
> * Page specific visibility settings (regexped paths)
> * Custom PHP visibility snippets
> 0 votes

# Answer
I want something like that you want, themes according to roles and I found the Role Theme Switcher module, it is the best one for this job. Here is a quote about it (from the module's project page):

> ... assign separate themes for different roles (including anonymous) in your system.
>
> Often you want to separate Drupal administrative interface from frontend. You can do this assigning appropriate theme for you as user. What to do if you want to show different theme for non-authorized user?

**update:**
Role Theme Switcher can't set admin theme per user, use can use Themekey or Themes By Role (TBR) module

> About this Module
>
> This module comes out of a personal need to not want to use the same admin theme as the users and content editors of the sites I build. This module aims to fix that problem by allowing different themes to be enabled based on a user's role. Key Features
>
> ```
> Choose admin themes based on user role instead of a single admin theme for the whole site
>     Default site theme
>     Default admin theme
>     Any available theme
>
> ```
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Why does this code work for the current term but not the parent term?
This code below displays the current taxonomy term on a taxonomy term page

```
$current = taxonomy_term_load(arg(2)); ?>
if ($current): ?>
echo $current->name; ?>
endif; ?>

```

The code below displays the error: "Notice: Trying to get property of non-object in eval() (line 9 of...) Line 9 is "echo $parent-\>name;"

```
$parent = taxonomy_get_parents($current->tid);
if ($parent){
echo $parent->name;
}?>

```

I'm really confused as to why the first set of code works but the 2nd doesn't? "print\_r($parent);" displays the info below, so the data is there.

Array ( \[3218\] =\> stdClass Object ( \[tid\] =\> 3218 \[vid\] =\> 12 \[name\] =\> NAME OF TAXONOMY TERM \[description\] =\> This is the description area \[format\] =\> full\_html \[weight\] =\> 0 \[vocabulary\_machine\_name\] =\> mfr\_model \[field\_displayed\_view\] =\> Array ( \[und\] =\> Array ( \[0\] =\> Array ( \[vname\] =\> final\_term\_pages|testing \[vargs\] =\> ) ) ) \[metatags\] =\> Array ( \[und\] =\> Array ( \[title\] =\> Array ( \[value\] =\> This is the meta page title ) \[description\] =\> Array ( \[value\] =\> This is the meta description ) ) ) ) )

# Answer
> 0 votes
If you check out the docs for taxonomy\_get\_parents() you can see that the return value is an array of parent terms.

So you might loop through the results like this:

```
$parents = taxonomy_get_parents($current->tid);
foreach ($parents as $parent) {
  echo $parent->name;
}

```

or use just the first one like this:

```
$parents = taxonomy_get_parents($current->tid);
if ($parents) {
  echo $parents[0]->name;
}

```

---
Tags: taxonomy-terms
---


# Question
Title: Automatically insert images to translated page
I have a bilingual D7 website. It seems odd to insert all images twice, one for the original and one for the translated version, so my question is: Is there a way to automatically insert the image I upload for my orignal site into its translation?

# Answer
You should use Entity Translation module instead of core Content Translation to provide multilingual functionality into your site, then define which fields are translatable and which are not. You can't reach your goal with Content Translation module only.
> 0 votes

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


title: Disappearing Content

text:
# Question
Title: Disappearing Content
I just inherited a Drupal 7 website from another agency. The site was fairing well in our DEV and STAGE environments. The problem started occurring when we switched DNS over to our PRODUCTION site.

We have all the nodes (from the same content type) that seem to be "randomly" disappearing.

I've made sure to upgrade the core to the latest and any security fixes for any modules that are being used.

I was wondering what I could do to troubleshoot this issue - as I'm exhausting all my efforts and nothing seems to be working.

# Answer
It looks like a cache problem. I will suggest to do this, as usual backup is always a good idea:

1. See if this happens also if you are login. You might have your node permissions corrupted. If you rebuild and have a lot of node, it might take a little while to do this.
2. Turning cache off for page and blocks.
3. is your content generated by a view? if so check the permission
> 0 votes

# Answer
Local module is disabled. Enable the Local module. It will solve it.
> -3 votes

---
Tags: security, nodes
---


# Question
Title: Is there a drupal.org API for retrieving the list of available modules?
Is there a drupal.org API for retrieving the list of available modules, a description of them and available versions?

# Answer
> 2 votes
Very recently there's an API published: https://www.drupal.org/api

# Answer
> 1 votes
There is no such API or mechanism at this time.

There is talk about extending Drush to support a Search functionality: https://drupal.org/node/1389460

But that's after a database of dependencies is created for all modules and stored in a binary-ish form fetchable by Drush: https://drupal.org/node/1299332

# Answer
> 1 votes
Turns out there is a big machine-readable list of Drupal projects available here:

http://updates.drupal.org/release-history/project-list/all

Warning: Very large. :-)

Courtesy of this comment, which also tells you a URL pattern to crawl for release information: https://groups.drupal.org/node/65023#comment-204808

I wish there were good documentation about the availability of other such easter eggs.

# Answer
> 1 votes
There's an issue to Expose list of projects to external services (via JSON, XML, etc). That issue ended up providing a `tsv` file with a list of all stable releases (no -dev) for all projects in drupal.org. The list is generated each 4 hours, after http://updates.drupal.org/release-history/project-list/all is regenerated.

https://drupal.org/files/releases.tsv (~4MB)

The rationale for this file is in comment #88 if the linked issue.

---
Tags: community-official-site
---


# Question
Title: how to remove element from node__product__type.tpl.php commerce kickstart
In my website with commerce kickstart, I would like to remove div with its class name "field\_label" in node\__product\__type.tpl.php. I have no idea of how to code to remove it. Any suggestion is greatly appreciate.

html

```
<div class="field-label">
    tshirt size:
</div>

```

node\__product\__type.tpl.php

```
<article<?php print $attributes; ?>>
<?php print "testing product testing" ?>
<?php print $user_picture; ?>
<?php print render($title_prefix); ?>
<?php if (!$page && $title): ?>
  <header>
     <h2<?php print $title_attributes; ?>><a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?></a></h2>
  </header>
<?php endif; ?>
<?php print render($title_suffix); ?>
<?php if ($display_submitted): ?>
<footer class="submitted"><?php print $date; ?> -- <?php print $name; ?></footer>
  <?php endif; ?>
 <div class="container-24 grid-14 prefix-1 clearfix">
   <?php print render($content['product:field_images']); ?>
 </div>
<div class="container-24 grid-8 prefix-1">
   <div<?php print $content_attributes; ?>>
     <?php
      // We hide the comments and links now so that we can render them later.
       hide($content['comments']);
       hide($content['links']);
       print render($content);
    ?>
   </div>
 </div>
 <div class="container-24 grid-24 clearfix">
    <?php if (!empty($content['links'])): ?>
    <nav class="links node-links clearfix"><?php print render($content['links']);?></nav>
  <?php endif; ?>
    <?php
      print render($content['comments']);
    ?>
   </div>
 </article>

```

# Answer
If you want to remove both the class and the label, 'tshirt size:', you don't have to do it via code. You can use the "Display settings" of the product and make the label hidden. ie, Go to content type -\> Manage Display -\> Node and select hidden for the size label.
> 0 votes

---
Tags: commerce, theming
---


# Question
Title: Store Products and Store Orders issues of Commerce_marketplace module
I want to create a marketplace site(where multiple merchants/ stores will add their products to our site.) using Drupal Commerce and commerce\_marketplace module. But i am having issues with this. Store owner is unable to find his/her added products.

Is there alternative way to do this.

# Answer
If you go to user/%/store(or by clicking the stores tab in your user page), you will be able to see the stores of the particular user. On clicking the store name, you will be re-directed to a page commerce\_store/store/%storeid. In this page, there will be diffrerent tabs View, Edit, Delete, "Storename"'s products, Memebers and Sales tab.

On clicking the tab "Storename"'s products, you will be able to see the products added to your store.

Also please double check that you have enabled correct permissions.

One thing though, admin will not be able to see the products of another user via the above method. He will have to naviagate to structure-\>Entity type -\> commerce store -\>store and click on a particular store name to view that store's details.

Let me know how that goes.
> 0 votes

---
Tags: commerce
---


# Question
Title: How can I create a new page template for the user registration page?
I am a beginner in Drupal. I need to create a new page template for the registration page. Because in my website almost all pages have different layout.

Currently all pages are rendering through `page.tpl.php`.

Any suggestions?

# Answer
> 2 votes
There are so many ways to theming your registration page. You can create `user-register.tpl.php`

To know about how to create `user-register.tpl.php` refer below links.

https://www.drupal.org/node/1211520

https://api.drupal.org/api/drupal/modules!user!user-profile.tpl.php/7

https://www.drupal.org/node/1195754

If you want to know how to create tpl files.

Page template suggestions are not working

---
Tags: forms, users
---


# Question
Title: URL alias in view with subfolder of the Drupal installation
I've never seen this before:

This D7 installation runs in a subfolder of my dev server. The same way as all the other installations.

In a view I have a field with the node alias path. But this path I get with the subfolder.

Drupal runs in: myserver/subfolder/mydrupal The path is: this-is-my-node

I should get: this-is-my-node

I get: /subfolder/this-is-my-node

When I overwrite the output of this field with \[path\] all works fine.

What could be happened?

# Answer
Open your root .htaccess file and uncomment `RewriteBase /`

This should set the new root for your Drupal installation when operating out of a sub folder. This is usually required when enabling Clean URL's.
> 1 votes

---
Tags: views, path-aliases
---


# Question
Title: drupal_render does not render concatenated elements
I am new to Drupal and wonder if users who have experience in this kind of questions can help me with my issue.

The problem is that the output of `$complete0` through `drupal_render()` results in an empty space. Replacing `$complete0` with either `$title0` or `$name0` works just fine, however trying to render a concatenated field does not get the job done. Please see the piece of code below:

```
    try{
        $title0 = field_view_field('profile2', $user['recommendation'], 'field_rec0_title');
        $name0 = field_view_field('profile2', $user['recommendation'], 'field_rec0_title');
        $complete0 = "{$title0} {$name0}";
    }
    catch (EntityMalformedException $e) {}
    if(empty($complete0)){
        $form['profile_evaluation']['field_field_eval_rec0']['und']['#title'] = 'Information missing';
    }
    else{
        $complete0['#title'] = 'Recommender 1';
        $form['profile_evaluation']['field_field_eval_rec0']['und']['#title'] = drupal_render($complete0);
    }

```

# Answer
`drupal_render()` renders an array.

The var `$complete0` in your code is a string, so you shouldn't be passing it to `drupal_render()`.

Either use `render()`, which works for strings too, or convert `$complete0` to a render array.
> 0 votes

---
Tags: theming
---


title: Drupal Image Styles

text:
# Question
Title: Drupal Image Styles
I have a Drupal site that has around 24 image styles defined. The problem I'm having is the files directory seems to be building up a huge amount of files.

If I upload an image, does Drupal automatically created a version for each of the 24 styles, or should it only create the relevant size if it's specifically requested within the code?

# Answer
Derivative images are created on-the-fly, when they're first requested via HTTP, or when `image_style_create_derivative()` is invoked manually for the relevant image/style name.

They're not generated en-masse when a file is first uploaded, unless you have a contrib/custom module installed which provides that functionality.
> 3 votes

# Answer
Drupal only creates the file when it's needed.

The way this works is a url is generated, eg. /sites/default/files/styles/public/somestyle/beach.jpg. The first time this url is called, the file doesn't exist.

Due to Drupal's url handeling, Drupal will chop of parts at the end until it has a hit, in this case /sites/default/files/styles will be caught by the hook\_menu of the image module. It will get public, somstyle and beach.jpg as parameters.

Based on these parameters, the image module creates the image.
> 1 votes

---
Tags: media
---


title: Hook inside class

text:
# Question
Title: Hook inside class
I would like know if it's possible to use hook inside a class and inside .module file.

By example :

modulename.module

```
<?php
use Drupal\xenforo\Xenforo\XenAPI;
use Drupal\Core\Entity\EntityInterface;
Class XenforoBridgeIntegration {
    // use Drupal 8 hook here and can use OrientedObject inside
}

```

I have try, but hook don't work if it's inside a class ?

# Answer
No, it's not possible.

Hooks are functions that exist in the global namespace. Class/instance methods cannot be used to implement them.

If you take a look at the very simple ModuleHandler::invoke method, you'll see this in action:

```
public function invoke($module, $hook, array $args = array()) {
  if (!$this->implementsHook($module, $hook)) {
    return;
  }
  $function = $module . '_' . $hook;
  return call_user_func_array($function, $args);
}

```

As you can see, you must have a function called MODULENAME\_HOOKNAME available in the global namespace, no consideration is given to classes or namespace resolution.

You can (and probably should) hand off whatever processing you're doing inside the hook to a specific class, but the hook itself will need to be implemented in procedural style.
> 4 votes

---
Tags: 8
---


# Question
Title: no acces to /admin urls after site migration to local wamp server
After migration of my site , any url starting with /admin generate a wamp server 'reinitialization error'. The migration has been done with drush-dump/archive-restore and is working fine when imported in a VM

what could be the cause and how can i debug it ?

# Answer
Doing a

```
   drush pm-update

```

solved the problem.

Any fine explanation why?
> 0 votes

---
Tags: migrations
---


# Question
Title: Rules reacting on an event that hasn't happened?
Rules is acting weird all of a sudden. (v. 1.28)

It seems to be reacting on an Event that has not happened.

Using Commerce. Debug log shows that Rules reacts on the "Calculating the sell price of a product" event **six** times when I add a product to the cart, then reacts on "After adding a product to the cart", then reacts again on "Calculating the price", then reacts on **"Select available payment methods for an order**."

This last one seems really weird. We haven't even entered checkout. Why react on an event that definitely has not happened?

To make matters worse the Rules under the different events are firing multiple times, so I have customers receiving multiple emails and so on.

I have rebuilt the Rules cache. I have disabled Rules Conditional. I cannot understand why this is happening. Help, please?

# Answer
> 1 votes
Have a read of https://www.drupal.org/node/2403851 .

In short, Rules 2.8 is causing issues with Commerce. The module maintainers are aware and looking at the problem but until it is sorted they are suggesting rolling back to Rules 2.7.

# Answer
> 0 votes
Rules 2.8 has a bug causing Reaction Rules to be run too early: https://www.drupal.org/node/2324587

This bug was marked fixed by the Rules people but it appears to be the cause of the problems with Rules in Commerce using Rules 2.8. One of the Commerce maintainers reopened the Rules issue on 1/16/15. It's not fixed yet.

Rules 2.8 should not be used with Commerce. It will trigger Rules before their time and break your site.

Users of Commerce with Rules 2.8 should downgrade to Rules 2.7 immediately.

---
Tags: commerce, rules
---


# Question
Title: Alter comment links in blog teaser in drupal 7
I would like to alter the comment links in the teaser view of the blog page. The code I have in node--blog.tpl.php at the moment is:

```
<code><?php if ($display_submitted): ?>
<div class="submitted">
  <ul>
<li><?php $date = date("d F Y", $node->created); ?>
<?php print $date; ?> </li>
 <li> <?php $user = user_load($node->uid); ?>
        <?php $username=$user->name; ?>
<?php print t("By"); ?>
<a href="blogs/<?php print $username ?>"><?php print $username ?> </a> </li>
  <li> <span><?php print ($comment_count); ?></span> <?php print render($content['links']['comment']); ?></li>
  </ul>
</div>

```

\>

with css: `.submitted ul li span {
 color: #fff;
 background: url("../images/blue-bubble.png") 0px 2px no-repeat;
 background-size: 100% 96%;
 padding: 0px 5px 5px 5px;
}`

which produces:

but I want to make:

Any suggestions on this would be great!

Thanks

# Answer
> 0 votes
If I were you I'd hide the span content in CSS and add a tag for my background image like this:

Template:

```
<li>
    <span class="comment-hidden"><?php print ($comment_count); ?></span>
    <span class="comment-count"></span>
    <?php print render($content['links']['comment']); ?>
</li>

```

CSS:

```
.submitted ul li span.comment-count {
  width: 16px; // or whatever
  height: 16px;
  background: url("../images/blue-bubble.png") 0px 2px no-repeat;
  background-size: 100% 96%;
  padding: 0px 5px 5px 5px;
}

.submitted ul li span.comment-hidden {
  display: none;
}

```

---
Tags: theming, nodes
---


# Question
Title: How do I update the body of a node using a query?
Let us consider I have a node called "DrupalTest" for which I need to update the body content using AJAX.

Shall I execute a query, or is there any other way to update the body content?

# Answer
1. Load the node using node\_load().
2. Set the body property of the node; examine the node object to determine which one the body property is. If you have the Devel module installed, kpr() will help you there.
3. Save the node using node\_save().

This ensures that the hooks associated with updating a node get executed, and that the cache is properly cleared.
> 3 votes

# Answer
Here is the detailed code for above answer

1. Determine the node id if possible. loan the node

if(is\_numeric($nid)){ $node = node\_load($nid); $node-\>body\['und'\]\[0\]\['value'\] = "your body content here "; $node\_save($node); }

**Saving node's fields without saving the node itself**

```
<?php
  $node = node_load($nid);
  $node->field_fieldname[LANGUAGE_NONE][0]['value'] = 'some value';
  node_save($node);
?>

```

There may be a case when you might want to save a node's field, but not the whole node itself. For example,if you may not want to update the node's timestamp for the last update, because you want it to be changed by human user activity only. In another case, you may not want to call node\_save() and thus invoke chain reactions such as email notifications when the node is updated.

A Drupal function `field_attach_update()` may save your day if you encountered a similar problem that I had. You could actually replace `node_save()` with `field_attach_update()`,

```
<?php
  $node = node_load($nid);
  $node->field_fieldname[LANGUAGE_NONE][0]['value'] = 'some value';
  field_attach_update('node', $node);
?>

```

The first argument takes 'entity type', which means it can be used for user, comment, etc, as well as node.

**If you want to update a single field only and save some time by skipping other fields** (because there are a lot and/or the routine is in a loop), you could remove unwanted fields first; the second argument ($node in the example) does not need to be complete with all possible fields.

by these ways you can update those node. easily ,efficiently and quickly.
> 0 votes

---
Tags: nodes
---


# Question
Title: Paging a view based on a grouping field?
I'm upgrading a site I created 2 years ago from D6 to D7. In that site, I have a view of items that are grouped according to year, so that the items for each year show up on a separate page -- you pass the view the year, and it displays the appropriate nodes for that year. I need to have "previous year" and "next year" links, which would link to pages that show the nodes for the previous or next years, as appropriate.

I did this in the old (D6) site by allowing the header to display PHP code (using the PHP filter), doing math on the passed-in "year" parameter, and writing out the link to the next and previous years as raw HTML. This feels wrong - very un-Drupal — but I can't figure out how to get views to do it more natively.

My feeling is that I'd like to use something like the grouping field (from "Format/Settings") except that instead of just putting a heading between the grouped nodes (which in my case would result in a page with over a thousand nodes displayed) it would split them into pages based on that grouping field.

Any ideas?

I found some items that point to a possible answer. There's this previous question:

Views pagination based on taxonomy terms

My years ARE also taxonomy terms, so this would work for me if the question was ever answered as asked. While there is no actual answer, there is a pointer to this very nice Earl Miles article:

http://drupalwatchdog.com/1/1/how-to-create-new-features-in-views-3

That is VERY close to my use case, and I guess if I have to I can try to create a Views Plugin based on Earl's instructions, but I'm hoping for something simpler. I'd rather use a plugin than write one!

(In the article, Earl says the code for the plugin could be found at http://drupal.org/project/views\_plugin\_examples, but when I go to that project it appears to be empty.)

In any case, this looks like a "solved problem" -- but I can't find the solution! Any pointers, before I re-invent the wheel?

# Answer
The easy way: use views summaries. You can put it as an attachment, right after your main view, and theme it as a pager.
> 0 votes

# Answer
Download the Date module at and be sure to active its Date Views submodule. That will add a Page by date option to the pagers listed in your Views config page. Here is a nice writeup by Richard Schulte on how to configure the date pager.
> 0 votes

---
Tags: views, datetime, paging
---


# Question
Title: Views pagination based on taxonomy terms
I have an archive Views page in Drupal 7 that is paginated after 10 items, themselves grouped and sorted by a taxonomy term ("issue date").

I've been asked whether it's at all possible to make the pager more descriptive based on the taxonomy vocab — i.e., instead of it just being "Go to Page 2", it's "Go to issues 2012-07-06 to 2012-06-29".

Any idea how I'd do that? Thanks!

# Answer
> 1 votes
I can't really understand why dates are stored as taxonomy terms, but yes, you can solve your task with powerful plugin system of Views. You should create custom views pager, which adds specific conditions to Views query.
The best example is an article by Views author Earl Miles: Creating a Date Pager Plugin for node "created" field (wow! dates, too).

> *As an example, we’re going to create a pager plugin that is somewhat useful, and completely non-traditional for Drupal. You have, however, very likely interacted with a pager of this nature before. Instead of relying on the number of results, we’re going to rely on the post date of the content...*

The code is avalible in Views plugin examples module.
Your task is more complex and, of course, requires professional skills.

# Answer
> -1 votes
If you specify the issue by using a Date field instead of a taxonomy term, you could use a date based pager. (It might also work with a taxonomy term if you do some handling to convert it to a timestamp in the argument handling code.)

Download the Date module at and be sure to active its Date Views submodule. That will add a Page by date option to the pagers listed in your Views config page. Here is a nice writeup by Richard Schulte on how to configure the date pager.

---
Tags: 7, views, taxonomy-terms, paging
---


title: I can't override the user_pass hook

text:
# Question
Title: I can't override the user_pass hook
because I use a websevcice to manage my users, I need to override the user\_pass() to send a new password via my webservices. This is what i did:

```
/**
* Implements hook_validate()
*/
function beneficiaire_user_pass_validate($form, &$form_state){
    die('poc');
}

/**
* Implements hook_submit()
*/
function beneficiaire_user_pass_submit($form, &$form_state){
    module_load_include('inc', 'beneficiaire', 'ws');
    global $user;

    if(beneficiaire_reset_password($user->name)){
        drupal_goto('login');
    }
}

```

My module is named beneficiaire. I've cleaned my caches many times when I enter a username in the form, it returns me

> Sorry, %name is not recognized as a user name or an e-mail address

instead of

> poc

An idea ?

Thank you

# Answer
> 3 votes
The main error is that, since your module's short name is beneficiaire, those are the implementations of `hook_user_pass_validate()` and `hook_user_pass_submit()`, which aren't hook Drupal utilizes. If you rename the functions `beneficiaire_validate()` and `beneficiaire_submit()`, those would not be hooks which are used as validation and submission handlers for the password change form.
See @Clive's answer for how adding form validation and submission handlers, keeping in mind that the validation handler is added with `$form['#validate'][] = 'beneficiaire_user_pass_validate';`.

As side notes:

* If you want to check a validation handler is called, use `form_set_error("", "beneficiaire_user_pass_validate() called");`
* To redirect the user after submitting a form, set `$form_state['redirect']` as in `$form_state['redirect'] = 'login';`

# Answer
> 2 votes
`hook_validate()` is for modules that provide content types, not for hooking into normal forms.

What you're looking for is `hook_form_FORM_ID_alter()`, something similar to this:

```
function beneficiaire_form_user_pass_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = 'beneficiaire_user_pass_submit';
}

function beneficiaire_user_pass_submit($form, &$form_state) {
  ...
}

```

---
Tags: users
---


# Question
Title: How to redirect user to new page after submitting user register form?
I've being trying to write custom module that redirects user from user register page after submit. I read several issues on Drupal Offsite and here on Stackexchange, but could not still resolve the issue.

This is my custom module code:

```
function myregistration_form_user_register_form_alter(&$form,&$form_state){
  unset($_GET['destination']);
  drupal_static_reset('drupal_get_destination');
  $_GET['destination'] = array('query'=>array('q'=>'order_translaton'));
}

```

The URL of the page I want to redirect to is: http://www.sociofobic.ru/drupal/?q=order\_translaton.

After registering user no redirect occurs. Instead I get the NOTICE:

> Notice: Array to string conversion in url\_is\_external() (line 2312 of /home/bnqpdcme/public\_html/drupal/includes/common.inc). Notice: Array to string conversion in drupal\_parse\_url() (line 589 of /home/bnqpdcme/public\_html/drupal/includes/common.inc). and Page not found: The requested page "/drupal/?q=Array" could not be found.

Please tell me what I do wrong, because the syntax for URL redirection I use is the same as explained in `drupal_redirect_form()`.

# Answer
> 2 votes
The syntax that you use is not the same as in the API docs. The `q`is to much.

Also, you shouldn't manipulate `$_GET`, that's not at all reliable. The correct way to achieve what you want, is to add a custom form submit handler and when that is called to set `$form_state['redirect']`.

Have a look at the accepted answer to this question: https://stackoverflow.com/questions/14542975/drupal-7-redirect-to-a-specific-page-a-tab-after-form-submit

# Answer
> 0 votes
Redirecting form after user save is easy

add a `hook_form_alter()`

```
$form['#submit'][1] = 'callback_redirect_to_custom_url_you_want';

function callback_redirect_to_custom_url_you_want(&$form, &$form_state){
    //get the custom field you want to redirect (sample code given below)
    $_GET['destination'] = array('query'=>array('q'=>'order_translaton'));
    $clean = $_GET['destination'] ;
    // or create a custom url you want to redirect
            $custom_url = $form_state['values']['field_name']['und'][0]['value'];
            $path = isset($custom_url) && !empty($custom_url) ? $custom_url : "";
            $clean = strtolower(trim($path, '-'));
            $form_state['redirect'] = $clean;
        }

```

---
Tags: forms, users, redirection
---


# Question
Title: Adding a validation step via hook_form_FORM_ID_alter()
I am trying to add a custom validation function to an existing form. I am using `hook_form_FORM_ID_alter()` to edit the form. I am then adding a new function to the #validation array. When I use `dpm()` and print out `$form['#validation']` I can see that my function is there. However the validation step is not running. If I `dpm()` in the validation function it is not hit.

```
/**
 *  Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_mycustomdorm_form_alter(&$form, &$form_state, $form_id) {
    $form['#validate'][] = 'mymodule_test';
    dpm($form['#validate']);
}

function mymodule_test($form, &$form_state) {
  dpm($form_state);
}

```

# Answer
Hi Bobby you can use custom validate submit handler to deal with this

```
$form['submit']['#validate'][] = 'custom_validate_function'

```

all you have to use is `#validate` in submit handler.

use the same callback function as above with replacing the callback name
> 0 votes

---
Tags: 7, forms
---


# Question
Title: 7 Ubercart hook_order for PayPal Paments Pro payment received
I've got Ubercart set up with Paypal Payments Pro and it is all working well, however, I want to set up the system so that when a payment is received (captured) in PayPal (after which the site successfully receives an IPN), an email is sent to our manufacturing plant to fulfill the order (including the order details, shipping address, etc.).

I am aware of hook\_order but I'm not sure how to use it in this scenario (i.e., upon IPN), or whether there might be an easier way to accomplish this (without code, i.e., using Actions). It is OK if we have to code it, that is not a problem. Only want to know my options.

# Answer
> 1 votes
IMHO the easiest way is to use Rules. There's a default rule you can clone and tune for your needs: uc\_payment\_received.

I would clone that rule, add the condition to ensure it's a payment coming from PayPal, then replace the action with "Send an order email". The you should be able to customize the email.

Writing a custom module for this task is a bit overkill.

# Answer
> 0 votes
One very important thing know about ubercart is that hook\_order from drupal 6 has been replaced with hook\_uc\_order in drupal 7.

Using hook\_uc\_order the conditions needed to figure out when an order is successfully completed seem to be:

```
function MODULE_NAME_uc_order($op, $order, $arg2) {
    if($op == 'update' && $order->order_status == 'payment_received' && $arg2 == 'completed'){
        //do something on order completion
    }
}

```

---
Tags: 7, ubercart, payment-gateways
---


# Question
Title: Omega 4: despite of environment set to production, css-file is full of sass-debug-info
I've built an Omega 4 subtheme, generating css through sass with 'drush omega-guard'. Despite my config.rb looks like this, all sass-debug-info{} rests in my generated css files:

```
saved = environment
environment = :production
if (environment.nil?)
  environment = :development
else
  environment = saved
end

output_style = (environment == :production) ? :expanded : :nested
line_comments = (environment == :production) ? false : true
sass_options = (environment == :production) ? {} : {:debug_info => true}

```

I there a wrong declaration in my config.rb or is there another setting overriding my config.rb?

# Answer
I cannot see anything wrong with your config.rb but if you are having problems you can use the following to force compass to strip out the debug info.

```
compass compile -e production --force

```

Source: https://www.drupal.org/node/1936986
> 1 votes

---
Tags: theming
---


# Question
Title: Form API 'image_button' vs 'submit' breaks my AJAX form
I have an AJAX form that works as expected with the following submit code:

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Go'),
);

```

I want to use an image for the button, but the type 'image\_button' breaks the AJAX functionality (multiple repopulating select fields, won't appear, or update):

```
$form['submit'] = array(
  '#type' => 'image_button',
  '#src' => '/themes/moon/images/go.gif',
  '#value' => t('Go'),
);

```

Oddly, the 'image\_button' works fine when clicking it (form works as expected) it's just the AJAX updating of the form that stops working? Drupal Form API Reference

# Answer
You have to set an unique '#name' tag for EVERY button (submit, image\_button, button) on the page. This worked for me.
> 1 votes

# Answer
Heads up that if you are using ctools modals, there is a bug with image buttons such that they aren't submitted when clicked (you can look at your POST details to check what values are submitted). I created a patch here that seems to fix it: https://www.drupal.org/node/1314894
> 0 votes

# Answer
Remove the `#value` from image button..
> -2 votes

---
Tags: forms
---


title: SQL Alias to Dynamic Query

text:
# Question
Title: SQL Alias to Dynamic Query
I have a complex views SQL query, that I have converted to a dynamic query which works perfectly -- my issue is with custom fields:

```
'node' AS field_data_field_description_node_entity_type,
'node' AS field_data_field_menu_photo_node_entity_type,
'node' AS field_data_field_price_node_entity_type

```

**How do I replicate these, this is the only part I am baffled by...** I am doing all of this using `hook_views_pre_execute()`, here is the original SQL returned by views (providing it so you can see the complexity):

```
SELECT node.nid AS nid,node.title AS node_title,
taxonomy_term_data_node.name AS taxonomy_term_data_node_name,
taxonomy_term_data_node.vid AS taxonomy_term_data_node_vid,
taxonomy_term_data_node.tid AS taxonomy_term_data_node_tid,
taxonomy_term_data_node.weight AS taxonomy_term_data_node_weight,
taxonomy_term_data_node__taxonomy_vocabulary.machine_name AS taxonomy_term_data_node__taxonomy_vocabulary_machine_name,
taxonomy_term_data_taxonomy_term_hierarchy.name AS taxonomy_term_data_taxonomy_term_hierarchy_name,
taxonomy_term_data_taxonomy_term_hierarchy.vid AS taxonomy_term_data_taxonomy_term_hierarchy_vid,
taxonomy_term_data_taxonomy_term_hierarchy.tid AS taxonomy_term_data_taxonomy_term_hierarchy_tid,
taxonomy_term_data_taxonomy_term_hierarchy.weight AS taxonomy_term_data_taxonomy_term_hierarchy_weight,
taxonomy_term_data_taxonomy_term_hierarchy__taxonomy_vocabulary.machine_name AS taxonomy_term_data_taxonomy_term_hierarchy__taxonomy_vocabul,
taxonomy_index.weight AS taxonomy_index_weight,
'node' AS field_data_field_description_node_entity_type,
'node' AS field_data_field_menu_photo_node_entity_type,
'node' AS field_data_field_price_node_entity_type
FROM {node} node
INNER JOIN (SELECT td.*, tn.nid AS nid FROM {taxonomy_term_data} td
INNER JOIN {taxonomy_vocabulary} tv ON td.vid = tv.vid
INNER JOIN {taxonomy_index} tn ON tn.tid = td.tid
WHERE (tv.machine_name IN  ('*DYNAMIC_VOCAB_MACHINE_NAME*')) ) taxonomy_term_data_node ON node.nid = taxonomy_term_data_node.nid
LEFT JOIN {taxonomy_term_hierarchy} taxonomy_term_data_node__taxonomy_term_hierarchy ON taxonomy_term_data_node.tid = taxonomy_term_data_node__taxonomy_term_hierarchy.tid
LEFT JOIN {taxonomy_term_data} taxonomy_term_data_taxonomy_term_hierarchy ON taxonomy_term_data_node__taxonomy_term_hierarchy.parent = taxonomy_term_data_taxonomy_term_hierarchy.tid
LEFT JOIN {users} users_node ON node.uid = users_node.uid
LEFT JOIN {taxonomy_vocabulary} taxonomy_term_data_node__taxonomy_vocabulary ON taxonomy_term_data_node.vid = taxonomy_term_data_node__taxonomy_vocabulary.vid
LEFT JOIN {taxonomy_vocabulary} taxonomy_term_data_taxonomy_term_hierarchy__taxonomy_vocabulary ON taxonomy_term_data_taxonomy_term_hierarchy.vid = taxonomy_term_data_taxonomy_term_hierarchy__taxonomy_vocabulary.vid
LEFT JOIN {taxonomy_index} taxonomy_index ON node.nid = taxonomy_index.nid
WHERE (( (users_node.uid = '*DYNAMIC_USER_ID*' ) )AND(( (node.status = '1') AND (node.type IN  ('*NODE_TYPE*')) )))

```

Here is the dynamic query, an exact replica of the above minus the `'node' AS` black magic:

```
// dynamically add vocabulary machine name
$query_vocab = db_select('taxonomy_term_data', 'td');
$query_vocab->innerJoin('taxonomy_vocabulary', 'tv', 'td.vid = tv.vid');
$query_vocab->innerJoin('taxonomy_index', 'tn', 'tn.tid = td.tid');
$query_vocab->condition('tv.machine_name', array($vocab_machine_name));
$query_vocab->fields('td')->addField('tn', 'nid', 'nid');

// main query
$query = db_select('node', 'node');

// joins
$query->innerJoin($query_vocab, 'taxonomy_term_data_node', 'node.nid = taxonomy_term_data_node.nid');
$query->leftJoin('taxonomy_term_hierarchy', 'taxonomy_term_data_node__taxonomy_term_hierarchy', 'taxonomy_term_data_node.tid = taxonomy_term_data_node__taxonomy_term_hierarchy.tid');
$query->leftJoin('taxonomy_term_data', 'taxonomy_term_data_taxonomy_term_hierarchy', 'taxonomy_term_data_node__taxonomy_term_hierarchy.parent = taxonomy_term_data_taxonomy_term_hierarchy.tid');
$query->leftJoin('users', 'users_node', 'node.uid = users_node.uid');
$query->leftJoin('taxonomy_vocabulary', 'taxonomy_term_data_node__taxonomy_vocabulary', 'taxonomy_term_data_node.vid = taxonomy_term_data_node__taxonomy_vocabulary.vid');
$query->leftJoin('taxonomy_vocabulary', 'taxonomy_term_data_taxonomy_term_hierarchy__taxonomy_vocabulary', 'taxonomy_term_data_taxonomy_term_hierarchy.vid = taxonomy_term_data_taxonomy_term_hierarchy__taxonomy_vocabulary.vid');
$query->leftJoin('taxonomy_index', 'taxonomy_index', 'node.nid = taxonomy_index.nid');

// conditions
$query
  ->condition('node.status', 1)
  ->condition('node.type', array($node_type))
  ->condition('users_node.uid', $owner->uid);

// fields
$query->addField('node', 'nid', 'nid');
$query->addField('node', 'title', 'node_title');
$query->addField('taxonomy_term_data_node', 'name', 'taxonomy_term_data_node_name');
$query->addField('taxonomy_term_data_node', 'vid', 'taxonomy_term_data_node_vid');
$query->addField('taxonomy_term_data_node', 'tid', 'taxonomy_term_data_node_tid');
$query->addField('taxonomy_term_data_node', 'weight', 'taxonomy_term_data_node_weight');
$query->addField('taxonomy_term_data_node__taxonomy_vocabulary', 'machine_name', 'taxonomy_term_data_node__taxonomy_vocabulary_machine_name');
$query->addField('taxonomy_term_data_taxonomy_term_hierarchy', 'name', 'taxonomy_term_data_taxonomy_term_hierarchy_name');
$query->addField('taxonomy_term_data_taxonomy_term_hierarchy', 'vid', 'taxonomy_term_data_taxonomy_term_hierarchy_vid');
$query->addField('taxonomy_term_data_taxonomy_term_hierarchy', 'tid', 'taxonomy_term_data_taxonomy_term_hierarchy_tid');
$query->addField('taxonomy_term_data_taxonomy_term_hierarchy', 'weight', 'taxonomy_term_data_taxonomy_term_hierarchy_weight');
$query->addField('taxonomy_term_data_taxonomy_term_hierarchy__taxonomy_vocabulary', 'machine_name', 'taxonomy_term_data_taxonomy_term_hierarchy__taxonomy_vocabul');
$query->addField('taxonomy_index', 'weight', 'taxonomy_index_weight');

```

If I add a `join` like `join('field_data_field_desciption', 'field_desc', 'field_desc.entity_id = node.nid')` I get no results. I might just opt for using `field_get_items()` in a `preprocess` function... but would rather not.

**Any guidance/help would be highly appreciated :)**

# Answer
> 0 votes
As it turns out the following are SQL Aliases, this is related to the FieldAPI:

```
'node' AS field_data_field_description_node_entity_type,
'node' AS field_data_field_menu_photo_node_entity_type,
'node' AS field_data_field_price_node_entity_type

```

They are replicated using `addExpression` they **must be before any `conditions` and `addField`**. Adding the following to my code above replicates the SQL perfectly:

```
$query->addExpression("'node'", 'field_data_field_FIELD_NAME_node_entity_type');

```

Thanks to @calebtr for the help!

---
Tags: 7, views, database
---


# Question
Title: Custom node field type should also support content block; what should I do?
I'm using the Paragraphs module for nodes. Here is a quote from its project page:

> Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's. Simply add a new paragraphs field on any Content Type you want and choose which Paragraph Types should be available to end-users.

But the type is not in the **add select** on `admin/structure/block/block-content/manage/basic/fields/add-field`.

It would be nice, if this module could offer the `paragraphs` field type also for **Content Blocks** (or other **field type creating modules** their types).

Has someone an idea, what the module maintainer has to do along general lines? I want to ask this as a feature request in the module's issue queue. But it would be nice if I can give some hint to the maintainer.

# Answer
> 2 votes
From looking at the code, the module does *not* define a field type. It just defines a widget for entity reference fields.

So, what you need to create instead is an entity reference field that points to paragraphs, and then select the Paragraps widget on "Manage form display".

But that should be exactly the same for nodes as well?

---
Tags: entities, blocks, 8
---


# Question
Title: Is Drupal cache as set in the core enough for simple sites?
Let's imagine a site which is almost completely static. There are news which are rarely updated and from time to time some new content in the form of more news. If there are only anonymous users apart from the admin... would the cache retrieval be so fast as simple HTML pages? I ask this because I have tested the config above with cache on and it goes very slow in comparison with HTML saved counterparts and I am not sure if it is a misconfiguration.

# Answer
> 1 votes
No it would be unlikely to be as fast as plain HTML, because the default caching is still using the database and some PHP.

However you can improve the speed significantly with a module or two. It is *highly* dependent on the speed of your servers - if you have a fast database server but a slow filesystem you might be better using the database although that is an unlikely situation. At minimum I recommend installing Advagg \- correctly configured that will reduce load times for a lot of sites by around 25%.

Depending on the site, Boost can also vastly improve performance although I have not found it as universally applicable as Advagg. Also depending on your setup an external cache like Varnish may be better although it requires careful configuration and some server admin knowhow.

# Answer
> 0 votes
Your problem might be misconfiguration of some modules, perhaps overuse of others. If you are using a shared host the problem might lie on the PHP Memory Limit, that sometimes is quite low (although lots of servers nowadays will allow you to change this for free).

You need to find out where is your bottleneck. Might be the connection with the db, the speed and limits of the PHP, perhaps some custom module...

---
Tags: caching, theming
---


# Question
Title: Switching to mobile theme while cache is enabled
I have a Drupal7 website using a modified Zen subtheme that looks ugly on mobile devices and i want some kind of utility to create a separate mobile theme .
I tried to use differents modules like Mobile Switch,Mobile Detect ,Mobile Tools & Theme Key but unfortunatley they don't support Drupal Default Cache .
Is there any way or method or another module to resolve this problem.
Thank you very much

# Answer
> 2 votes
ThemeKey does support the Drupal cache.

However, the Drupal cache cannot perform device specific cacheing on a single domain since page caches are organized by absolute URLs. See this discussion for an explanation: https://www.drupal.org/node/2242303

The solution is to have a device redirect at the server level to a mobile subdomain (ie. m.mysite.com) which shares the same docroot and switches the theme there. The Boost module is recommended and the process is outlined here:

https://www.drupal.org/node/1214890

---
Tags: theming, mobile-tools
---