# Question
Title: How to display elements responsively side by side using Bartik theme, similar to bootstrap grid?
I am developing a module for Drupal 8, currently using the default Bartik theme. My module defines some pages through twig templates. As I am displaying several sections of a dashboard, I would like to show two DIVs next to each other side by side.

I am looking for something similar to the Bootstrap Grid. I am even thinking to just try to use Bootstrap inside my module regardless of the Drupal theme, as I used Bootstrap before but I am new to Drupal theming.

Is there some way the Bartik theme (or different Drupal 8 theme) provides to display elements responsively side by side?

# Answer
> 2 votes
I ended up working around it by extracting the relevant css classes of bootstrap into my custom css file. Now I can use the bootstrap grid without disturbing the normal Drupal theme:

```
.row {
  margin-right: -15px;
  margin-left: -15px;
  box-sizing: border-box;
}
.row:before, .row:after {
  display: table;
  content: " ";
}
.row:after {
  clear: both;
}

.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
  position: relative;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
  float: left;
  box-sizing: border-box;
}

.col-md-12 {
  width: 100%;
}
.col-md-11 {
  width: 91.66666667%;
}
.col-md-10 {
  width: 83.33333333%;
}
.col-md-9 {
  width: 75%;
}
.col-md-8 {
  width: 66.66666667%;
}
.col-md-7 {
  width: 58.33333333%;
}
.col-md-6 {
  width: 50%;
}
.col-md-5 {
  width: 41.66666667%;
}
.col-md-4 {
  width: 33.33333333%;
}
.col-md-3 {
  width: 25%;
}
.col-md-2 {
  width: 16.66666667%;
}
.col-md-1 {
  width: 8.33333333%;
}

```

---
Tags: 8, theming
---


# Question
Title: Drush and MAMP3: cannot connect to database
I've just updated to MAMP 3.1, and am running Yosemite 10.10.3 (public beta). Since updating, I cannot perform any commands using Drush.

I have:

1. sim-linked from /var/mysql and also /var/lib/misql into /Applications/MAMP/tmp/mysql/mysql.sock
2. Tested the connection to the database using Sequel pro;
3. Tested the connection using a standard PHP script.

In both 2 and 3 above, I used the direct path to the MAMP socket, and also the one in /var/mysql/mysql.sock

So can anyone think of a reason why this won't work?

# Answer
> 1 votes
Thanks for those suggestions. I inadvertently stumbled on a solution. I'm no expert here, so there could (and probably are) reasons why this isn't a good idea but I'll share it anyway.

I simply created a sim-link by doing the following: cd /tmp sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock mysql.sock

Worked like a charm.

# Answer
> 0 votes
2 things seem to work:

* setting your mysql / pgsql to 127.0.0.1 in your settings.php file instead of localhost (if that was the case)
* reverting to Drush 6

But this is still an issue on MAMP 3.1 + Drush 7 that needs to be resolved.

---
Tags: drush
---


# Question
Title: How do I override a module template (.tpl.php) from my custom subtheme?
I've seen how to override module templates from other modules and theme templates from subthemes, but how do I override module from subtheme? The file is under the profiles folder.

Edit:

I'm using Open Atrium. I want to override this file:

> /var/www/openatrium/profiles/openatrium/modules/apps/oa\_home/oa-home-default.tpl.php

From my subthem wich is located at:

> /var/www/openatrium/sites/all/themes/my\_radix/

The subtheme is working fine, but I need to override some .tpl.php files that are not part of the parent theme. How can I do that? Where do I copy them? How do I tell Drupal to use the new files?

# Answer
Copy file from your module folder: `/var/www/openatrium/profiles/openatrium/modules/apps/oa_home/oa-home-default.tpl.php` and paste this to your subtheme in following path : `/var/www/openatrium/sites/all/themes/my_radix/templates/oa-home-default.tpl.php`

open this file and write something like this somewhere under php tags

```
 drupal_set_message('in new file');

```

go to `admin/config/development/performance/` and clear all cache. Now when you visit to the page where the template is getting rendered, you'll see the message.
> 2 votes

# Answer
You would just need to copy that module tpl.php file into your sub-theme's folder. You can just place it in the root directory of your sub-theme or inside a folder named "templates" to be cleaner on your file structure.

Drupal looks for any tpl.php overrides and in that process, it will use the tpl.php file which is in your sub-theme.
> 1 votes

---
Tags: theming
---


# Question
Title: Preventing a menu item from being pressed twice
I have a menu item that shows up on one of my nodes and when pressed it will trigger a somewhat long process. I would like to make it so that the user is not tempted to press the menu button again but I can't quite figure out how to do that. Is there a good way to put an overlay over the Drupal window to explain that the process will take some time and prevent another click? If not, would it be possible to show an alert dialog from the menu callback, warning the user this will take some time.

# Answer
> 1 votes
For long tasks you should use Drupal's Batch API. It takes a bit to learn, but has these benefits.

* The user will be taken to a separate page with a progress bar.
* You can display a custom message explaining what you are doing.
* If you can break your task into discrete chunks that can be performed in separate requests that will ensure that you won't run into any php timeout issues and the users will see their progress.

For example, during Drupal setup you see the following batch process:

# Answer
> 0 votes
This module is matching your requirement https://www.drupal.org/project/jquery\_loadinganimation.

---
Tags: 7, routes
---


# Question
Title: How would I insert one item into the user-edit page with templates?
I'm looking to insert a button into the user edit page. I've seen examples of how to edit the entirety of the user-edit page, but I want to keep everything intact and only make one small change.

Is it possible to do this without building the entire user-edit page all over again from scratch?

# Answer
> 2 votes
Although you could add a button into the template, this is done better with the forms api using a custom module. You can use hook\_form\_FORM\_ID\_alter to alter the user\_profile\_form and only make the small change you want while leaving the rest of the form untouched.

As an example, you could add a button "My cool action" to the use profile form with the following code. You just need to replace MODULE with the actual name of the module you put it in.

```
function MODULE_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    $form['actions']['newaction'] = array(
        '#type' => 'submit',
        '#value' => 'My cool action'
    );
    $form['actions']['newaction']['#submit'][] = 'my_newaction_callback';
}

function my_newaction_callback($form, $form_state)
{
    // this function is called when your button is pressed
    // do whatever you want here.
}

```

**Update #2**

You could place the button in the middle or top of the page using the following code and figuring out which weight places it where you want. Try a weight of 0 to have it near the middle.

```
$form['newaction'] = array(
    '#type' => 'submit',
    '#value' => 'My cool action',
    '#weight' => -3,
    '#submit' => ['my_newaction_callback']
);

```

---
Tags: theming, users
---


# Question
Title: What are recommended filters for using Pagespeed along with Drupal 7 (and Advagg enabled)?
We are planning to integrate Google Pagespeed module in our Drupal 7 site which is already using Advanced for CSS/JS Aggregation (Advagg).

Based on the inputs at https://www.drupal.org/node/2182289#comment-8421621 , it seems that Pagespeed CSS/JS filters are not needed since the same job is done by Advagg. Pagespeed has other useful filters for image optimization and inlining critical css.

**My question**: If someone is using Pagespeed along with Drupal and Advagg, can you share the Pagespeed filters that you are currently using or would recommend? If you are using Pagespeed with Drupal but without Advagg, please share your filter recommendations.

I have been searching extensively on this topic but couldn't find much practical information on using Pagespeed along with Drupal.

# Answer
Every site is different. I recommend extensive testing. http://www.webpagetest.org/ is one of the better sites for testing the frontend and seeing what options are best for you're site. Be sure to test more than just the frontpage & look at the connection view; using the bundler you can adjust this a little bit, try a bundle of 1 or even 10. Point is you'll need to experiment to get the best results. The modifier has lots of things you can do to tweak things; deferring the js is one of the better options in my opinion.

I've heard that google pagespeed has a +-20% difference; it works better or worse depending on various factors. Give it a try and be sure to test!

Work on inline css is being done btw: https://www.drupal.org/project/css\_delivery
> 1 votes

---
Tags: performance
---


# Question
Title: Views/Block: Only display if node field has a value
I've created a Block in Views. I only want this Block to display if a boolean field on the node is ticked. The View itself should only display content that relates to the node. How can I do this?

---

When displaying content in Views that relates to a node, you can normally use "Context Filters ID: Node". This would allow a View to take over a node. But it only seems to work in the Page display of the View and not the Block display.

I now I can use modules such as Rules, Panels or Node Fields Block to achieve this. But those are quite big modules and I only want to use it for a small thing on my site, so I was hoping their might be some solutions that can be done without any extra modules.

# Answer
> 1 votes
This should work in Views for blocks as well if you choose "Content: Nid" under "Contextual filters" and then add that boolean field as a "Filter criteria".

1. Choose Content: Nid as contextual filter.
2. Choose Provide default value
3. Choose Content ID from URL as type of cont. filter.
4. Choose that boolean field's value under Filter criteria.

When you're creating a view, under "Show" choose Content.

# Answer
> 1 votes
The context module lets you conditionally display blocks on pages. context\_entity\_field then would let you set a condition based on the boolean field in your node.

---
Tags: views, theming, blocks
---


# Question
Title: How to sync a Drupal calendar with an iphone/ipad Calendar?
Is there a way for us to sync our Drupal calendar to an iphone/ipad calendar?

# Answer
Yes, with https://www.drupal.org/project/date\_ical you can create an ical feed display in views.
> 1 votes

# Answer
The Date iCal module can be used for syncing a Drupal calendar in **both directions**. Some more details about it (from its project page):

> ... your one-stop shop for iCal support in Drupal. It provides a plugin for Views to enable exporting your site's calendar as an iCal feed, and a plugin for Feeds to enable importing external iCal feeds into your site's calendar.
>
> Any entity which contains a Date field can be utilized by Date iCal for import and export of iCal feeds.

So it provides:

* a plugin for the Views module to enable **exporting** a Drupal calendar as an iCal feed.
* a plugin for the Feeds module to enable **importing** external iCal feeds into a Drupal calendar.
> 2 votes

---
Tags: 7, importing-exporting, datetime
---


title: How to ajaxify simplenews module?

text:
# Question
Title: How to ajaxify simplenews module?
I have installed and enabled the simplenews module and I have a newsletter subscribtion block in my website frontpage now. I would ajaxify the subscribe's button in that block so I googled many websites about that, but I couldn't find any answer about 'How to ajaxify simplenews subscribtion form in drupal 7, any suggestion?

# Answer
> 1 votes
I don't know if you found your answer but I had the same problem and found a solution :

In a `hook_form_alter`

```
  if ($form_id == 'simplenews_block_form_' . variable_get('simplenews_id', 23)) {
    $form['submit']['#ajax'] = array(
      'callback' => 'simplenews_block_form_ajax_submit',
      'wrapper' => 'block-simplenews-' . variable_get('simplenews_id', 23),
      'method' => 'replace',
      'effect' => 'fade',
      'progress' => array('type' => 'none'),
    );
    $form['submit']['#executes_submit_callback'] = TRUE;
    unset($form['#submit']);
    unset($form['#validate']);
  }

```

And then in the ajax submit

```
/**
 * Ajax callback to reload the image field
 */
function simplenews_block_form_ajax_submit($form, $form_state) {
  $return = '<div id="block-simplenews-23" class="block block-simplenews first odd">';
  $return .= '<h2 class="block__title block-title">' . t('Newsletter') . '</h2>';
  $return .= render($form);
  $return .= '</div>';
  if (!valid_email_address($form_state['values']['mail'])) {
    $return .= '<section class="errors-primal">' . t('The e-mail address is not valid.') . '</section>';
    return $return;
  }
  else {
    if (module_exists('simplenews')) {
      module_load_include('inc', 'simplenews', 'views/simplenews.subscription');
      $tid = $form['#tid'];
      $account = simplenews_load_user_by_mail($form_state['values']['mail']);
      $confirm = simplenews_require_double_opt_in($tid, $account);
      $subscription = simplenews_subscribe_user($form_state['values']['mail'], $tid, $confirm, 'website');
      $return .= '<section class="confirm-primal">' . t('You have been subscribed.') . '</section>';
      return $return;
    }
  }
}

```

This will do a simple registration to the database in AJAX. You can adapt depending on what you exactly need.

# Answer
> 1 votes
Additionally to pbonnefoi answer, submit can be simpler:

```
/**
 * Ajax callback for simplenews
 */
function CUSTOMMODULE_simplenews_form_ajax_submit($form, &$form_state) {
  if (!valid_email_address($form_state['values']['mail'])) {
    drupal_set_message(t('The e-mail address %mail is not valid.', array('%mail' => $form_state['values']['mail'])), 'error');
  }
  else {
    module_load_include('inc', 'simplenews', 'views/simplenews.subscription');
    simplenews_block_form_submit($form, $form_state);
  }
  return render($form);
}

```

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


title: Search a product - Search API Module

text:
# Question
Title: Search a product - Search API Module
I'm creating a e-commerce website, with a type of content "Products". I'm using Search API to be able to have Facets filters on my views. I linked the type of content "Products" to the search API. So i have different facets filers available. Everything is working perfectly.

Now I would to be able to search a product. On my search results page i can have my facets filters.

So I tried 2 options :

1) I found this tutorial and I tried but it didn't work

2) I tried the Search API Pages module and I have the same problem, nothing is working. When I search something, it found nothing. I tried to find out some tutorials to see if I miss something.

I tried to find out some tutorials about how to use Search API Pages module, but I found nothing useful.

I found this previous post which is similar as my problem :

But that doesn't help me either

Does anyone have an idea ?

Edit : I'm not using Apache Solr on my server

# Answer
I solved my problem.

Well i don't if what i did was the issue but it's working so ^^

I went in the parameters of the Search API Module. I went on the tab "Filters", in the "Precesseurs" part i just activated this 2 things : HTML filter Tokenizer I re-indexed everything and by magic it's working.
> 1 votes

---
Tags: 7, commerce, search, views
---


title: Drupal trip and hotel reservation

text:
# Question
Title: Drupal trip and hotel reservation
Is there a Drupal module that would allow you to use custom tables for making hotel and trip bookings and reservations? In my project, I have to use a specific API from a third party tour operator for gathering data for the offers, and displaying them. Thank you in advance.

# Answer
Look for booking / reservation modules. There are some that would be a good starting point for you.

Rooms, Simple Reservation, Easy Booking and Open Hotel are just a few worth trying.
> 0 votes

---
Tags: bookings
---


# Question
Title: AJAX populated filter breaks when Views Dependant Filter module added
I have a view with two exposed filters and I want to make the second filter dependant on the first in 2 ways

1. A user has to select an option from the first filter before the second is available to use. Achieved using Views Dependant Filters
2. The options within the second filter are dynamically updated so only combinations that will return results are presented. Achieved following this Views AJAX Dynamic Dependent Exposed Filters tutorial and creating a custom module.

I have an example of this view available on this development server.

Select an option from filter one and the second filter becomes available and it's options are updated as expected.

The problem occurs when you select a second different option from the first filter. The AJAX does not fire and the second filter options are not updated.

Code for updating filter two with AJAX is below, but I believe the problem lies on the client side.

I appreciate your suggestions.

```
function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
    if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {

        $form['#after_build'][] = '_sort_alphabetically';

        if(!empty($form_state['values'])) {
            $form_state['input'] = array_merge($form_state['input'], $form_state['values']);
        }

        $selectedCommodity = $form_state['input']['field_commodity_tid'];
        $form['field_keywords_tid']['#options'] = _get_associative_array_from_view(
            'annotated_bibliography_dependant_keywords', // view id
            'default', // view display id
            'taxonomy_term_data_field_data_field_keywords_tid', // key field id
            'taxonomy_term_data_field_data_field_keywords_name',
            $selectedCommodity // term id of the selected shape
            );
        $form['field_commodity_tid']['#ajax'] = array(
            'callback' => '_update_keywords_callback',
            'wrapper' => 'keywords_wrapper',
            );
        $form['field_commodity_tid']['#ajax']['progress']['type'] = 'throbber';
        $form['field_commodity_tid']['#ajax']['progress']['message'] = 'Updating keywords';
        $form['field_keywords_tid']['#prefix'] = '<div id="keywords_wrapper">';
        $form['field_keywords_tid']['#suffix'] = '</div>';
    }
}

function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
                $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}

function _update_keywords_callback($form, $form_state) {
    return $form['field_keywords_tid'];
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $keyFieldID, $valueFieldID, $contextualFilter){
    $associativeArray = array();
    $associativeArray['All'] = t('- Any -');
    $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);
    foreach($viewResults as $viewRow) {
        $associativeArray[$viewRow->$keyFieldID] = $viewRow->$valueFieldID;
    }
    return $associativeArray;
}

```

# Answer
> 1 votes
I was able to make the second filter dependant in both ways without the need for Views Dependant Filters by adding additional logic to my `hook_form_views_exposed_form_alter`.

```
if($form_state['input']['field_commodity_tid'] === 'All')
    $form['field_keywords_tid']['#disabled'] = 1;
}

```

Here is the entire working code:

```
function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
    if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {

        $form['#after_build'][] = '_sort_alphabetically';

        if(!empty($form_state['values'])) {
            $form_state['input'] = array_merge($form_state['input'], $form_state['values']);
        }

        $selectedCommodity = $form_state['input']['field_commodity_tid'];
        $form['field_keywords_tid']['#options'] = _get_associative_array_from_view(
            'annotated_bibliography_dependant_keywords', // view id
            'default', // view display id
            'taxonomy_term_data_field_data_field_keywords_tid', // key field id
            'taxonomy_term_data_field_data_field_keywords_name',
            $selectedCommodity // term id of the selected shape
            );
        $form['field_commodity_tid']['#ajax'] = array(
            'callback' => '_update_keywords_callback',
            'wrapper' => 'keywords_wrapper',
            );
        $form['field_commodity_tid']['#ajax']['progress']['type'] = 'throbber';
        $form['field_commodity_tid']['#ajax']['progress']['message'] = 'Updating keywords';
        $form['field_keywords_tid']['#prefix'] = '<div id="keywords_wrapper">';
        $form['field_keywords_tid']['#suffix'] = '</div>';

        if($form_state['input']['field_commodity_tid'] === 'All')
            $form['field_keywords_tid']['#disabled'] = 1;
        }
}

function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
                $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}

function _update_keywords_callback($form, $form_state) {
    return $form['field_keywords_tid'];
}

function _get_associative_array_from_view($viewID, $viewDisplayID, $keyFieldID, $valueFieldID, $contextualFilter){
    $associativeArray = array();
    $associativeArray['All'] = t('- Any -');
    $viewResults = views_get_view_result($viewID, $viewDisplayID, $contextualFilter);
    foreach($viewResults as $viewRow) {
        $associativeArray[$viewRow->$keyFieldID] = $viewRow->$valueFieldID;
    }
    return $associativeArray;
}

```

---
Tags: ajax, views
---


# Question
Title: How to give class name to the text field in drupal
I am new to drupal and I have a problem in drupal text-box.

Question : how to give a class for text box?

my html :

```
<input type="text" name="uname" class="uclass" id="uid">

```

i want the same in drupal

## **My code is** :

```
function my_module_my_form($form_state) {

// This is the first form element. It's a textfield with a label, "Name"

$form['name'] = array(

'#type'  => 'textfield',
                    '#title' => t('Enter Your Name'),
                    '#value' => t('Enter user name'),
                    '#name'  => 'uname',
                    '#id'    => 'uid',
                    '#class' => 'uclass',
                    '#maxlength' => 5
                   );
return $form;

}

```

Note: through inspect element , i find the class name is "form-text", but actually my class name is uclass, It is not taking, can one help me.

# Answer
Additional HTML attributes, such as 'class', can be added using the '#attributes' property.

```
function my_module_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
   $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Enter Your Name'),
      '#weight' => -10,
      '#attributes' => array('class' => array('uclass')),
    );
 }

```

Please note that when you alter existing form elements (e.g. via hook\_form\_alter()), you probably want to add (attributes) to the existing array rather than writing over it.

Checkout Form API of Drupal 7 to get more detail.
> 1 votes

---
Tags: views, theming
---


# Question
Title: How to remember the selected foo before and after a registration process?
I have a view with 50 objects available for anonymous members.

* I the user clicks "Yes, i want to see more of this nice foo" he should register himself with only a email and/or password or even only a email is enough. Then a rule is needed to run and adds the role of member to the user.
* The member should now be returned to the selected foo/row.

How to remember the selected foo before starting the registration process starts so I can redirect the user the foo correctly?

Any suggestions great appreciation.

# Answer
I tried a lot of things with logintoboggan but the unauthenticaed role makes it diffecult for other modules to make well. So if you try to establish this with logintoboggan you are implicied chosing for modules which are only compatible with the adjustment of the login system. Something I do not prefer.

I solved it with the following modules:

```
Email_registration          fo the username is not needed anymore
GenPas                      for generating a auto password and direct login
Persistent login            for login in for a long time
User email verification     for verify the email
nocurrent_pass              for remove password edit’s profile
email_confirm               when user changes email

```

When a anonymous gets on the site reqistrating is posssible with only email. With a rule you give the person a role. After that you can do what you like. If the person does not have a role yet and clicks on the link for premium content, you just append the unique id to the registration url and after registration a redirect can pick this up, the person is then verified with a first pre member role.

You send all pre member roles an email with user email verification. If this is verified u can use a rule to upgrade the role. You now have a full registrated process without have the disadvanced of logintobboggan concept and in line with tha fact that no passwords are send by email.
> 0 votes

---
Tags: users
---


# Question
Title: hybridauth redirection to an emailed link after success login
Im using hybridauth to let users login from different social media websites ... I send emails manually to some users with an link to edit specific nodes (for example http://example.com/node/444/edit?parma1=val1&param2=val2). At that moment the user is automatically redirected to a page to choose a social media he want to login with. Im using hook\_init for this :

```
function MYMODULE_init(){
  if($node->type == 'type' && other conditions){
    drupal_goto('link_to_hybridauth_login_page');
  }
}

```

Now I want that user to be automatically redirected to that link sent via email after success login via hybridauth ( I tried to add destination query inside drupal\_goto but not working.)

how can I do this redirection ?

Thanks in advance.

# Answer
> 0 votes
How did you try to add the 'destination' query? It should be something like this:

```
$query_array = array('param1' => 'value1', 'destination' => 'original_path');
$options = array(
  'query' => query_array,
);
drupal_goto('link_to_hybridauth_login_page', $options);

```

Basically, it's important that the destination is passed as part of the $options\['query'\].

If that doesn't work, try and add your own hook\_user\_login(), to pick up the 'destination' (or whatever parameter you want to use for the original URL, and redirect the user accordingly). Like:

```
if (isset($_GET['destination'])) {
  drupal_goto($_GET['destination']);
}

```

You can see an example implementation of hook\_user\_login in the user\_homepage module code: http://cgit.drupalcode.org/user\_homepage/tree/user\_homepage.module?id=6803e00

Hope this helps with your problem.

**EDIT**: The hook\_user\_login() is meant to be something additional to the hook\_init() logic you were trying, but not to replace it. Thought I'd just clarify that =).

**EDIT 2**: Ok, So if I'm getting the problem right, you need to get not only the 'node/xxx/edit' part of the URL, which you have already sorted (right?) but you need to also get all the params of the incoming URL.

Basically, you need to use drupal\_get\_query\_parameters() for that. So you could assemble the $options array like this:

```
  $current_query_params = drupal_get_query_parameters();
  // Pick up URL and treat params as you need, and prepare query array with
  // the 'destination' desired, assembled with data from $current_query_params.
  $new_query_array = array();
  $options = array(
    'query' => $new_query_array,
  );

```

Hope I'm getting it right now. The linked drupal code from user\_homepage uses these functions for a very similar scenario. Look at *user\_homepage\_build\_homepage\_path\_from\_request()* and *user\_homepage\_user\_login()* functions.

---
Tags: 7, authentication-authorization
---


# Question
Title: Using exposed filters as part of the rendered page's title
I'm using exposed filters in a Drupal 7 site. I'd like to make the **selected items** from those filters part of the titles. Is there a way I can get the text value of those selected filters and use that text as part of the title?

Settings are as allowed:

I'm also using Better Exposed Filters in this view.

# Answer
> 1 votes
A also have this question. But now I'm trying this module: https://drupal.org/project/exposed\_filter\_data? And this module is not working for me.

I found this:

```
/**
 * THEME_PREPROCESS_VIEWS_VIEW
 * @param type $vars
 *
 */
function MYTHEME_preprocess_views_view(&$vars) {
  if ($vars['view']->name == 'viewName') {
    // get var from GET
    $obj_type = $_GET['obj_type'];
    if (isset($obj_type)) {
      // obj_type is the taxonomy term, get taxonomy term name
      $tax_name=taxonomy_term_load($obj_type)->name;
      // if taxonomy term have parents
      $tax_parent = taxonomy_get_parents_all($obj_type);
      if (isset($tax_parent[1])) {
        // add parent name to taxonomy term name
        $tax_name =  $tax_parent[1]->name . ', ' . $tax_name;
      }
      //update title
      $vars['view']->build_info['title'] = $tax_name;
    }
}

```

And this is working!

# Answer
> 0 votes
(Yes, I know this is an old question, but better late than never?)

If you're wanting to use the exposed filter settings as part of the `<title>` tag, you can do something similar to:

```
function hook_process_html(&$variables) {
  if (!empty($variables['head_title']) && $uri = request_uri()) {
    $variables['head_title'] .= " ($uri)";
  }
}

```

If you were wanting to change the view title as it appears on the page, it's best done in `preprocess_views_view()` as mentioned by VVS.

---
Tags: views
---


# Question
Title: Strict warning and views - site not working
I am using drupal 6 and after moving to php 5.4 or 5.5 from 5.3, I am getting error `"strict warning: Declaration of views_plugin_style_default::options() should be compatible with views_object::options() in.... views_plugin_style_default.inc on line 24."`
I tried updating views but does not help. It is not just about warning - Views do not work at all. What can be done in this case? Besides switching to 7.x - it is not an option for me. Thank you.

# Answer
> 0 votes
There is a patch, it can be found here: https://www.drupal.org/node/893128

I used this one: https://www.drupal.org/files/issues/893128-61.views\_.strict-warnings-method-declarations-php-5-4.patch but it did not fix everything. In the end I fixed some items manually similar to what is done in the patch where I replace the function arguments that are the problem from $argument to &$argument. (or sometimes the other way around).

Did you already try the latest dev version, because a patch for the issue I mentioned was committed recently, but I don't think a new version was released since then.

---
Tags: views, 6
---


title: Base path and user picture uploading

text:
# Question
Title: Base path and user picture uploading
So I recently migrated my site between servers. I think this is causing some issue with the base path of Drupal, which in turn affects the image upload path when a user tries to upload an image to his/her profile.

So, before migrating, some data was already uploaded to some of the users and their images and paths work just fine. The path is as follows for example:

```
www.example.com/sites/default/files/styles/thumbnail/public/pictures/picture-125-1377507580.jpg

```

But now, when I'm trying to add new users and when I upload new pictures, the image doesn't get uploaded and the path to the image is as follows:

```
www.example.com/new/?q=sites/default/files/styles/thumbnail/public/pictures/picture-125-1377507580.jpg

```

Why is this happening? How do I change the Drupal base path? Thanks

# Answer
Firstly, it seems that the **new server does not allow clean urls** or it needs some configuration. Check the documentation on Drupal.org: Step 6: Configure clean URLs

Then, clean all caches and run cron. You will then see all image paths as /new/sites/sites/default/files/...

That's because the new site is set on folder ROOT/new or am I wrong? So there is no error, you have to **set the domain to look at this subfolder**.

If you don't have permissions to do this in your hosting or there are no options like Add-On domains you can follow the discussion at **Drupal installed in subdirectory but made to appear in root** according to your hosting enviiroment.
> 0 votes

# Answer
First of all mention `$base_url = 'http://example.com';` in settings.php file. Then provide permission to your files folder. It should be at sites/default/files

Provide permissions:

```
cd /var/www/drupal_root/sites/default/
sudo chmod 777 -R files

```

Hope this helps
> -1 votes

---
Tags: 7, media, uri
---


# Question
Title: Is it dangerous to call a function that deletes nodes based on criteria while a cron job is running that imports them
I have custom module that performs a dbquery on a button click that deletes nodes that fit a certain criteria. Is it dangerous that I also occasionally run a cron job that imports nodes that fit this criteria? If I ran both at the same time could something break?

# Answer
> 1 votes
Depends on the way you import:

1. If you delete the nodes on some criteria and import the nodes as new nodes (`$node->is_new = TRUE`), this shouldn't be a problem.
2. If you are updating the existing nodes while importing and deleting the nodes at the same time, then there could be issues.

This is because the `node_save()` function internally calls drupal\_write\_record, which creates a node with an incremental nid value if the `$node->is_new` is set to `TRUE`. Or updates the exiting nodes if you are importing.

---
Tags: 7, cron
---


# Question
Title: Using Theme() to output html/javascript in user edit
I have a module that outputs a button to the user edit page. I use the form\_user\_profile\_form\_alter to append the button but I want to add html and javascript after it. I saw that the theme() function can do this but my attempt does not add any html. Also I saw that the theme needs two parameters but I do not know what the 1st parameter is supposed to be. I was only following examples.

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

  $form['actions']['myButton'] = array(
    '#type' => 'submit',
    '#value' => 'Click Here'
  );
  $form['actions']['myButton']['#submit'][] = 'myModule_callback';

  return $form;
}

```

Here is my callback function

```
function artsci_pubmed_biblio_callback($form,$form_state){
  drupal_set_message('Button Clicked');
  return theme('box', '<li>Item 1</li><li>Item 2</li><li>Item 3</li>');
}

```

# Answer
If you just want to add some markup and Javascript, you don't need a submit callback because that's for handling form submissions.

**Requirement 1: Add html**

Options:

1. #prefix and/or #suffix form element attributes. (If just simple short html this will do)
2. #theme to use you custom theme function declared hook\_theme and place your markup in your tpl.php file. (If too much markup and want your module/theme to be clean)

**Requirement 2: Add javascript**

You can use #attached form/form element attribute

In the links, there are example codes that you can follow.
> 2 votes

---
Tags: 7, forms, theming
---


# Question
Title: How to update one select element via Ajax when using node_add
I have just created a new content type called pieza\_musical. What I just want to do is update one select element via Ajax depending on another select choice, a dependant select.

I'm altering the form\_node\_add using hook\_form\_alter to inject the #ajax element and replace in the wrapper the previous select rendered by default in the content type.

Everything is working except when it comes to save. I think, due I'm replacing the select via $ajax\['method'\] = replace, maybe some token is missing and the content type can't be saved.

It show these error messages:

> An illegal choice has been detected. Please contact the site administrator.
> Género: illegal value.

This is my simple code:

```
function seven_form_pieza_musical_node_form_alter(&$form, &$form_state, $form_id) {
  $generos = taxonomy_get_tree(2,0,1);
  $values_generos = array();
  foreach ($generos as $genero) {
    $values_generos[$genero->tid] = $genero->name;
  }

  $form['field_genero']['und']['#options'] = $values_generos;
  // adds ajax
  $form['field_genero']['und']['#ajax'] =  array(
     'event' => 'change',
     'wrapper' => 'edit-field-subgenero-und',
     'callback' => 'subgenero_ajax_callback',
  );
}

function subgenero_ajax_callback($form, &$form_state) {
  $generoId = $form_state['values']['field_genero']['und'][0]['value'];

  $cat = taxonomy_term_load($generoId);
  $vid = $cat->vid;

  $generos = taxonomy_get_tree($vid,$generoId,1);

  $options = array();
  foreach ($generos as $genero) {
    $options[$genero->tid] = $genero->name;
  }
  $form['field_subgenero_ajax'] = array(
    '#type' => 'select',
    '#id' => 'edit-field-subgenero-und',
    '#required' => TRUE,
    '#name' => 'field_subgenero[und]',
    '#options' => $options,
  );
  return $form['field_subgenero_ajax'];
}

```
* Is it possible to make this is a content type?
* Should I create a new entity just for this little purpose?
* Should I create a custom field?

# Answer
Since you're dealing with fields created in by Drupal admin, You may want to check the option values you replaced in the fields that it matches in the field settings.

\[EDITED\]

Try the Hierarchical Select module. In the page, it also supports Taxonomies.
> 0 votes

---
Tags: forms, ajax
---


# Question
Title: How to find hooks being called by a Drupal page?
I am looking at module code, and this is one of my first time working with Drupal modules. How can I find which hooks are being called by the page that I am working on at the moment? I saw this suggestion, but I don't want to hack core like it suggests. I think I might be able to do it with the devel module, but I am not sure how.

# Answer
> 0 votes
Use hook\_module\_implements\_alter and do the drupal set message in here. You'll need to use a FAKE cache for the cache\_bootstrap bin.

In your settings.php

```
if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
$conf['cache_class_cache_bootstrap'] = 'DrupalFakeCache';

```

I will say that hacking core in this case is the preferred way to do this. The person who wrote that linked article is a core maintainer; so they know what there talking about. Using hook\_module\_implements\_alter with a fake cache backend will only make this fire on the first run of that hook. Additional calls to the hook will not be caught due to the static cache. Not using the static cache would require hacking core in this case.

---
Tags: hooks
---


title: Importing large datasets via HTTP

text:
# Question
Title: Importing large datasets via HTTP
I'm having trouble importing a very large dataset with feeds. It's about 8mb of text in XML format. It imports impossibly slow (I started it about a month ago and it's still not finished).

However, if I run the exact same importer with the same file I upload from my computer, it runs in about two minutes.

The thing is, I need to check the stock of my products from my supplier through this file every hour. Most of the data is irrelevant other than stock info.

Are there any good alternatives to do what I'm trying to do? (Drupal Commerce) I've been thinking that if I have another module retrieve the file from my supplier every hour, then I could just point feeds to the file on my own server. However, I'm having trouble finding a module that does that file retrieve.

Any ideas?

# Answer
A month-long operation is a good sign that something went wrong? How did you launch the import? If you used a Web GUI, the operation probably timed-out without updating the UI. I doubt your webserver is configured to allow a month-long HTTP request processing. Are you able to connect to the server to check if a PHP process is indeed still running?

Instead of looking for a module to download the imported file every hour, you could rely on a simple cron job using curl or wget to download the file:

```
0 * * * * wget http://my.supplier.com/products.xml -a /var/log/supplier-products-download.log --no-verbose -O /some/path/products.xml

```

If I remember correctly, the default XML parser for Feeds uses SimpleXML. It will load the complete XML tree in memory beofore processing it. For a 8Mb file this could start to be an issue (depending on your PHP memory configuration). A beast approach would be to write your own Feed parser (as a Feeds plugin) using the XMLReader API which support a streaming mode (ie. data are processed when reading the file).
> 0 votes

# Answer
Here is a simple drupal module that downloads one file using php. I call it feeds\_downloader and this is the **feeds\_downloader.module**.

I usually run the downloader using elysia\_cron or ultimate\_cron.

In my case I download an array of files and this module is a bit different (contains a loop). And they are of 1GB size or more.

```
<?php

/**
 * Implements hook_cron()
 * Create a cron job
 */
function feeds_downloader_cron() {
  // Get last cron run
  $last_run = variable_get('feeds_downloader_last_cron', 0);

  // Default interval every 20 hrs.
  $interval = variable_get('feeds_downloader_interval', 60 * 60 * 20);

  // Run cron if it is time to run
  if(time() - $last_run > $interval){
    variable_set('feeds_downloader_last_cron', time());

    // Run the download function

    // Where to save the file
    $path = "public://feeds";
    // Where to download the file from
    $url = "http://example.com/my_file.xml";
    // The local filename that will be saved
    $name = "my_file.xml";
    feeds_downloader_curl_list($path, $url, $name);
  }
}

/**
 * A function to download files using curl.
 * @param string $path
 * @param string $url
 * @param string $name
 */
function feeds_downloader_curl_list($path = "public://", $url, $name){
  if ($url == "" || $name == ""){
    return;
  }
  // Get real path of $path
  $path = drupal_realpath($path);

  // Local file of the file to be saved
  $filename = $path . "/" . $name;

  // Optional, for large files. Disable time limit
  set_time_limit(0);

  // Create file
  $fp = fopen($filename, "w+");

  // Initialize curl
  $ch = curl_init();
  // Add url
  curl_setopt($ch, CURLOPT_URL, $source);
  // Allow redirects
  //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_POSTREDIR, 3);
  // Set timeout
  curl_setopt($ch, CURLOPT_TIMEOUT, 0);
  // Write curl response to file
  curl_setopt($ch, CURLOPT_FILE, $fp);

  // Run curl - download
  $results = curl_exec($ch);

  // Get info about download
  $info = curl_getinfo($ch);
  $message = t("File %file with size: %size_download MB downloaded on
    %date from %url");
  $message_variables = array(
    '%url' => $info['url'],
    '%size_download' => $info['size_download']/1000000,
    '%date' => format_date($info['filetime'], $type = 'medium'),
    '%file' => $name,
  );

  // Debug download if there is no error
  if(!curl_errno($ch)) {
    // Create a watchdog message
    watchdog("feeds_downloader", $message, $message_variables, WATCHDOG_INFO);
  } else {
    watchdog("feeds_downloader", $message, $message_variables, WATCHDOG_ERROR);
  }

  // Close curl function
  curl_close($ch);

  // Close file
  fclose($fp);
}

```
> 0 votes

---
Tags: feeds
---


# Question
Title: How to implement a user profile attribute to indicate "Where did you hear about us"?
I want to add a "Where did you hear about us?" checkbox list to user profiles. There will be 6 radio buttons and an "Other" textfield.

There's no need for a taxonomy vocabulary, which was my first thought. I also thought about using Webform, but that feels like overkill and I think I'd have to do more work to link the form to the user.

Really, I just want to view the user profile and say "*Oh look, they found out about us from twitter ...*". So what are good techniques/approaches to implement this?

# Answer
> 0 votes
This question does not say if it is about D6 or D7, but how about just a pull-down selection list (could be a checkbox as well if you prefer)? Similar to what you can see on this registration page, around the middle of the page (still a D6 site, D7 should be similar).

If it makes sense, I'd be happy to further enhance my answer to include the details of how I implemented that (piece of cake).

**Note**: please do not submit a real registration request if you checkout the link I added here ... unless you really want to sign up there (which requires prior approval ... ).

---
Tags: webforms, users
---


# Question
Title: Get more drupal.org project usage information
Choosing a Drupal module has become an art-form. Deciding if the module is active, used frequently, growing in usage, etc. is important.

I'm a site builder. https://drupal.org/project/usage has lot's of good information but interested in levaring the view. What kind of URL arguments are supported? I know that: `?sort=asc` will work, but can I filter by category, change time range or make a more sophisticated query? I can add https://drupal.org/project/usage/webform and get more granular on a project basis but would like more control and to understand the URL arguments supported.

I didn't find any Project documents that were relevant.

# Answer
The usage page comes from project\_usage\_overview(); it's not a View. The only parameters are those provided by Drupal's *tablesort API*, "sort" and "order".

`?sort=asc` you've already discovered, and the other parameter changes the sort column (`?order=Project` would sort by project name).
> 6 votes

# Answer
Great question! I'm struggling with the same kind of question, but then limited to any of the charting modules available in Drupal (or at least that I'm aware of ...).

The various "features" available/supported in any such module is, IMHO, only 1 of the criteria to decide for a specific module. But also (maybe even more?) important I think is what is in the very first paragraph of the question in the OP. Therefor I started to use the "maintenance scorecards". Even though I started using it for "charting" modules, I also use it now for any other types of modules I need to decide about.

Without trying to highjack the original question here: I'm now trying to find a way to use something like JSON to periodically (like weekly) go get (retrieve) all sorts of data included somewhere on drupal.org ...

Something that might help for such JSON data is located at https://www.drupal.org/node/669910#comment-7432476 , which is includes a ZIP file with content like so:

> a feature that provides some data for Drupal.org. This will meet the requirements for security.drupal.org, it does not meet all the requirements listed above. The data is in JSON format. It will require that views\_datasource be installed.
> 1 votes

---
Tags: uri, community-official-site
---


# Question
Title: Custom form handler not found (call_user_func_array() error)
Currently on Drupal 8 beta 7.

I'm trying to build a form with separate "submit" and "cancel" buttons. The cancel button has some separate cleanup work to do. I've tried to follow the documentation and examples to create a custom form handler to manage this. Here's my actions block from my form.

```
    $form['actions']['#type'] = 'actions';
    $form['actions']['cancel'] = array(
      '#type' => 'submit',
      '#value' => 'Cancel',
      '#button_type' => 'cancel',
      '#submit' => array('uso_cancelForm'),
    );
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Submit',
      '#button_type' => 'primary',
    );

```

Then, in my form object, I define the custom handler.

```
public function uso_cancelForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message("Editing cancelled");
    // Handle state information here
}

```

However, pressing the cancel button has no effect, except to log an error:

> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'uso\_cancelForm' not found or invalid function name in Drupal\Core\Form\FormSubmitter-\>executeSubmitHandlers() (line 116 of /{redacted}/core/lib/Drupal/Core/Form/FormSubmitter.php).

So it looks like, for some reason, Drupal can't find my **uso\_cancelForm** function, which is sitting in the form object definition right next to **validateForm** and **submitForm**. The "Submit" button calls **submitForm** without a hitch.

What am I doing wrong here?

I've figured out that if I move my custom **uso\_cancelForm** function into my .module file, Drupal finds and runs it, but this solution won't work as a long-term solution, because I need to use `$this` in the code that the cancel function executes.
So, clearly, my form's public functions aren't in scope when the button press is being handled, although the standard validateForm and submitForm functions are. I tried adding `include_once "src/Form/{my form filename}.php";` to my .module file, but this doesn't help.

Is there some other way I need to let Drupal know about this method, so that the FormSubmitter will know about it and call it?

# Answer
Use `'::uso_cancelForm'` or `[$this, 'uso_cancelForm']`.
> 4 votes

---
Tags: 8, forms
---


# Question
Title: Drush site-install and extra settings for the settings file?
We are developing a site with a make file, profile and drush-si.
Thus far it's great, but i cant find a way how to add some slightly more complex settings to the settings.php file. For the beginning, base\_url and second database would be totally enough :). Memcache and proxy are other candidates.

Or is this something that could be done in an installation profile ? Where ?

# Answer
> 1 votes
Checkout the post about Collecting and writing configuration settings to setting.php from an install profile.

It describes how a custom task was injected into the installation profile and then details how drupal\_rewrite\_settings() was used to inject the custom settings into settings.php.

---
Tags: drush
---


title: What is taxonomy/term/tid/*

text:
# Question
Title: What is taxonomy/term/tid/*
I'm first time seeing a link indexed by Google : taxonomy/term/10007/\* as in here.

What could be causing it?

I've already GlobalRedirect enabled, also not using the View "Taxonomy term" which emulates Drupal core's handling of taxonomy/term.

# Answer
> 1 votes
Removing the "\*" from the path *does* trigger the redirection to the right page.

It seems to me the "\*" is just confusing global redirect (maybe some setting not configured correctly in the module?), because the redirection is definitely not happening, and that might be the reason why google is indexing that.

I'd suggest double-checking the globalredirect settings in place.

# Answer
> 1 votes
The problem is your link rel="canonical" tag. It's setting the core taxonomy path in the href value.

link rel="canonical" tells search engines the canonical URL to use for search results. That needs to be fixed to resolve your indexing problem.

Are you use the metatag module? If so, some additional tweaks there should solve the problem.

# Answer
> 0 votes
Not sure but I guess enabling globalredirect module might solve your problem.

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


# Question
Title: Changing Default Text of Fivestar Rating Widget
My fivestar rating says 'no votes yet' when no one has yet voted on the node. How is it possible to change this text to say something else, like 'vote this item'?

I thought this would be a simple problem to solve but wasn't able to find the answer to this anywhere and it's not immediately apparent how this is done when configuring the tool.

# Answer
The String overrides make it easy to change that text or any other text in your Drupal site. Install the module, then visit /admin/config/regional/stringoverrides in your site and you can change the text as shown below.

Then when viewing the vote you'll see:
> 2 votes

---
Tags: rating
---


# Question
Title: Tying together creation of multiple content types in a form
I need to make a content creation form that ties in the creation of two different content types.

Imagine `garage` and `cars` as an example. There is a one-to-many relationship between `garage` and `cars`, so one `garage` can have 0 to many `cars`.

I've created the content types and established the relationship between them but I need to figure out how to best support the user in creating content. I think it is important that distinction between content types is more or less transparent to the user, so he could be creating his garage at one point, then later on come back to add cars. Or he could be creating a garage and adding two cars in one go. Or he could go in and create a car without even assigning a garage.

I imagine accomplishing this by having a form for adding garages and a form for adding cars, but near the end of the 'create garage' form I have the option of either assigning an existing car I have created earlier (probably using an autocomplete textfield) or load the 'create car' form in a modal window allowing to create a new car right before submitting the garage form (the relatioship will then be established right away).

My question is how to accomplish this best from an architectural point of view.

Should I write a completely custom module and maybe place it in a block with panels or could I get by simply by creating a hook that changes the content creation forms for cars and garages? Or maybe you know about a contrib module that fixes this for me out of the box?

Furthermore, I imagine the end result being soaked in asynchronous requests, allowing the form to be validated and saved asynchronously. For an early proof-of-concept I could live with "nested save buttons", though. I will most likely be using AngularJS for some of the realtime stuff. Should I look into exposing the content types as a REST service build and the entire page in AngularJS right away? (something I am planning to do further down the line anyway, but I also need to have something up and running quickly and I imagine a rewrite for Drupal 8 in a not too far future. So I would prefer not having to learn how to build services in Drupal 7).

# Answer
The Field Collection module is a quick and easy solution. It lets you nest entities within your content type as a field. So you could have a "Garage" Content Type which then has "Car" field of type (field collection) with "Number of values" set to unlimited.

At `/admin/structure/field-collections` you can add fields to this Car type.

On the Garage edit form you can add cars to your garage as shown below:

Then while viewing a Garage node, a user with sufficient permissions will see edit and add links which work just like you would expect. See below.

The downside with this approach is that since the Car's information is tied closely to a specific Garage, it's not easy to move a car from one garage to another or have one car in several garages, etc. Those use cases are possible, but you will have to write you own code however.
> 0 votes

---
Tags: forms, nodes
---


# Question
Title: How to change textformat of many nodes at once?
How to change textformat of many nodes at once,

module? drush? or script

**UPDATE** (sorry I was on the run at first edit)

I had imported hundred or more nodes I had to migrate from an old site. Did it via node\_export. The new site has a textformat with same name, but defined another way so I decided all nodes should be plain text .

I websearched a bit but could not found anything. So i thought there might by a module with VBO support for that?

# Answer
> 1 votes
In previous instances where this has happened to me, I've just updated the \*_format column in the field\_revision\_\* & field\_data\_\* tables, flushed the Drupal cache, and things worked without issue.

For example, if you're looking to change the nodes' body format for all imported nodes of type *my\_type* from *my\_format* to *plain\_text*, you could execute this query:

```
UPDATE field_data_body SET body_format = 'plain_text' WHERE entity_type = 'node' AND bundle = 'my_type' AND body_format = 'my_format';
UPDATE field_revision_body SET body_format = 'plain_text' WHERE entity_type = 'node' AND bundle = 'my_type' AND body_format = 'my_format';

```

**NOTE:** There's probably a better, programmatic way, than touching the database directly, but I've never seen any adverse effects from this method.

---
Tags: drush
---


# Question
Title: Paths to images are messed up in Vagrant
All the paths linking to modules, javascript, css are correct when I move a site locally and run in a vagrant environment. Yet, the image paths stored in the site come out wrong, so they are all borked.

The console in Chrome shows the paths to the images as skipping a folder. This is how the path looks: localhost/sites/default/files/img.jpg

This is how the path should look: localhost/sitename/sites/default/files/img.jpg

For some reason, Drupal in Vagrant looks for the sites folder in the localhost folder. I feel like something is wrong with the way apache is set up on my Vagrant installation. But I suppose it could be a number of things. Does anyone know?

# Answer
So I think I figured out that the solution to my problem involves updating the apache configuration for each site I run locally. My hosting service does this for me on the prod, but you can update it locally. Probably system admin 101 stuff: http://www.techmalaya.com/2008/06/09/apache-22-virtual-hosting/
> 0 votes

# Answer
you should add your site name to the base url in .htaccess file and uncomment the base url code.
> 0 votes

---
Tags: media, virtual-machine
---


# Question
Title: Suggestions for adding Advanced Search features to a block (using the dashboard)?
Is it possible to do the following:

1. Add a Search box to a block through the dashboard?
2. Have an Advanced Search on multiple fields in that block?
3. Have the results of the search open in a new page?

I understand that there are options to do this with code, but my client would like to manipulate as many areas as possible through the dashboard.

Any suggestions?

# Answer
> 0 votes
Search form is itself a block; you should add this box to a region. Let the client configure blocks; they can move the block from admin/structure/block.

>

---
Tags: blocks, search, dashboard
---


title: Permission Denied (403) using /batch

text:
# Question
Title: Permission Denied (403) using /batch
I have run into a scenario where I am getting an 'Permission Denied' error when attempting to run anything that uses batch, with the sole exception being CRON.

First off, this error is NOT related to the max\_allowed\_packet issue referred two in every other thread regarding this scenario. First off, my max\_allowed\_packet is set to 16M, and second, my batch table shows valid requests waiting to be run:

my.cnf:

```
max_allowed_packet = 16M

```

drupal.batch table:

```
15456   ba_Tu-5BZEcFUq3RH37zvx6bvCWJGvlUUtYgADfOlPY 1406048062  ...

```

The requests being attempted are very small as well, I'm only trying to delete 1 user.

This happens with the primary admin account (UID 1) as well as all other administrators, so it does not appear to be account or access specific.

**I am uncertain where to look next for more clues.**

MySQL logs do not show any warnings or errors, and the only line in PHP is this:

```
php drupal: https://www.example.net|1406048063|access denied|X.X.X.X|https://www.example.net/en/batch?op=start&id=15456|https://www.example.net/en/admin/people|1||batch

```

*IP and Domain censored from above log.*

I have also confirmed that there is no '/batch/' folder in my Drupal route that could be messing with the url.

**UPDATE**

I have continued to investigate this as I do patching and upgrading to my network. As part of this overhaul, the backend DB was just switched from MySQL to PostgreSQL, and the issue persists on both databases. So database can been completely ruled out.

I have had success with disabling 'Clean URLs' in my config. If I disable them all batch operations work as expected, however I cannot leave them disabled for obvious reasons. Disabling them every time is not a great option either, as content admin do not have access to this setting and cannot delete spammers as a result.

# Answer
> 1 votes
I would look at your .htaccess rewrite rules. I've hit instances in the past where batch requests wouldn't fire during updates. Turns out I had custom .htaccess rewrite rules interfering with those requests.

Based on your example URL, it looks like you're running Drupal in a subdir on the domain. Have you set up the **RewriteBase** directive for that subdir? Do you have any other custom redirects in .htaccess?

---
Tags: batch-operations
---


# Question
Title: Remove "pubdate" attribute from Submitted Time tag in Drupal 7
Currently when a node or comment is submitted it gets a Submitted text saying "Submitted by user on Wed, 04/01/2015 - 18:07"

The mark-up for this is:

```
<span>Submitted by *user* on <time pubdate="pubdate" datetime="2015-04-01T18:07:34+0000">Wed, 04/01/2015 - 18:07</time></span>

```

What I need to do is remove the "pubdate" attribute from the tag because the it is failing on W3C validation.

I have tried to add the following code in my template.php file but had no luck

```
function ThemeName_preprocess_node(&$variables) {
    $attributes['datetime'] = '<time'.drupal_attributes($attributes) .'>'.$variables['date'] . '</time>';
}

```

How can I remove the "pubdate" attribute in the Submitted by tag?

# Answer
> 0 votes
So \`$variables\['submitted'\] is the one you want to override in your theme's preprocess\_node function. Try this as a starting point:

```
function ThemeName_preprocess_node(&$variables) {
  $variables['submitted'] = t('Submitted by !username', array('!username' => $variables['name']));
}

```

Which will replace the $submitted variable with "Submitted by username" (where the username will be linked to the user's profile page).

# Answer
> 0 votes
Need to hook into "preprocess\_node" to access the $submitted variable like so:

```
function THEME-NAME_preprocess_node(&$variables, $hook) {

$variables['pubdate'] = '<time datetime="' . format_date($variables['node']->created, 'custom', 'c') . '">' . $variables['date'] . '</time>';

$variables['submitted'] = t('Submitted by !username on !datetime', array('!username' =>$variables['name'], '!datetime' => $variables['pubdate']));
}

```

---
Tags: 7, nodes
---


# Question
Title: How to create a views that display all the publish content type as one output per user
Intro : I have created a two different content types because I needed two different moderation process for those two content type, each of those content type are limited to 1 per user. Those content are "Projet Description" and "Projet Images".

Now I need to combine those two content types into one with views so I can show the user projet and is related images. The problem I have for the moment when I group result together by UID is that the two node hare display separately and I see a Title for the Projet but I also see a Title for the Images.

**What I need is :**

USER 1
Title : My Projet Titre
first image for this project: (image1)

USER 2
Title : My Super Projet
first image for this project: (image1)

**What I have for the moment is :**

USER 1
Title : My Projet Title

Title : Images for the Projet
(image 1)(image 2)(image 3)

USER 2
Title : My Super Projet

Title : Images for the Projet
(image 1)(image 2)(image 3)

PS: I try to keep that as one question but I also need to have a exposed taxonomy filter for Projet

# Answer
> 1 votes
I finally did that with Relation module. I was assuming I don't need that because there is a relation between the two content type, the author is the same for the two node, but I was not able to combine the two node in one.

My solution Relation Module to combine the two node. I created a relation between the project and the project images node. In views I created a content type view with the field I need from the project type than I add the relation : Relation(node \<-\> node) add I add the field "Image(from Projet Image)" to display the image and Bingo I have one view output for two different node.

To make the relation automatic I created a Rules with Rules module. I fire the rule when a Projet is added or a Projet Image is added than I create the relation.

A quick help for rules 5 actions step 1st action : create a variable / create a list 2st action : fetch entity by property / node / Author 3rd action : place the fetch result in the list created at step 1 (you may have to create a lot) personally because the node hare limit to 1 per content type per user I just repeats the step 3 two time 4ft action : create a entity / relation / with the list created at step 1.

Those step have to be improve because those are my first step with Rules and I rules are not strong at all.

Hope it help someone.

---
Tags: views, nodes, users
---


# Question
Title: Migration taking increasingly long periods of time
I have a migration and I've noticed that the code, through each batch operation, seems to process less and less items.

For example, the first few cycles, it'll say, "processed 600", and 600 or around there will be processed. However about 5-10 cycles in, and it will still say "processed 600", and it actually processes perhaps 100 or 200. This eventually stops the migration from happening, as it essentially grinds to a halt.

It was completing on my local machine and not the stage environment, which I initially thought to be due to some sort of environmental condition. Now I think that the cycles on my local were just large enough to allow everything to process before it grinded to a halt.

I'm not sure what is causing this, and if it's in this migration, or the migration that this migration is extending. I'll include the former, and if anyone needs the latter, let me know.

Note, there may be occasional instances where the words Company or Type are capitalized when they should not be - I just did a quick find/replace for sensitive data.

```
class CompanyTypeUserDataMigration extends CompanyCertBaseMigration {

public function __construct($arguments) {
    parent::__construct($arguments);

    $this->machineName = "CompanyTypeUserData";
    $this->systemOfRecord = Migration::DESTINATION;
    $this->group = MigrateGroup::getInstance("Company");
    $query = Database::getConnection('default', 'Type')
        ->select('Type')
        ->fields('Type', array('Name', 'Username', 'Address', 'City', 'State', 'Zipcode', 'Country', 'Phone', 'Notes', 'Email'));
    $query->addExpression('`Company Name`', 'Company');
    $query->addExpression('`Supervisor Email`', "supervisor_email");
    $query->addExpression('`Declined Recert Renewal`', "declined_recert");
    $query->isNotNull('Username');
    $this->source = new MigrateSourceSQL($query, array('status' => 'Status calculated based on various fields'));
    $this->destination = new MigrateDestinationUser();
    $this->map = new MigrateSQLMap($this->machineName, array(
            'Username' => array('type' => 'varchar',
                'length' => 50,
                'unsigned' => FALSE,
                'not null' => FALSE,
            ),
            'Email' => array('type' => 'varchar',
                'length' => 50,
                'not null' => FALSE,
            )
        ), MigrateDestinationUser::getKeySchema()
    );

    $this->addFieldMapping('name', 'Username');
    $this->addFieldMapping('field_company', 'Company');
    $this->addFieldMapping('field_supervisor_email', 'supervisor_email');
    $this->addFieldMapping('field_notes', 'Notes');
    $this->addFieldMapping('field_status', 'status');
    $this->addFieldMapping('field_full_name', 'Name');
    $this->addFieldMapping('uid', 'user_id');
}

public function prepareRow($row) {
    // Always include this fragment at the beginning of every prepareRow()
    // implementation, so parent classes can ignore rows.
    if (parent::prepareRow($row) === FALSE) {
        return FALSE;
    }
    if (empty($row->Username)) {
        return FALSE;
    }

    $uid = $this->find_user_id($row);
    if($uid === FALSE){
        return false;
    } else {
        $row->user_id = $uid;
        $user = user_load($uid);
        if(isset($user->name)){
            $row->Username = $user->name; //so we don't try to overwrite username permutations
        }
    }
}

}

```

# Answer
What's the total number of nodes you're importing? I've hit this issue before using the D2D Migration module. I've found that D2D starts to slow down on consecutive batches when I'm importing in more than ~5K nodes. In scenarios where I've needed to import 10K-100K nodes, batches eventually slow down to where nothing is ever imported.

Using XHProf & XDebug, I traced down the issue to database objects consuming tons of memory & CPU to the point of stopping PHP execution. I've never been able solve the issue for importing over 10K nodes using D2D. Searches all over the internet have produced nothing. In many instances I've had to rely on custom PHP import code as since I could not use D2D.
> 0 votes

---
Tags: 7, database, migrations
---


# Question
Title: How to edit Drupal core rdf.module functionality
Using drupal's core RDF module there is a function (shown below) that add "xml:lang" attibute to tags. What I want to do is to change this functionality so that `$variables['attributes_array']['xml:lang'] = 'en';` instead of leaving it blank like in the core module. What would be the best way to achieve this?

```
/*
 * Implements MODULE_preprocess_HOOK().
 */
function rdf_preprocess_username(&$variables) {
  // Because xml:lang is set on the HTML element that wraps the page, the
  // username inherits this language attribute. However, since the username
  // might not be transliterated to the same language that the content is in,
  // we do not want it to inherit the language attribute, so we set the
  // attribute to an empty string.
  if (empty($variables['attributes_array']['xml:lang'])) {
    $variables['attributes_array']['xml:lang'] = '';
  }
}

```

# Answer
> 0 votes
You can add the following preprocess function to template.php in your custom theme. The RDF module is preprocessing the variables used by the theme\_username() function. Your custom theme can also preprocess these same variables and override the values set by the RDF module.

```
/*
 * Implements THEME_preprocess_HOOK().
 */
function YOURTHEMENAME_preprocess_username(&$variables) {
  $variables['attributes_array']['xml:lang'] = 'en';
}

```

---
Tags: 7, hooks, theming, rdf
---


# Question
Title: Why is my custom block template applying to all blocks?
I have a region on my home page called home\_area\_1. It contains several blocks. I want those blocks to be formatted in the same way, so I created a template called block--home-area-1.tpl.php. It is formatting those blocks correctly, but it's also being applied to blocks in other regions on the home page.

What am I doing wrong? I only want the blocks in this particular region to use this template.

I'm on Drupal 7.35, and am fairly new at this.

# Answer
As stated in Drupal 7 Template (Theme Hook) Suggestions, it suggests the file name structure to be like *block--sidebar\_first.tpl.php*.

**==EDITED==**

In my themename.info file I declared

```
regions[sidebar_first] = First Sidebar

```

Copied the core **block.tpl.php** file, renamed it to **block--sidebar\_first.tpl.php**, added "BLOCK NAKO" text.

Then I Flushed Caches. The image below is the result.

As you can see the footer region blocks doesn't have the override that I only set for blocks within the sidebar first region.
> 1 votes

---
Tags: theming, blocks
---


# Question
Title: Call python from module and receive output
I am creating a Drupal 7 custom module and would like to call a python script from the PHP and receive back some output from the script. I am running on a Linux OS and have the following so far:

```
    $command =  "/usr/bin/python " .  drupal_get_path("module", "mycustmod") . "/pycriptdir/pyscript.py ../../../../default/files/shapefiles/CherokeeCounty.shp";
    $output = shell_exec($command);

```

Within the python script I am using echo to pipe the output. However, I do not get anything back into the output variable as I would expect.

Any advice on how to get this to work would be greatly appreciated.

Thanks, Derek

# Answer
Thanks for the responses. The basic take-home for me here is to try a simple python script shell\_exec first. Once I did this I was able to quickly see that shell\_exec was working as expected. This in turn led me to my issue which ended up being not really related where I had some minor path issue that were throwing me off. Perhaps drupalist advice to "try a simple command to make sure shell\_exec works, then check the python" will help others with the same issue.

Derek
> 1 votes

# Answer
I don't understand why you are "using echo to pipe the output". Your python script should just print normally. shell\_exec captures std out.

I tried out code like you have above and it worked for me. I would try printing out the command and trying it via ssh after cd'ing to your folder and see if that works.

Also I would try it with a very small python script and see if that works.
> 0 votes

---
Tags: 7
---


# Question
Title: Updating settings.php breaks website hosted from subfolder
This is somewhat linked to this question. I have 2 Drupal 7 sites hosted in subfolders, one of which is intended to be a production site (`public_html/site1`) and the other is the testing site (`public_html/site1-test`).

The main url (i.e., site1.com) should be shown when accessing the production site. When I go to my main url, it shows correctly. However, all links and content are shown via the subfolder (e.g., `site1.com/site1/content/...` rather than `site1/content`).

To facilitate the change, I updated the `$base_url` variable in the settings.php file to serve the base URL (i.e., site1.com) and that completely breaks the site. The theme stops showing, logins don't work, etc.

Is there a way around this problem? The main site should mask off the subfolder in the url, however I don't think I can do that without updating the `$base_url`

# Answer
Try setting your base URL in settings.php like

```
$base_url = 'http://site1.com';  // NO trailing slash!

```

And in your .htaccess file set RewriteBase to:

```
RewriteBase /site1

```

or

```
RewriteBase /site1-test

```
> 0 votes

---
Tags: 7, .htaccess, uri
---


# Question
Title: How can I place $content in search results instead of $snippet?
I'm using the Link module to display a field that links to an external site. `$snippet` places this link (along with other fields) in a paragraph. The fields have no separation and the link doesn't work. I'd like to place $content in search-result.tpl to remedy this but everything I've tried has given me an error.

Someone mentions `$result` here which may be what I need.

I tried `<?php print $result['field_lipsum']; ?>` but it gives me `Notice: Undefined index: field_lipsum in include() . . .`

How can I place $content in search results instead of $snippet?

# Answer
Define *yourtheme*\_preprocess\_search\_result in your theme's **template.php** file. Do something like this:

`function yourtheme_preprocess_search_result(&$variables) {
 //$variables['result']['node'] should contain the entire node object
 $variables['content'] = $variables['result']['node']->body[LANGUAGE_NONE][0]['value'];
}`

You should be able to use the variable **$content** inside **search-result.tpl.php** now.
> 0 votes

---
Tags: search
---


# Question
Title: Drupal Lightbox2 fails W3C validation because of rel="lightbox[field_image][]" attribute
I am using the latest Lightbox2 module for Drupal which works great but for my field images it adds a rel="lightbox\[field\_image\]\[\]" which fails W3C validation.

Is there a way to work around this so it passes validation? I have been reading somewhere to change the "rel" to "data-rel", but how would you apply this? Any ideas?

# Answer
> 0 votes
You can copy the `lightbox2-insert-image.tpl.php` file into your own theme and change it there - but this will break the functionality of the module as javascript uses `rel` attribute multiple times.

You could refactor the javascript, change all occurrences where it accesses `rel` and change it to `data-rel` and create patch and submit it to drupal.org to the author of the issue as a request (or just submit issue now requesting this and wait if/until the maintainer does it).

On a personal note - why do you need it to pass W3C validation? Is it a project MUST requirement? If not, I would not waste any time on this as valid HTML is not that important any more, not even for SEO and indexing.

Edit: http://google.com is not passing W3C validation, I think that sends a message. (http://validator.w3.org/check?uri=google.com&charset=%28detect+automatically%29&doctype=Inline&group=0)

---
Tags: 7, media, javascript
---


# Question
Title: Drupal 7 Calendar - How do you modify link from day number?
When I click on the day number, it currently goes through to day page. I'd like to customise this to go to a specific event page for that day.

I can't find a hook for this. Is there one?

# Answer
The day page is generated by the day display of the view generated by the calendar module. You can customize this display as much as as you want - add header, footer, embed an attachment view, or otherwise enhance it:

You can disable the day display if you don't want the links at all.

Replacing it with another page would be much harder, but it might be possible using the panels module.
> 0 votes

# Answer
U need to customize it. Firstly you need to put a alter in your template.php

```
function themename_preprocess_calendar_datebox(&$vars) {
  $date = $vars['date'];
  $view = $vars['view'];
  $day_path = calendar_granularity_path($view, 'day');
  $vars['url'] = 'events-and-attractions/events/' . $date;
  $vars['link'] = !empty($day_path) ?l($vars['day'],$vars['url']):$vars['day'];
}

```

Create a view page that list the events , with a contextual filter of event start date. And provide that view path in $vars\['url'\].
> 0 votes

---
Tags: datetime
---


title: Get all children of a term

text:
# Question
Title: Get all children of a term
I have the following tree structure, I want to get all child terms. I implemented `taxonomy_get_children('tid')` drupal api function.

```
1.Gloves
 1.1 Seamless
   1.1.1 Kevlar
    1.1.1.1 Shell
    1.1.1.2 Dots
    1.1.1.3 Coated
 1.2 mechanics
 1.3 cut and sewn
2.Apparels
 2.1 Coveralls
 2.2 Aprons
 2.3 Trousers

```

When I clicked on `Apparels` I successsfully get all child terms using but when I clicked on `Gloves`, it provides me only top level child terms `('seamless', 'mechanics','cut and sewn')`, not the deep levels.

# Answer
Use `taxonomy_get_tree` instead, it takes vocabulary ID as the first param, and the term ID under which to generate the tree - this should give you all children of a term.

More info here.
> 3 votes

---
Tags: taxonomy-terms
---


# Question
Title: Avoid access to profiles (user/%user/view)
I want to avoid access to *user/%user/view*, so only admins can see profiles. At first I tried with changing the permission user\_view\_access without any luck.

I tried to use the hook hook\_menu\_alter:

```
53 function mymenu_menu_alter(&$items) {
54   $items['user'] = array(
55     'access callback' => 'user_access',
56     'access arguments' => array('access administration pages'),
57     'type' => MENU_NORMAL_ITEM,
58   );
59   $items['user/%user_uid_optional'] = array(
60     'access callback' => 'user_access',
61     'access arguments' => array('access administration pages'),
62      'type' => MENU_NORMAL_ITEM,
63   );
64   $items['user/%user/view'] = array(
65     'access callback' => 'user_edit_access',
66     'access arguments' => array('access administration pages'),
67     'type' => MENU_NORMAL_ITEM,
68   );

```

It doesn't work neither. Do you have any hint?

# Answer
There are four problems with the code you reported:

* The code is changing the menu type, when it should not do so.
* The code is changing values that it should not touch, if the purpose is to only change who can access the user profiles.
* user\_edit\_access() and user\_access() expect the argument they receive to be a user object, not a string. It is wrong to set "access arguments" to `array('access administration pages')`, as you are doing.
* Even if you would set "access arguments" to `array(1)`, `user_edit_access()` allows the users to see their own user profile; if you want to avoid to show to the users their own user profile, then that function is not the function I would use as access callback.
* As said by jhedstrom, it is not necessary to use code in this case, when it is enough to don't give the permission to access user profiles to those roles you don't want to be able to see any user profile. The answer I am going to give takes the assumption you don't want the users to see any user profile, including their own; in this case, removing the permission to access user profiles doesn't help, as Drupal still allows the users to see their own user profile.

```
function mymenu_menu_alter(&$items) {
  $items['user/%user/view']['access callback'] = FALSE;
}

function mymenu_user_view_access($account) {
  return $account && $account->uid && user_access('administer users');
}

```
> 6 votes

# Answer
Finally I achieved what I wanted with:

```
  function mymenu_menu_alter(&$items) {
   $items['user/%user_uid_optional'] = array(
      'page callback' => '_mymenu_profile_view',
      'page arguments' => array(1),
      'type' => MENU_LOCAL_TASK,
    );
  }

  function _mymenu_profile_view($account) {
    global $user;
    if (user_access('administer users')) {
      include_once(drupal_get_path('module', 'user').'/user.pages.inc');
      return user_view($account);
    } else {
      return drupal_not_found();
    }
  }

```

Thanks for your suggestions!
> 1 votes

# Answer
For this trick I have used chain\_menu\_access module. Code below.

```
/**
 * Implements hook_menu_alter().
 */
function mymodule_menu_alter(&$items) {
  chain_menu_access_chain($items, 'user/%user', '_mymodule_check_permission');
}

function _mymodule_check_permission() {
  global $user;

  $own_profile = $user->uid == arg(1);
  $has_access = user_access('administer users');

  return (!$has_access && !$own_profile) ? FALSE : TRUE;
}

```
> 1 votes

# Answer
This is coming a bit late, but I'll leave this here just in case anyone else has the same problem :)

There's Path Access:

> Although a lot of the Drupal modules provide some degree of access control permissions it never covers all possible requirements users have. Path\_access provides the means to restrict pages based on their path alias - meaning you can lock out certain user role groups from whole sections of a site using wildcards.

But the best option, and a module that is now at the top of my master .make file is Rabbit Hole \- which supports custom redirects for nodes, users and taxonomy terms.

> Rabbit Hole is a module that adds the ability to control what should happen when en entity is being viewed at its own page.
>
> Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.
> 1 votes

# Answer
If you want a user to be able to edit their own profile but not view it:

If already using Panels module you can simply create a second variant in the user view override if (in the selection rules) a user lacks the permission needed to view the usual panel (such as User:Permission =\> Logged in user has "View user profiles"). You choose a HTTP Response Code and select a 301 redirect to `user/%user:uid/edit`.

You can then hide the view button with CSS or implement the code mentioned above:

```
function mymodule_menu_alter(&$items) {
  $items['user/%user/view']['access callback'] = '_mymodule_user_view_access';
  $items['user/%user/view']['access arguments'] = array(1);
}

function _mymodule_user_view_access($account) {
  return $account && $account->uid && user_access('administer users');
}

```

or use several methods to remove tabs. I suppose the following should work in Drupal 7 but maybe it's not the right way to do it or it has side effects.

```
function mymodule_menu_local_tasks_alter(&$data) {
  foreach ($data['tabs'][0]['output'] as $key => $value) {
    if ($value['#link']['path'] == "user/%/view") {
      unset($data['tabs'][0]['output'][$key]);
    }
  }
}

```
> 0 votes

---
Tags: 7, routes, users
---


# Question
Title: Rabbit hole: what's the recommended setting for content that should not be directly accessible?
I have one content type, as well as several vocabularies (taxonomy) that are only shown on the site through views and therefore should not be accessible on their own. I'm using the rabbit hole module to prevent that from happening.

My question is this: from an SEO point of view, is it better to use a 301 redirect (to the front page), or a "page not found" response?

Maybe I should point out that the site isn't online yet, so it hasn't been crawled by search engines.

# Answer
It's really up to you what you want to do but the way I see it, if a user goes to a random non-existing path on your site they will get a 404 error, so if the rabbit hole page is a page the user should never be able to get to then it should also be a 404 error because as far as that user is concerned it is not a valid page.

Now if you redirect all 404 errors to your home page or search page or something then these pages should have the same behavior.

If the page is something that anonymous users cannot see but a paying member can (or some similar scenario), then it may make more sense to set rabbit hole to a 403 error, because it is a page that they can't currently see but could see if they log in.
> 2 votes

# Answer
Usually I would recommend a 301 redirect – if the contennt really has moved to a new location. But in this case, redirecting from various pages to the front page, a 301 would **not** be recommendable – at least **from a SEO point of view**. When a search engine reads a 301, it interpretes it as "*this content has move permanently to a new location*". But in your case that's not the case – and so I would fear that a 301 could actually fire back. The pages you basically just wanted to hide from the user will probably disappear from the search indexes one by one.

Instead I personally would probably use javascript for forwarding users to the front page. The user experience is close to a 301 redirect – but for search engines javascript is mostly not functional so that the pages you just wanted to **hide from users** can actually **stay in the search indexes**.

I haven't tried the rabbit hole module myself – but since it seems to be able to have search engines crawl, while users are redirected, at least it sounds worth trying.

ps: just saw your comment on the accepted answer: "those pages are simply not supposed to exist". Well – then it's *probably / almost* all the same.
> 1 votes

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


title: Creating A Submenu In Drupal

text:
# Question
Title: Creating A Submenu In Drupal
Hello I Am New to drupal and i want to create a submenu bar under Menu Navigation So Can ANYONE Suggest And Idea Or Something To Create A Submenu In Other Page Like Shown On Image

# Answer
Submenu can be created by selecting Parent link for that menu and ordering can be done by weights. Try reading this in detail at drupal.org
> 0 votes

# Answer
Do you have a dynamic list of links that you want to use in the submenu or those links are always the same?

If your URLs in that submenu don't change, the easiest solution is to manually create a block with submenu links and just place it under the main menu,
> 0 votes

---
Tags: routes
---


# Question
Title: Enabling aggregate and compress CSS files resuls in vanishing theme
I used this module for more compression on css and js files but it does not work for me! so I disable and remove it entirely. After that when I enable aggregation of css and js files, my site's theme will disappear! even my administration theme! what should I do now?

# Answer
> 0 votes
Do following steps:

1. Again place advagg module's folder in your module's directory. Usually (sites/all/modules)
2. Go to database and truncate all cache tables starting with "cache". Do with caution.
3. See if site works.
4. Otherwise if you are having drush installed, check command "drush status" if it works. And clear the cache throudh drush again by command "drush cc all".

Hope this will help you. If not reply in comment I'll assist you to make your site work again.

---
Tags: performance, css-js-aggregation
---


# Question
Title: drupal site is really slow on VPS server
I have a drupal 7 website on a VPS server with the following specifications:

**Processor Name:** Intel(R) Xeon(R) CPU E31270 @ 3.40GHz

**Processor Speed (MHz):** 3392.294

**Total Memory:** 3924628 kB

**Free Memory:** 276096 kB

**Total Swap Memory:** 4063228 kB

**Free Swap Memory:** 3894104 kB

Apache 2.2.29: Running

DirectAdmin 1.47.0: Running

Exim 4.84: Running

MySQL 5.5.31: Running

Named 9.8.2rc1: Running

ProFTPd 1.3.5: Running

sshd: Running

dovecot 2.2.16: Running

Php 5.3.29: Installed

With one GB of ram, I thought that the slowness of my website might be because of the heaviness of tables. (Number of tables: 381, DB size: 60 MB) But by searching the net, I found that my DB is not that heavy. I also noticed that in my services, the memory usage of httpd is 650 MB. I think this also might have something to do with slowness of my website. Can anybody help me with this issue? Thanks.

# Answer
Isn't it closer to 4Gb RAM based on your posted stats? A server with only 1Gb RAM will most likely not work properly with a full application stack. Apache and MySQL require memory to be performant. The least I'd recommend based on personal experience is 2Gb RAM.

What you can also do is perform traces on your site with xhprof to see what the slowest items are, and improve those. APC and memcache can also help to boost speed. Or if you only have anonymous users, using the boost module can be a very quick fix, although it's not maintained actively anymore for Drupal 6 it seems.
> 1 votes

# Answer
You're most likely running into RAM issues. Your host should be able to tell you more.

Switching to Nginx instead of Apache is usually a good solution. If your site isn't too big, Varnish could also be useful.
> 0 votes

---
Tags: database
---


# Question
Title: Problem In Adding Flexslider To Slideshow
Hello i Have Create A Views Slideshow Using Views And Jquery Cycle But I Am Installing Flexslider Module But I Can Able To See A Slide Sidebar I Am Also Placing The Flexslieder Into Libriaries

Check My Link Adclof.com

# Answer
> 1 votes
Make sure you use the flexslider module with views integration, views slideshow and flexslider views style are different modules. They each provide a different style for your view!

---
Tags: javascript
---


# Question
Title: How to pass content type filter to taxonomy
I created a classified ad website with different content type like vehicle, clothing, mobile phone, computers, etc. Within this content type has a field called location. A location field is an address of the item posted on my website like cities.

My question is on how can I filter location plus the content type. Currently, when I click the location, all of the content type article shows.

Here's an example of what I want:

Select article about vehicle, within the vehicle article is a field called location. When I click the location of the item, the result should include only items related to the previous content type, that is, vehicle content type. Location field is connected to Location taxonomy I created.

BTW, I already installed views and it is working fine.

# Answer
> 0 votes
I think you need to edit the location links to include a second "parameter" so it could look like:

```
yoursite.com/yourview?location=yourLocation&articletype=yourArticle

```

For this you would need to implement some hooks. Maybe you can start with hook\_preprocess\_node.

What I would do is to:

1. Use the said hook
2. Get the location terms available for the current viewed node
3. Construct the URL based on the term data and content type the way I want it to look.

Then in your view, you need to add just two contextual filters that would be those fields. The location term reference field and the content type.

**EDITED**

## Node view and term link update

1. Created a new content type name Article 2 (Machine name: article\_2) to follow your structure of content types having Vehicle, Clothing and etc. So mine is just Article and Article 2. My content types have the Term reference field of the Tags vocabulary w/c in your setup is the Location.
2. Added terms into the Tags vocabulary: Term 1 and Term 2.
3. Created a simple custom module using hook\_preprocess\_node() w/c looks like:

---

```
function yourmodulename_preprocess_node(&$vars) {
  // Check if your term field is being rendered in the node view
  if (isset($vars['content']['field_tags']['#items'])) {
    // Loop through all terms present in the node
    foreach ($vars['content']['field_tags']['#items'] as $index => $info) {
      $node_type = '/' . $vars['type'];
      // We append the node type to the URL of a term so that
      // it can be used as a contextual filter in the term view.
      $vars['content']['field_tags'][$index]['#href'] .= $node_type;
    }
  }
}

```

Remember to do a Flush Cache since were adding a new hook function into the system. Now when you view a node, check the term link(s) listed and you will see that the URL structure is not like **http://yoursite.com/taxonomy/term/2/article**

## Term View

1. Clone the Taxonomy Term view (So that we wont be changing the original)
2. Add a second wild card argument in the Path w/c looked like taxonomy/term/% to **taxonomy/term/%/%**. The second argument would be for the content type.
3. Under contextual filter add the Content: Type field following the settings in the image.

4. And then place the Content: Type contextual filter at the second row to match the URL structure w/c would look like:

And that's it. A simple sample result based on this URL http://localhost/drupal/taxonomy/term/2/article would look like:

So it's filtering the right node that has Term 2 as its Tag(my setup)/Location(your setup) and only the Article content type.

My test data are:

1. Article content type: Article 1, Term 1
2. Article content type: Article 2, Term 2 (This is the result in the latest screenshot)
3. Article 2 content type: Article 3, Term 1
4. Article 2 content type: Article 4, Term 2

## Issue

So far I haven't figured out how to use this style with Pathauto so the URL would look better for example, www.mysite.com/illinois/chicago/article.

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


# Question
Title: Set Image Custom Field as Open Graph Image in Metatags
I have installed the Metatags module along with the Open Graph and Twitter Card extension modules. In my default content type, I have added an Image field that allows an image to be uploaded for use on Facebook and Twitter.

Now I cannot get the Metatags module to accept this image custom field as the entry for the og:image and Twitter Card Image fields. I've tried entering \[node:field\_image\] but the meta tags do not get added to the source code. If I enter a URL the tags appear.

How do I get Metatags to dynamically include a corresponding image for each page in the Open Graph and Twitter Cards metadata?

# Answer
> 3 votes
I used `drupal_add_html_head` in my case. In my theme template.php.

```
$og_image = image_style_url('200x200', $node->field_gallery_preview_image[LANGUAGE_NONE][0]['uri']);
// OG image meta property.
drupal_add_html_head(array(
  '#tag' => 'meta',
  '#attributes' => array(
    'property' => 'og:image',
    'content' => $og_image,
  ),
), 'node_' . $node->nid . '_og_image');

```

# Answer
> 0 votes
I fixed editing my template.php \> MYTHEME\_html\_head\_alter.

Code:

```
function YOURTHEME_html_head_alter(&$head_elements) {
  // Overwrite og:image file
  $head_elements['opengraph_meta_og:image']['#attributes']['content'] = "path/to/your/image.jpg" ;
 }

```

---
Tags: meta-tags
---