title: Wordpress to Drupal: Wordpress Migrate

text:
# Question
Title: Wordpress to Drupal: Wordpress Migrate
I have a fresh install Drupal 7.34 on WAMP. Token and Pathauto are already installed. The Theme, if it is relevant, is Stanford Open Framework.

I have Wordpress\_migrate, migrate, migrate\_extras intalled and then included features, media and media\_youtube as low level diagnostic.

I follow through the instructions to use wordpress\_migrate that seem self-explanatory and get this string of errors

```
Passing a group object to a migration constructor is now deprecated - pass through the arguments array passed to the leaf class instead.
The DynamicMigration class is no longer necessary and is now deprecated - please derive your migration classes directly from Migration.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
No migration found with machine name WordPressAuthor
No migration found with machine name WordPressBlogEntry
No migration found with machine name WordPressPage
No migration found with machine name WordPressAttachment
No migration found with machine name WordPressComment
Passing a group object to a migration constructor is now deprecated - pass through the arguments array passed to the leaf class instead.
The DynamicMigration class is no longer necessary and is now deprecated - please derive your migration classes directly from Migration.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.
The field mapping arguments() method is now deprecated - please use subfield notation instead.

```

The migration does seem to complete but the list of imports under the blog name is 0 0 0 throughout.

I can see that a partial XML file has been transferred from Wordpress. I have also tried exporting the Xml file from Wordpress and uploading that. I get the same errors.

The string of red errors suggests the entire module is borked. Is that correct? In which case, what is the best strategy to migrate a Wordpress blog to Drupal.

If the module is not borked then any suggestions what I might have missed or misunderstood?

I clearly do not understand the underlying problem, so please do not bite my head off. A clear orientation will be received with sincere gratitude though.

# Answer
> 1 votes
The module is pretty borked.

Beebee is right. When you install using Drush, you will get the latest non-dev Wordpress\_migrate and the latest Migrate - clash! You also get no warning about needing migrate\_extras features and media.

So the trick is install the latest Migrate with Drush but as of today's date, download the latest dev version of Wordpress\_Migrate.

I was able to download my blog from its url. It did hang and I exited expecting a mess but all the content is there. As I am trying to sort out content, that suits me.

So the principles -- --download migrate, migrate\_extras, media, features and ctools -- manually download the dev version of wordpress\_migrate

If your blog is large, be patient. If the download borks, then try to increase the execution time or try exporting your blog to a file from inside Wordpress, use the Wordpress file splitter and try uploading by file.

Thanks Beebee.

---
Tags: 7, migrations
---


# Question
Title: Adding a button to a form that links to an external URL
I am trying to add another button to a user login form. I am able to get the button to show up, but not to link to an external URL (example.org in the code below). Code I am using is below:

```
<?php

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_login' || $form_id == 'user_login_block') {
    $form['change_pass'] = array(
      '#type' => 'button',
      '#prefix' => '<div class="form-actions form-wrapper" id="change_pass">',
      '#suffix' => '</div>',
      '#value' => t('Change Password'),
      '#weight' => 1000,
      '#submit' => array('MYMODULE_change_pass_submit'),
      '#limit_validation_errors' => array(),
    );
  }
}

function MYMODULE_change_pass_submit($form, &$form_state) {
  drupal_goto('https://example.org', array('external' => TRUE));
}

```

Any thoughts?

# Answer
> 2 votes
You should use `$form_state['redirect']` to redirect in form submit instead of `drupal_goto` ,I mean

```
function MYMODULE_change_pass_submit($form, &$form_state) {

  $form_state['redirect'] ='https://example.org';
}

```

---
Tags: forms
---


# Question
Title: How to create a view block for comments with nesting and parent relationship
I'm trying to display the comments on my nodes in a view rather than using drupals default comments rendering.

Is it possible to display a comment view on a node, which also renders the comments with replies, rather than rendering every comment (including replies) as a top level comment?

How would you setup views to do this?

**UPDATE**

I've successfully setup views, so that it renders comments and replies in the correct order.

You have to set:

```
Relationship -> Comment: Parent Comment
Sort Criteria -> Thread (desc)
Sort Criteria -> (Parent Comment) Comment: Post date (asc)

```

However the pager still counts every single comment reply as an item, so it is prone to cutting off threads in the middle and ideally I'd still like to page it.

**ORIGINAL WORKINGS**

**What I've tried to do so far -- Show: Settings: Parent relationship**

Getting the top level comments was reasonably easy, I created a view block which displays comments and then added:

`Contextual filter -> Comment NID (Content ID from URL)` (Shown here)

This gives a me a view block which will display comments. However all the comments are rendered as top level comments (no indented markup)

I needed the parent relationship, so I added a second relationship (comment views by default have a `Comment: Content` relationship),

```
Comment: Parent Comment

```

And then under Format: Show: Settings, I enabled:

```
Relationship: Parent Comment

```

Unfortunately on loading the node, this causes several PHP errors. views\_plugin\_row\_comment\_view.inc has a pre\_render function and for some reason changing the Relationship: Parent Comment causes none of the CID's to load in the pre-render function and so it spits out all the horrible errors you see below. How am I setting this up wrong?

```
Undefined property: stdClass::$cid in views_plugin_row_comment_view->pre_render() (line 79 of ... sites\all\modules\views\modules\comment\views_plugin_row_comment_view.inc
Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of C:\xampp\htdocs\basic\includes\entity.inc).
Notice: Undefined index: in template_preprocess_views_view_row_comment() (line 645 of C:\xampp\htdocs\basic\sites\all\modules\views\modules\comment.views.inc).
Notice: Trying to get property of non-object in template_preprocess_views_view_row_comment() (line 646 of C:\xampp\htdocs\basic\sites\all\modules\views\modules\comment.views.inc).
Notice: Undefined index: in template_preprocess_views_view_row_comment() (line 646 of C:\xampp\htdocs\basic\sites\all\modules\views\modules\comment.views.inc).
Notice: Trying to get property of non-object in template_preprocess_views_view_row_comment() (line 650 of C:\xampp\htdocs\basic\sites\all\modules\views\modules\comment.views.inc).
EntityMalformedException: Missing bundle property on entity of type comment. in entity_extract_ids() (line 7729 of C:\xampp\htdocs\basic\includes\common.inc).

```

**What I've tried to do so far -- Sort: Comment Threading**

I took a look at the following sandbox module and according to the issue thread it was based on https://drupal.org/node/1039494, apparently it was solved ages ago by adding in a sort criteria `Comment: Thread`.

I tried adding this and setting the relationship to parent comment but this also had no effect, the comments still remained in separate rows. Has anyone had success with this method?

# Answer
> 1 votes
If i only had a specified number of nesting levels (e.g. 2) would try to use attached views.

All relationships should be from parent comment to child comment and not the other way round.

Also make sure that the relationships are not required (you want OUTER JOINS instead of INNER JOINS in order to avoid filtering out comments that don't have child comments)

So the top level view would only fetch top comments. Then the attached view would fetch child comments for the parent comment and so on.

This solution has not optimal performance and does not scale for deep nesting. However it requires no custom coding.

If you are willing to do custom coding try add a Views PHP field and use something like this https://api.drupal.org/api/drupal/modules%21comment%21comment.module/function/comment\_get\_thread/7

to get all comments in your thread

# Answer
> 2 votes
I recommend installing the Views Threaded Comments sandbox module.

> Provides Threaded comments views plugin

I'm a developer, so I'd start there ... if you're not a developer you may not find a sandbox project as a good starting off place, your mileage may vary.

# Answer
> 0 votes
Ok so here was my final solution. I never managed to solve the pager issue so instead I used the following design:

* Top level comments are displayed on the node in a field only view
* Each then has a link to a comment discussion which is a separate view on a different page
* The separate comment view renders comments as opposed to fields

The top level comment view is reasonably simple to set-up, the only slightly confusing part is the filter to only show top level comments. You need:

* Relationship: Comment: Parent Comment
* Filter: Comment ID - Relationship (Parent Comment) - Value = NULL

Generating the link to comment discussion requires a separate module. The issue is how you grab the correct comment and all it's replies from the database. Comments store a PID, but in a chain, this means you'd have to search recursively to find an entire chain. Instead we need to use the thread field which isn't naturally loaded.

The thread field contains values as follows:

```
Comment   - 01
  Reply   - 01.01
    Reply - 01.01.01
    Reply - 01.01.02
Comment   - 02

```

So in order to grab a whole chain all we need is the first two digits of thread and nid of the node the comment is on.

To do add thread to our we we alter the comment view we're using on the main page using `hook_views_query_alter`. A good explanation of how to setup the module is here.

The exact query you need is:

```
  if ($view->name == 'my_comment_view') {
    $query->fields['thread'] = array (
      'field' => 'thread',
      'table' => 'comment',
      'alias' => 'comment_thread',
    );
  }

```

You then need to create the comment discussion view with a path that contains two wildcards.

When you then generate the URL in the views template, one will need to be the id of the node the comment is on and the other will be the first two digits of the thread.

The comment discussion view will need a contextual filter:

* Contextual Filter: Comment: NID

And you'll need to alter the query to pick out the correct thread with `hook_views_query_alter` alter again because this isn't possible in the UI.

```
if ($view->name == 'comment_discussion_page' && $view->current_display == 'page') {
    $thread_id = $view->args(1);
    //check argument is an integer before putting it in a query
    if((is_numeric($thread_id) && $thread_id >= 1 && $thread_id == round($thread_id))) {
      $query->add_where(1, 'thread', $thread_id.'%', 'LIKE');
    } else {
      drupal_set_message(t('Whoops something has gone wrong. Go back and try reloading this page.'), 'error');
    }
}

```

And congratulations we have a fully working comment system.

Actually I forgot two parts: One in order to add some indented classes I added the following code to `template_preprocess_comment`:

```
    $vars['count_fullstop'] = substr_count($vars['elements']['#comment']->thread, '.');
    if($vars['count_fullstop'] > 0 && $vars['count_fullstop'] < 4) {
      $vars['classes_array'][] = 'indented_'.$vars['count_fullstop'];
    } elseif($vars['count_fullstop'] >= 4){
      $vars['classes_array'][] = 'indented_3';
    }

```

In order to get around the paging problem I display the whole thread on a single page. This doesn't bother me because I don't expect huge threads and it offloads the possible performance issues onto less valuable pages.

(A sidenote. The only reason I'm using views rather than the traditional comment system, is on certain nodes I need to aggregate comments from multiple nodes and I need to be able to filter them. If that's not the case I'd stick the normal system!)

---
Tags: 7, views, comments
---


# Question
Title: No page content displaying on front page
When I go to set my Drupal 7 site's front page (*Administration » Configuration » System » Site information*) to a basic page that I've created, and then load the front page, nothing is displayed in the content section on the front page except for the site's header (masthead, navigation, search, etc.), footer, and sidebar for that page. Basically, the content of the page won't display when it's set to be the front page. It displays fine when it's not the front page. What gives?

# Answer
Try viewing the page source to see what is there. Does it match your front page layout file?

Have you modified the front page layout file?
> 0 votes

# Answer
If Ben's solution doesn't find the problem, then check how the path aliases work.

I find the front page must be set as node/6 (say - with the correct number).

To find the node number, go to configuration and find the path aliases middle-left.

Hope that helps.
> 0 votes

# Answer
I can see that you are using YaleSites. That distribution has some very specific custom overrides for the front page. I don't think you can easily replace the content of the front page with a new node. Instead, follow the directions here: http://yalesites.yale.edu/book/adjust-pre-populated-content-your-new-yalesite

If that doesn't work, contact the people at YaleSites directly. They are very helpful.
> 0 votes

# Answer
Try this in your template file (which can be page.tpl.php OR page--front.tpl.php)

```
render($page['content']);

```

I hope it will work.
> 0 votes

---
Tags: nodes
---


title: Users are logged out when viewing nodes

text:
# Question
Title: Users are logged out when viewing nodes
I'm having a really strange problem with my test website. When users (both admin and non-admin) visit node pages, they are logged out and are being logged in again as the user who commented last on the node.

I've no idea what causes this behaviour, as I've never experienced this before. I don't have any caching modules and clearing caches multiple times brings no solution. What can cause this problem?

# Answer
I finally found the reason for this weird problem: my comments' template contained a misplaced `global $user;`. I don't know why this causes trouble, but at least it's fixed now. Hopefully, this can get people with a similar problem on the right track to find a solution.
> 0 votes

---
Tags: users
---


# Question
Title: How to create a View that shows other nodes that have the same entity reference as the current page
I have job nodes, that relate to organizations. I want a sidebar block that will display other jobs that are related to the same organization.

I have tried a lot of different permutation of contextual filters and relationships, but so far I have not been successful.

I can only get the nid of the current node via a contextual filter, but that filters the content directly. I need just to get the referenced organization node, and then filter the view by that reference, but I can't seem to make it work.

(This question is for Drupal 7 with entity reference. The same question for Drupal 6 is here).

# Answer
> 3 votes
I found another (better) solution which doesn't require writing PHP if you're referencing taxonomy terms.

1. Make sure you're filtering the view by the content type you want to view a list of, not the one you're trying to reference.
2. Add a contextual filter using the entity reference field.
3. Select 'Provide default value' and select 'Taxonomy term ID from URL'.
4. Check the box for 'Load default filter from node page, that's good for related taxonomy blocks', along with whatever other configuration you want.
5. Save the view and check it out.

---
Tags: 7, views, entities
---


title: Adding a region to the Omega template

text:
# Question
Title: Adding a region to the Omega template
I am trying to add a new region to the Omega Hero template. I have duplicated the Hero template calling it SuperHero and this is working okay. ( I have created a sub-theme ).

In the tpl file I have added the new bottom\_sidebar region:

```
<?php print render($page['sidebar_first']); ?>
<?php print render($page['sidebar_second']); ?>
<?php print render($page['sidebar_bottom']); ?>

```

In the .inc file I have added the region here:

```
regions[sidebar_first]  = First sidebar
regions[sidebar_second] = Second sidebar
regions[sidebar_bottom] = Bottom sidebar
regions[footer]         = Footer

```

I have create new stylesheets and they are working okay but the new sidebar isn't appearing in the HTML.

Any ideas on what I might be doing wrong?

# Answer
I finally found out from this post here drupal.stackexchange.com/questions/100102/… that I was overlooking the theme.info file in the themes root directory:

```
regions[sidebar_first]  = First sidebar
regions[sidebar_second] = Second sidebar
regions[sidebar_bottom] = Bottom sidebar
regions[footer]         = Footer

```

Works perfectly now. There are *three* steps to adding a region to the Omega template.
> 1 votes

---
Tags: theming
---


# Question
Title: How to use hook_theme and hook_block_view correctly
The following code works - the block\_view calls the theme function and the correct variables get passed.

Is this the right way to use these functions when you have a block and you want it themed with variables and using a specific template?

Thanks,

```
function youtube_pull_block_view($delta = '') {

    switch($delta){

      case 'youtube_pull':
      $block['content'] = theme('popular_analytics', array('videos' => get_most_popular()));
      break;
    }

return $block;
}

function youtube_pull_theme() {

return array('youtube_pull_listing' => array(
             'variables' => array('videos' => NULL),
             'template' => 'youtube-pull-listing',));
}

```

# Answer
That code would be perfectly fine, if you define a theme function and use that theme function. In your case, the code is defining the youtube\_pull\_listing theme function, but using the popular\_analytics theme function.

As for an example of `hook_block_view()` implementation that uses a theme function, see user\_block\_view(), which contains the following code.

```
  if (user_access('access content')) {
    // Retrieve a list of new users who have subsequently accessed the site successfully.
    $items = db_query_range('SELECT uid, name FROM {users} WHERE status <> 0 AND access <> 0 ORDER BY created DESC', 0, variable_get('user_block_whois_new_count', 5))->fetchAll();
    $output = theme('user_list', array('users' => $items));

    $block['subject'] = t('Who\'s new');
    $block['content'] = $output;
  }
  return $block;

```

The fact the theme function is using a template file doesn't make any difference for how the function is called. The only difference is that the variables declared in `hook_theme()` are the variables the template file will be able to access.

Keep in mind that, in Drupal 7, it is now preferable to return an array in `$block['content']`, in the same way `blog_block_view()` does.

```
  if (user_access('access content')) {
    $result = db_select('node', 'n')
      ->fields('n', array('nid', 'title', 'created'))
      ->condition('type', 'blog')
      ->condition('status', 1)
      ->orderBy('created', 'DESC')
      ->range(0, variable_get('blog_block_count', 10))
      ->addTag('node_access')
      ->execute();

    if ($node_title_list = node_title_list($result)) {
      $block['subject'] = t('Recent blog posts');
      $block['content']['blog_list'] = $node_title_list;
      $block['content']['blog_more'] = array(
        '#theme' => 'more_link',
        '#url' => 'blog',
        '#title' => t('Read the latest blog entries.'),
      );

      return $block;
    }
  }

```

The reasons why using `theme()` is bad are given in theme() renamed to \_theme() and should not be called directly, even if that change record refers to Drupal 8.

* It circumvents caching
* It circumvents defaults of types defined in `hook_element_info()`, including attached assets
* It circumvents the pre\_render and post\_render stages
* It circumvents JavaScript states information
> 5 votes

# Answer
I would say it would be preferable to return a render array as opposed to rending the output in block\_view. This would give other modules an opportunity to edit your modules output before it is rendered.

An example of doing it this way would be:

```
function youtube_pull_block_view($delta = '') {
    switch($delta) {
        case 'youtube_pull':
            $block['content'] = array(
                '#theme' => 'youtube_pull_listing',
                '#videos' => get_most_popular(),
            );
            break;
    }
    return $block;
}

```
> 1 votes

---
Tags: blocks
---


# Question
Title: In Drupal Commerce how can you turn product select box options into images?
As seen in the image below, how can I turn the product dropdown options into selectable images instead? Is there a module for this or does this have to be done via js/css?

# Answer
> 1 votes
If you need images (not just colored blocks) as commerce product options take a look at commerce\_options\_as\_images

I've created this module and use in on my projects.

# Answer
> 2 votes
ok seems that this module does the trick:

https://drupal.org/project/commerce\_fancy\_attributes

> This module provides a "Rendered term" attribute mode, that shows the rendered term instead of a radio button (degrades to a normal radio button when JS is off) on the add to cart form.
>
> Example usage: 0) Enable this module. 1) Create a Color vocabulary, add a text field called "Color" that will hold hex values. Go to the "Manage Display" screen of that vocabulary, click the tab called "Add to Cart form - Attribute", enable only the color field (with the label hidden, and using the "Color" formatter). 2) Create several terms with matching hex colors (Black: #000000, White: #ffffff, etc). 3) Add a Color taxonomy\_term\_reference field to a product type. 4) When you add the color field on the product type, tick the checkbox "Enable this field to function as an attribute field on Add to Cart forms." and select "rendered term" as option of the "Attribute selection widget".
>
> The Add To Cart form will now show the colors. Of course, imagefields can be used instead of "textfields holding hex values" rendered as images.

---
Tags: 7, commerce, forms
---


# Question
Title: How to remove a unique key in an update hook
I have a primary key and a unique key in my modules' schema. I need to remove the unique key.

To remove an an index it is simple:

```
function draggableviews_update_7205() {
  if (db_index_exists('draggableviews_structure', 'entity_id')) {
    db_drop_index('draggableviews_structure', 'entity_id', array('entity_id'));
  }
}

```

There is a db\_index\_exists() function. There is db\_drop\_unique\_key() and db\_add\_unique\_key() function, but no db\_unique\_key\_exist().

How do I remove the unique key in an update hook?

# Answer
> 1 votes
All of the core schema classes (mysql, pgsql & sqlite) check for the existence of the constraint before actually dropping, so you don't have to check yourself. If you do you're actually doubling up on a DB op unnecessarily.

To cover all eventualities your code could look something like this:

```
try {
  if (db_drop_unique_key($table, $name)) {
    // Constraint was found and removed.
  }
  else {
    // Constraint was not found, nothing was altered.
  }
}
catch (PDOException $e) {
  // Constraint was found, but something went wrong, see $e->getMessage() for more info.
  throw new DrupalUpdateException($e->getMessage);
}

```

Incidentally, a unique constraint is treated the same as an index by the core schema classes, so `db_index_exists()` can be used to check for them too.

# Answer
> 1 votes
The function to drop a unique key is `db_drop_unique_key()`. You don't need to first check the unique exists, since all the database classes implemented from Drupal first check the unique key exists.

```
// DatabaseSchema_mysql
public function dropUniqueKey($table, $name) {
  if (!$this->indexExists($table, $name)) {
    return FALSE;
  }

  $this->connection->query('ALTER TABLE {' . $table . '} DROP KEY `' . $name . '`');
  return TRUE;
}

```

```
// DatabaseSchema_pqsql
public function dropUniqueKey($table, $name) {
  if (!$this->constraintExists($table, $name . '_key')) {
    return FALSE;
  }

  $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT "' . $this->prefixNonTable($table, $name, 'key') . '"');
  return TRUE;
}

```

```
// DatabaseSchema_sqlite
public function dropUniqueKey($table, $name) {
  if (!$this->indexExists($table, $name)) {
    return FALSE;
  }

  $info = $this->getPrefixInfo($table);

  $this->connection->query('DROP INDEX ' . $info['schema'] . '.' . $info['table'] . '_' . $name);
  return TRUE;
}

```

There isn't `db_unique_key_exists()`, nor a `db_primary_key_exists()`, and you should not really need them, since the methods used to drop them first check they exist.

As for using `db_index_exists()`, you cannot use it for unique/primary keys because it does not guarantees compatibility with all the database engines. In fact, the database engine for PostGreSQL uses `DatabaseSchema_pgsql::constraintExists()` to verify the unique/primary key exists.

```
// DatabaseSchema_pgsql
public function dropPrimaryKey($table) {
  if (!$this->constraintExists($table, 'pkey')) {
    return FALSE;
  }

  $this->connection->query('ALTER TABLE {' . $table . '} DROP CONSTRAINT ' . $this->prefixNonTable($table, 'pkey'));
  return TRUE;
}

```

---
Tags: database
---


# Question
Title: Changing Site Background on button (and carrying it over to all pages on site)
i'm trying to create a drupal site where under the logo, there would be three options visisble (light, dark, color), and once the user clicks on one of them, the site background will change.

now i know that this is easy to do with javascript (button, changing css background-image element)

but, how can i carry it over so that if the user clicks on a link on the site, the background-image stays the same without revolting to default?

i couldn't find any resources on how to do it, but i would gladly appreciate all of your help and anyone else on the interwebs with the same idea :)

# Answer
You could change the background with JavaScript and also save that preference in the user's Local Storage - which is basically a cookie that doesn't get sent to the server. It gets erased when cookies get erased.

First you need a JavaScript function to check that LocalStorage is available. Here is the function I use, cribbed from Stack Overflow:

```
function localStorageTest(){
  var test = 'test';
  try {
    localStorage.setItem(test, test);
    localStorage.removeItem(test);
    return true;
  } catch(e) {
    return false;
  }
}

```

You'll throw an exception if the localStorage object is not available (e.g. if cookies are completely disabled), so that's why the try/catch.

Then you need to check for a preference when the page loads. I'm using jQuery here:

```
if (localStorageTest()) {
  var bgcolor = localStorage.getItem('bgcolor');
  $('#page').css('background-color', bgcolor);
}

```

Finally, some code to set the preference - assuming here we are setting the same color as the button. You could use another attribute on the element to store the value. jQuery again:

```
$('#button').click(function() {
  var bgcolor = $(this).css('background-color');
  $('#page').css('background-color', bgcolor);
  if (localStorageTest()) {
    localStorage.setItem('bgcolor', bgcolor);
  }
};

```

Just to add some Drupal to this answer, there is a Local Storage module that doesn't quite do this yet, but could potentially work if you set up a custom form and send the color choice as an AJAX form submit.

Also consider the Session Cache API module if you are going to elaborate on this example - it won't do what this example does, but it can help perform similar tasks.

I haven't tested this code, so there may be errors - consider it at least a roadmap to accomplishing the task.
> 2 votes

# Answer
Try the Sweaver module

> Sweaver offers a visual interface for completely changing your Drupal theme without knowing any CSS. Through a bar that sits at the bottom of your screen, you can change the fonts, colours, dimensions etc of all your design elements and see the changes real-time. If you are happy with the changes, you can easily save it as a revision to activate immediately or save for later.
>
> Advanced users will find a highly pluggable and configurable system that allows full manipulation off the interface and extendability of the functionality.

Have a look on some similar modules

Flexible Colors \- Flexicolor provides a flexible method for Drupal Designers to provide content administrators with ways to color text and backgrounds on different parts of the site.

DesignKit \- DesignKit is a small API module lets themes provide options for customizing colors and images.
> 0 votes

---
Tags: theming
---


# Question
Title: Files (±50MB, audio) automatically repetitively deleted (after ± a couple of hours-days?)
Might I ask you what can be the cause and solution of:

the automatic dissapearing of "large" files (±50MB, such as an audio file) that I have manually put into the root folder of my Drupal website/installation, using a FTP-client?

Does this has something to do with CRON (just a wild guess)? Is it not smart to manually (FTP) upload files into the root folder? Should a module be used at all times?

# Answer
> 0 votes
The problem was not related to Drupal. The problem was a "right" (and the claim thereof) reserved by my webhost:

> However, we reserve a right to remove files larger than 5 MB, if some day we will start running out of disk space.

Perhaps this question is not very useful here on Drupal-Stackexchange any longer, since I was just too dumb to have checked my hosting policy?

---

A solution could be to put the files with a different host, like Dropbox or Google Drive. If you would have any suggestion of a good service, it would always be welcome.

# Answer
> 1 votes
> Does this has something to do with CRON (just a wild guess)?

No, drupal won't delete files in the folder, it must be something else on your server.

> Is it not smart to manually (FTP) upload files into the root folder? Should a module be used at all times?

Files should be in your files directory (usually sites/default/files) if you're uploading them via the UI so Drupal can manage them. If they're more static, they should be in a module/theme folder.

---
Tags: files
---


# Question
Title: Customizing search results page to use template.php and search-results.tpl.php
I'm using Drupal 7, the basic Drupal search tool. I like what it returns as far as the actual node pages. However, I want to customize the main search results page that shows a list of results after a user enters a term to search by.

Right now it shows a list with a linked title to the node (fine), and then a 'summary' (if you can call it that) that's sort of a jumbled mess of the URL, part of the description field, and some other fields. I just want the description to show up there. I'd also like to add the date field and the associated image for the node in the search results. So I've discovered that I need to customize template.php mytheme\_preprocess\_search\_results function and also search-results.tpl.php (results NOT result).

But I can't figure out how to parse out individual items from what the database is returning so I can make sure to only print those out in the tpl file. I did a var\_dump on $search\_results and see it returns a big 'ol chunk of HTML and database data...but how do I return just individual fields from the database and print those out?

Right now it just does a print $search\_results.

I tried print $title and print $url but drupal complains it doesn't recognize those vars. So what are the vars and how can I use them to display what I want?

I'm also noticing it's showing the author and date for each node in the search results (although I hid this information in the content type)...so I'd also like to hide that information in the search results.

I've found a bunch of stuff online that led me to those two files I referenced, for changing the search results...but nothing that specifically addressed how to grab and use individual fields from the database. I also don't want to use a module, I want to do this with template.php and the tpl.php files if possible.

Thanks for your help in advance!

# Answer
To change the snippet (that jumbled mess you mention), use theme\_preprocess\_search\_result() (you want to override each search result, not the page of search results). Explicitly set $variables\['snippet'\] to the value you want to display.

A common tactic is to use the node's teaser view.

```
function mytheme_preprocess_search_result($variables) {
  $teaser = node_view($variables['result']['node'],'teaser');
  $variables['snippet'] = drupal_render($teaser);
}

```

You can manage the node's teaser in Admin -\> Structure -\> Content Types -\> Your content type -\> Manage Display -\> Teaser as always.

There's a no-code approach also. While you're managing displays, check out the expandable fieldset for 'Custom display settings' and check the one for 'Search results highlighting input'. Here you can control the fields you want to display, but Drupal will still show only a snippet, and it will highlight where in the node your search terms show up. Ditch the preprocess function in this case.

Here is one more example with the theme\_preprocess\_search\_result() function that shows the first 160 characters of the body field: https://alastaira.wordpress.com/2011/01/07/customising-the-search-results-snippet-in-drupal-7/ (note that this one does not check for language).
> 3 votes

---
Tags: search
---


# Question
Title: How to manually create a menu item for a taxonomy term?
We need to create menu items out of some taxonomy terms in D7. Currently we do this manually by switching between taxonomy and menu administration pages. That is, we:

1. In the vocabulary administration page, create a term. Set the term's path.
2. In the menu administration page, create a menu item pointing to the path of the above term.

This can get quite tedious. There are some ways to automate this but we still want to create menu items manually for the sake of flexibility. For example, we need to create several menu trees from a single vocabulary. Also, the terms that would get a menu item are more or less hand-picked in our case, so they may not be easily selected with a view. Ideally we just need some way to simplify managing the menu item of a term.

It would be great if there is a "menu settings" tab when editing a term, just like the same tab you get when editing a node. That way we could have a single interface to manage the term and the menu item it created.

I am wondering if there is already a module for this.

# Answer
I don't know if there is a module for this, but what you can do is to create it via views. There are two ways I can see:

1. Install Entityqueue.

> The Entityqueue module allows users to create queues of any entity type. Each queue is implemented as an Entityreference field, that can hold a single entity type.
>
> For instance you can create a queue of:
>
> * Nodes
> * Users
> * Taxonomy Terms

2. Install Flag and Views Bulk Operations, then add a bulk operation on the flag in the specific view's UI.

Make sure to cache your views for better performance.
> 1 votes

---
Tags: taxonomy-terms, navigation
---


title: Error after validation by email

text:
# Question
Title: Error after validation by email
I have the following problem with drupal 6 and I am using the Login Tobogan module. When an user creates a new account in Drupal, the user receives the respective email. When the users click in the link for validate the account, the account is validated but appears the next error:

```
Unable to send e-mail. Please contact the site administrator if the problem persists.
You have successfully validated your e-mail address.

```

Thanks for your help.

# Answer
> 0 votes
I have disabled the Login Tobogan and I have enabled again the Login Tobogan again and the error was fixed.

# Answer
> 0 votes
I have this problem once, but then realized that it happened for wrong email configuration. For my case, it was the server restricted gmail mail address to send emails from the servers. So, I changed the site email address something to mymail@mydomain.com & it worked.

If you're using smtp module, then please check all other settings on smtp page as well, specially web-server username& passwords to match your hosting mailbox password.

Send a testing emails & enabling debug option will help you to understand better if other problems were there.

Hope now you can use LoginToboggan & smtp both without that problem :)

---
Tags: 6, users
---


# Question
Title: How to restrict node view to users by registration date?
In short I'm trying to find a solution to:

1. Restrict view access to certain custom node types by the date the user registered
2. The user would be able to see restricted content created in the month they registered and any future month while their user account is active, but nothing before the date the account was created
3. There is existing content restrictions and functionality for the same users on the same content. Only certain roles can see selected node types and this is selected when the user is created (manually). This is managed by https://www.drupal.org/project/nodeaccess

This website has restricted content that only members (registered users) can see.

These fall into several categories and the content is divided into these categories too. Depending on the type of member and what you been given access too, you will only be able to see that content. This is managed by Node Access and works well and as intended.

A new requirement has now popped up after the fact where this content access should be further restricted. It should honour the previously mentioned restrictions managed by nodeaccess but now apply additional parameters. All these are relevant to the month in which the user's account is created:

1. Restricted content posted before must not be available
2. Restricted content posted after must be available (and future content too, but still honouring the nodeaccess restrictions)

I'm fairly capable with Drupal dev, but cannot write code or rules which I think this requirement is leaning towards.

Anyone got any suggestion that will work or can perhaps point me in the right direction to get a start?

# Answer
> 1 votes
You need use this hook https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook\_node\_access/7

So in your module you need code smth like this

```
function YUORMODULE_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if ($op == 'view') {
    global $user; // get current user
    // check user register date
    if ($user->created < $node->created) {
      return NODE_ACCESS_DENY;
    }
  }

// Returning nothing from this function would have the same effect.
  return NODE_ACCESS_IGNORE;
}

```

---
Tags: users
---


# Question
Title: Insert several lines in field collection programmatically
I have a problem with field collection and entity reference fields. I have a field collection called 'field\_co\_intervenant' and i want to add several entities in this field collection and after saved my node. But i got an error with the index i think, because when the node is saved, there is just one reference entity in my field collection. You can see the code here :

$intervenant is the array of my 'nid'.

```
if(!empty($intervenant)) {
    //Create entity
    $fieldcollection = entity_create('field_collection_item', array('field_name' => 'field__doc_fc_intervenant_tab'));
    //Attach entity
    $fieldcollection->setHostEntity('node', $node);
    //Fill field
    $i = 0;
    foreach ($intervenant as $val) {
        if($val != null) {
            $fieldcollection->field_fc_intervenant_tab[LANGUAGE_NONE][$i]['target_id'] = $val;
            $i++;
        }
    }

    //Save entity
    $fieldcollection->save();
}

```

How can i save all my values in the field collection and not just one ?

Thanks

# Answer
> 3 votes
**First be sure that that field in your field collection field setting accept multi value** then try save your item with

```
  $node->field_fc_intervenant_tab['und'][] = array('value' => $field_collection_item->item_id,
    'revision_id' => $field_collection_item->revision_id,);

```

and finally be something like

```
if(!empty($intervenant)) {

    // you should have $node here
      $field_collection_item = NULL;
      $field_collection_item = entity_create('field_collection_item', array('field_name' => ''field__doc_fc_intervenant_tab '));
      $field_collection_item->setHostEntity('node', $node);
      $field_collection_item->save(TRUE);
          foreach ($intervenant as $val) {
             if($val != null) {
      $node->field_fc_intervenant_tab['und'][] = array('value' => $field_collection_item->item_id,
        'revision_id' => $field_collection_item->revision_id,);
}
}
    $fieldcollection->save();
}

```

---
Tags: nodes, entities
---


title: How do I add shipping costs to orders?

text:
# Question
Title: How do I add shipping costs to orders?
I have a really complex set of shipping rules

I have three product types

Product type A with a rate of £1 per product Product type B with a rate of £2 per product Product type C with a rate of £3 per product

A customer can add any combination of products into their cart so

2 x Product type A 1 x Product type B 1 x Product type C

I have created rules to loop through commerce\_line\_items and get the individual shipping costs for product types based upon a field in the commerce\_product entity and I have got it so it calculates quantity times shipping cost.

What I do not know and cannot work out is how I then add these shipping costs back to the order, there seems to be no way to set the value of a shipping service.

Also I do not know how to parse the line items for each product type and calculate the shipping costs based upon each product type. So I need a condition check on the product type of each line item in the order to obtain the product type and then do the calculations based upon the correct shipping rate and quantity.

Any advice would be fully appreciated.

# Answer
> 0 votes
1. Edit the Reaction Rule "Collect rates: Flat Rate" and add conditions if you wish, so that it only applies to certain Product Types, or to an Order whose total is over a certain amount, for example. (Note that because you are using Conditional Rules you could also put such logic in the Action of your shipping pricing rule \[see below\])
2. Create a Shipping Service for your Flat Rate Shipping Method. For example, "My Basic Shipping." Give it a base rate - can be $0, or whatever.
3. Create a shipping pricing Rule that applies shipping charges to Products through the Service you just created. You can use conditionals in the Rule to apply the shipping based on SKU, Product Type, price, or whatever. You can use extra modules to base it on size and weight, day of the month, whatever.

Here's an example of a Price Calculation Rule. My Shipping Service is called 'swag shipping' and the Rule adds to the shipping cost based on the country:

```
{ "rules_ship_s_store_shipping_surcharge_by_country" : {
"LABEL" : "Ship\u0027s Store: Shipping Surcharge by Country",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "Commerce Checkout" ],
"REQUIRES" : [
  "rules",
  "commerce_order",
  "rules_conditional",
  "commerce_line_item",
  "commerce_shipping"
],
"ON" : { "commerce_shipping_calculate_rate" : [  ] },
"IF" : [
  { "data_is" : { "data" : [ "commerce-line-item:type" ], "value" : "shipping" } },
  { "data_is" : {
      "data" : [ "commerce-line-item:commerce-shipping-service" ],
      "value" : "swag_shipping"
    }
  },
  { "entity_has_field" : {
      "entity" : [ "commerce-line-item:order" ],
      "field" : "commerce_customer_shipping"
    }
  },
  { "NOT commerce_order_compare_address" : {
      "commerce_order" : [ "commerce-line-item:order" ],
      "address_field" : "commerce_customer_shipping|commerce_customer_address",
      "address_component" : "country",
      "value" : "US"
    }
  }
],
"DO" : [
  { "CONDITIONAL" : [
      {
        "IF" : { "commerce_order_compare_address" : {
            "commerce_order" : [ "commerce-line-item:order" ],
            "address_field" : "commerce_customer_shipping|commerce_customer_address",
            "address_component" : "country",
            "operator" : "is one of",
            "value" : "CA\u000D\u000AMX"
          }
        },
        "DO" : [
          { "commerce_line_item_unit_price_amount" : {
              "commerce_line_item" : [ "commerce_line_item" ],
              "amount" : "1000",
              "component_name" : "flat_rate_swag_shipping",
              "round_mode" : "1"
            }
          }
        ]
      },
      { "ELSE" : [
          { "commerce_line_item_unit_price_amount" : {
              "commerce_line_item" : [ "commerce_line_item" ],
              "amount" : "1500",
              "component_name" : "flat_rate_swag_shipping",
              "round_mode" : "1"
            }
          }
        ]
      }
    ]
  }
]

```

} }

IMPORTANT NOTE: You may have trouble after you get your shipping working, to display your shipping line items in your Order display, for example in the Order acknowledgment e-mail that comes by default with Commerce. You need to make some rather complicated configuration changes to get this to work. Please see the article How to display all Drupal Commerce line items using a token if you get that far.

---
Tags: commerce, rules
---


# Question
Title: Term reference field lists the terms for all the languages
What I meant is that I have the i18n module installed and configured for content and taxonomies, this is what I need

I have a taxonomy called "Colors" I have translated all the terms of this taxonomy from spanish to english

I have a term reference field in a content type that points to the taxonomy "Colors"

While I create the the node of that content type and try to select a color, the select list shows me all the colors in english and spanish, is there a way of update that term reference select list to show only the terms for the selected language for that node?

Check the image and you will understand what I mean

If you check the image I selected in the list as language spanish, but in the color checkboxes it shows me all the terms in both languages (English & Spanish)

How to show the terms depending of the selected language while creating the node?

This is the image of the translated and original taxonomy terms in Spanish and English

# Answer
Try selecting `Localize. Terms are common for all languages, but their name and description may be localized` as the **Translation mode**, after that remove the terms that you added separately for Spanish language and edit each term that are there in English and translate it to Spanish.
> 1 votes

# Answer
If you want different colors for each languages, set "Translate. Different terms will be allowed for each language and they can be translated." in the vocabolary terms, after check in admin/config/regional/i18n/select -\> Select taxonomy terms by language
> 0 votes

---
Tags: 7, taxonomy-terms, forms, i18n-l10n
---


# Question
Title: How to resolve an XMLReader warning produced by Wordpress Migrate module?
I'm converting a Wordpress site to Drupal. To do so, I need to import a wordpress export file. But whenever I try to import my wordpress export file, I get this error:

> Warning: XMLReader::open() \[xmlreader.open\]: Unable to open source data in WordPressBlog-\>\__construct() (line 188 of /mnt/www/html/dev/docroot/sites/all/modules/wordpress\_migrate/wordpress.inc).
>
> Exception: Could not open XML file wordpress://blog.wordpress.2013-09-05.xml in WordPressBlog-\>\__construct() (line 219 of /mnt/www/html/dev/docroot/sites/all/modules/wordpress\_migrate/wordpress.inc)

As shown in the path names within the error mesages also (ie: 'wordpress\_migrate'), I'm using the Wordpress Migrate module. For this module, only a 7.x version exists.

I'm not quite sure why it can't read the XML file. I've run the file through the xmllint command with no errors.

Can anyone help me with this?

# Answer
I had the exact same error. I uninstalled all the WordPress migrate and migrate modules (uninstalling migrate may not have been necessary), removed from site directory and then reinstalled.

I re-installed Migrate 7.x-2.6 and WordPress Migrate 7.x-2.3-beta2+4-dev.

After that the import worked.
> 1 votes

---
Tags: migrations
---


# Question
Title: A better solution to make image field into div background?
In Drupal 7, I want to turn my image field in Views to looks something like

```
<div style="background-image:url([field_someimgefield_image]);"></div>

```

so I can apply the JQuery Parallax scrolling effect. However, I'm not able to get the full "absolute path" of my image, even I use the "absolute path" on "output this field as a link" and "strip HTML tags" features. All I got is the file name, not the full absolute path.

Another issue I have is the "Global: Custom text" in fields, it does not has the text filter option, so I would not be able to write the above code.

So far, I only found the "BackgroundField" module for the replacement. Anyone know a better solution for div background image?

PS: the CSS trick only make it looks similar, they are totally differnt.

**------ update info on Feb. 2 2015 : 12:58pm ---**

The Views that I have is a list of node that contain Title and other fields. Therefore, each node should has their own background from image field.

**------ update info on Feb. 2 2015 : 02:46pm ---**

Looks like the "BackgroundField" module I mentioned above is similar to Background Images, which does not work too.

# Answer
> 4 votes
There is also the Background Images module suite:

> Background images is a collection of modules that allows users to add background images to html elements on pages of the site.

There is also a Field Group sub-module for background image support called Field Group Background Image:

> This module creates a field group display formatter that consists in a wrapper with a background.
>
> The background can be set from:
>
> * An image field of the entity being displayed
> * A color field (of Color Field or jQuery Colorpicker modules)
>
> This module can be used alongside Display Suite, and is particularly useful for creating custom Fieldable Panels Panes bundles.

You mention parallax scrolling ... I know what that is, I've never had to implement it -- you may want to try to use Parallex Background:

> This a simple module that allows to set a vertical Parallax effect on the background of any element on the DOM.

I kindly suggest you work more on your Google-fu skills.

# Answer
> 4 votes
Instead of using one of those modules, you could override the field output through a theme function like this:

```
    function MYTHEME_field__field_someimgefield_image($variables) {
        $output = '';

        // Render the label, if it's not hidden.
        if (!$variables['label_hidden']) {
            $output .= '<div class="field-label"' . $variables['title_attributes'] . '>' . $variables['label'] . ': </div>';
        }

        // Render the items.
        $output .= '<div class="field-items"' . $variables['content_attributes'] . '>';
        foreach ($variables['items'] as $delta => $item) {
            // Generate styled background image.
            $img_uri = $item['#item']['uri'];
            $img_style = $item['#image_style'];
            $bg_img = image_style_url($img_style, $img_uri);
            $classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
            // Write image url to inline css and drop the rendered item.
            $output .= '<div class="' . $classes . '"' . $variables['item_attributes'][$delta] . ' style="background-image:url(' . $bg_img . ')"></div>';
        }
        $output .= '</div>';

        // Render the top-level DIV.
        $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

        return $output;
    }

```

In your view, enable "Use field template" in the field's style settings. Thus Views will render your field via the theme function above. Of course, you will have to give the field some width and height to make the background image visible.

# Answer
> 2 votes
You need Image URL Formatter module perhaps.

> This module add\[s\] a url formatter for image field. Then you can output image url directly.

Works with Views. It will give you an additional "Formatter" choice, which should say something like "Path to the image" or "URL to the image".

Also regarding "Global: Custom text", I think this is meant to be FULL HTML, but it is run through filter\_xss and other various sanitizers. So you can put the HTML directly in the field, you don't need a Text input filter.

# Answer
> 0 votes
Maybe the Dynamic Background module is what you need as it allows you to target a div? It also has a handy Context Background for setting up backgrounds based on context for things like dates, paths, etc. https://www.drupal.org/project/dynamic\_background

---
Tags: views, entities, media
---


# Question
Title: Print Primary and Secondary Menu Links separately
I have a main menu with primary, secondary and tertiary links. The primary links will be positioned top right of the page. I want the sub menus (secondary/tertiary links) to print in a separate wrapper that will span the width of the browser. I cannot use absolute position because I need the sub menu to push down the content below it when I hover over the primary links. How can I do this with templates?

# Answer
> 1 votes
Check out the theme\_menu\_link and theme\_menu\_tree hooks. You can add them to a custom theme, and they give you full access to the links as they are built.

Take a look at the following line in theme\_menu\_link:

```
if ($element['#below']) {
  $sub_menu = drupal_render($element['#below']);
}

```

If you add a test to check if the link being tested is top tier than you can change the $element\['#below'\] to suit your needs. checking for top tier is as simple as

```
$element['#original_link']['plid'] == 0

```

The parent link id of top tier elements is 0, so this works out. Then, if it is top tier and has links below it, add a theme wrapper that will allow you do what you want it to. For example:

```
if ($element['#below']) {
  if ($element['#original_link']['plid'] == 0){
    $element['#below']['#theme_wrappers'][] = 'my_custom_theme_wrapper';
  }
  $sub_menu = drupal_render($element['#below']);
}

```

I am seeing the original theme wrapper is `menu_tree__main_menu`. If you want to completely replace it use you should unset that one, then set a new one as mentioned above.

If you want some pointers on theme wrappers check this post.

# Answer
> 0 votes
I think you should create a menu block for the 1st and one for the 2+ level of main menu which you can format with css separately.

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


title: Auto posting to Facebook page

text:
# Question
Title: Auto posting to Facebook page
I am using the Drupal for Facebook module on both a D6 and D7 site to post to a FB page (not a group or a personal account/wall) via streams.

It is working fine except I would like the 'Post to Facebook' checkbox be automatically checked ***only*** when the node is created, but not on subsequent edits. My users won't check this box on their own (and I may not even want them to see it).

I've tried using Rules, but there seems to be no FB posting action there.

I'm assuming it can be done via hook\_form\_alter, but have had no luck with that. The Element ID for the checkbox is... fb\_stream\[fb\_stream\_do\_post\]

Any thoughts???

Thanks,

Eric

# Answer
> 2 votes
Thanks everyone.

What I was able to do was build a Rule with Form Events that sets the 'Post to Facebook' checkbox (and one for Twitter) if the current page URL matches the node edit URL. This way only the creation of a node, and not subsequent edits, are posted to FB...

I was initially going to do a hook\_form\_alter, but once the initial Rules test worked I figured I would go with it.

Rule Export \>\>

```
{ "rules_form_alter_post_to_fb" : {
    "LABEL" : "Form Alter - Article Post to FB and Twitter",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_forms" ],
    "ON" : { "rules_forms_article_node_form_form_built" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "http:\/\/www.example.com\/node\/add\/article"
        }
      }
    ],
    "DO" : [
      { "rules_forms_set_default" : {
          "form" : [ "form" ],
          "element" : "checkbox:fb_stream:fb_stream_do_post",
          "value" : 1
        }
      },
      { "rules_forms_set_default" : { "form" : [ "form" ], "element" : "checkbox:twitter:post", "value" : 1 } }
    ]
  }
}

```

# Answer
> 0 votes
Ok, so based on your example. Recall that the checked property of a toggle is a HTML attribute. Then you'd want to do something like this:

`$form_state['fb_stream']['fb_stream_do_post']['#attributes']["checked"] = "checked"`

This would produce the following HTML, IIRC:

`<input type="checkbox" name="fb_stream_do_post" checked="checked" />`

---
Tags: 7, social-network
---


# Question
Title: file_entity update means views now checks for public: in their uri?
Since a recent update, I think Views must have changed the way it links in relationships to file fields.

Now the SQL includes a WHERE clause like this:

```
EXISTS (
  SELECT fm_access.fid AS fid
  FROM file_managed fm_access
  WHERE ( (fm_access.uri LIKE 'public%' ESCAPE '\\') ) AND
  (file_managed_field_data_field_file_private.fid = fm_access.fid) )

```

Now the files that are linked here are actually private, so this clause means my view now returns nothing.

Why is Views adding this bit, and how can I stop it from doing so?

# Answer
> 0 votes
File entity adds a tag to Views' queries called `query_file_access`.

This checks to see if a user has `view private files` privilege, and if not it denies access to any private files.

So you can get this view working again by granting this privilege to that user.

I find the privilege confusing because I do not want grant access to all files to this user, and the privilege screen warns that this has security implications.

I believe it's ok as long as the node access checks are done.

---
Tags: 7, views, files
---


# Question
Title: How to make a Views Filter criteria based on another language version existing?
How to make a view that lists otherwise Finnish nodes but if there exists an English translation for the node, list that instead?

Filter criteria would be logically "Language: if there is an English translation, then that, else Finnish".

So when all nodes are Finnish, the list of the node titles would be (these are ordinals in Finnish, just for the example):

Ensimmäinen
Toinen
Kolmas
Neljäs
Viides

And then someone adds a translation to the second and third one, the list would become:

Ensimmäinen
Second \<--- now links to the English translation of the node
Third \<--- now links to the English translation of the node
Neljäs
Viides

# Answer
Answer: https://www.drupal.org/project/select\_translation. It does exactly what I need and much more.
> 0 votes

---
Tags: views, i18n-l10n
---


# Question
Title: Does Drupal cache db_query results for multiple users?
I am running into something strange and perhaps someone here can help me. I am trying to prevent two things from happening at once because the second attempt might be influenced by the first attempt.

The (simplified) code:

```
function save_my_thing($thing) {
  module_invoke_all('my_thing_presave');
    >>> INVOCATION

      if (!lock_acquire('mything_lock')) {
        // If  we cannot obtain a lock, wait.
        lock_wait('mything_lock');
      }

      $sql = "SELECT COUNT(*) FROM {my_things}";
      $count = db_query($sql, array())->fetchField();

      if($count >= 1) {
        drupal_set_message('already there','error');
        drupal_goto(drupal_get_destination());
      }

    >>> END INVOCATION

  drupal_write_record('my_things', $thing, array('tid'));
  dpm(db_query('SELECT * FROM {my_things} WHERE `tid` = ' . $thing->tid)->fetchAssoc());

  module_invoke_all('my_thing_save');
    >>> INVOCATION

      lock_release('mything_lock');

    >>> END INVOCATION

}

```

Above code works perfect if I request the function, wait for it to complete and then call it again. I end up on the page I came from with a visible error.

However if I call this function from two different windows before either of them is finished (as can occur in real life), the sql count returns 0 in both cases. The lock works, and using microtime() I can see the second call starts right after the first call releases the lock. The dpm() returns the inserted row, so the record is written before the lock is released. But `SELECT COUNT(*) FROM {my_things}` keeps returning 0.

The only thing I can think of now is some kind of fancy SQL caching layer that presents '0' to the second call for some reason, however I could find no such thing in the Drupal database code.

One more interesting thing is that when I move my lock from the custom invoking module to the main module, right before \_presave and right after \_save. It does work as expected. But then why doesn't this implementation work?

# Answer
> 0 votes
You need to put in an `else {...}` after using lock\_acquire(); or have it return right after calling lock\_wait().

Also, db\_query is not cached in any way

---
Tags: database
---


# Question
Title: Passing variables to JS from theme folder .tpl files
I use many template files in my modules via hook theme. In order to pass variable to JS files I use the method described here: https://www.drupal.org/node/304258 in the .tpl.php files:

```
$my_settings = array(
  'basePath' => $base_path,
  'animationEffect' => variable_get('effect', 'none')
);

drupal_add_js(array('myModule' => $my_settings), 'setting');

```

and then in the .js files:

```
var basePath = Drupal.settings.myModule.basePath;
var effect = Drupal.settings.myModule.animationEffect;

```

For the first time (it seems) I'm trying to pass variables to JS from .tpl files located in my theme folder. Suppose I have a content type called 'cars', I craete a page-cars.tpl.php template file in my theme folder which automatically applies to all car pages. But in these tpl files I can't pass variables to JS using the method described above. I tried switching 'myModule' to 'myTheme' but Drupal won't recognize it as a defined setting

As per Clive's instructions I added to the my\_theme\_preprocess\_content\_type(&$variables) function and it works! (thanks Clive)

# Answer
Take a look at the variable\_set function. If my memory is correct, I used this to move variables between PHP and java script.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Minutes in date value displayed never the same as value entered
I have a weird bug. On many content types, I have a Date field using the Pop-up calendar widget with the format "February 3 2014 - 2:35".

When that date is displayed, the minutes are never the same as the minutes that I entered when I saved my content. If my date field has the time value 4:15, the time displayed will be 4:12. If I change the minutes again for let's say, 4:52, the time displayed is still 4:12. And when I edit that content, the time I entered is still there, so I know it's saved correctly. If I change the hour, that change is displayed properly but the minutes stay the same.

Also, when I check recent log messages, for a given hour, the minutes displayed are always the same. Like every event that happened between 2PM and 3PM has the time 2h02.

Does anybody know what the problem might be ?

I'm on Drupal 7.34 and using Date 7.x-2.8.

# Answer
> -1 votes
Well, turns out the discrepancy was due to a bad date format ... I was using "m" for the minutes instead of "i".

My bad !

---
Tags: 7, datetime
---


title: Module and theme in one directory?

text:
# Question
Title: Module and theme in one directory?
For my project, I have a custom module, a features module and a custom theme. I want to keep all in a single Git-Repository.

The problem is: modules need to be in `sites/all/modules`, themes in `sites/all/themes`.

I know, I could bundle both in a profile. But I am already using a special profile. And as far as I know, there is no way to inherit a profile.

And yes, I know I could use symlinks. But they tend to create issues with path structures.

So is there another, maybe a "Drupal" way to bundle modules and themes in one directory?

# Answer
> 1 votes
Thanks to the suggestion of @kenorb, I have found a good way to solve this:

I init the git repository in `drupal/`, and I put only the following line into `.gitignore`:

```
*

```

Then, I add (by force) my custom module and theme folders:

```
$ git add -f sites/all/modules/custom
$ git add -f sites/all/themes/custom

```

With this, my repo still contains only my code and no Drupal modules. And this allows me even to track also my `.htaccess`, with:

```
$ git add -f .htaccess

```

---
Tags: 7
---


# Question
Title: Add callback to existing migrate field mapping
I have a use case where I want to use the callbacks functionality for the body field in a D6-\>D7 migration using migrate and migrate\_d2d modules. However, according to the above-referenced docs page, this is done when you are adding a new field mapping:

```
$this->addFieldMapping('destination_field', 'source_field')->callbacks('my_callback');

```

not adding to an existing mapping. How can I add a callback to an existing mapping? Do I have to remove and then re-add the mapping, or is there another way?

# Answer
> 1 votes
With some debugging and looking at code, it turned out to be pretty easy. All of the mappings are MigrateFieldMapping objects in $this-\>codedFieldMappings, so it's just a matter of getting a reference to that object and calling the callbacks() method. For example, to add a callback to the body field, you would use:

```
$this->codedFieldMappings['body']->callbacks('my_callback');

```

---
Tags: migrations
---


title: Add taxonomy to Views page

text:
# Question
Title: Add taxonomy to Views page
I am attempting to get a views page into a taxonomy term page using this solution to no avail.

My taxonomy page is at \[URL\]/menu-tags/resource, so I made the Views page URL \[URL\]menu-tags/resource/resource-hub. The page doesn't show up despite having the settings set up in the pathauto config and the taxonomy checks out. I'm not sure where to go from here.

# Answer
There are a number of different ways to build your own taxonomy term lists via views-driven output. One of these methods, which appears to be the one that you are working on, is to override the core taxonomy/term/% path with a view display. This "routing-level" override just ensures that all requests to a taxonomy/term/\[id\] page are handled by your view instead of the core term list callback. In order for this to work however, your view needs to use the **exact same path** as the core taxonomy term path (i.e. taxonomy/term/%), and implement a contextual filter for the term id. This path is independent of any path alias patterns you may have setup for your taxonomy terms. So if one of your term vocabularies is aliased with a pattern menu-tags/resource/\[term-name\], the actual Drupal path that views needs to respond to, and override, is still taxonomy/term/\[id\].

It's also worth pointing out that this technique has some drawbacks. Most notably you don't have the ability to define different view displays for different taxonomy vocabularies (as all vocabularies use taxonomy/term/% as their raw path by default). Because of this you may want to consider an alternative approach of using the taxonomy display module. Instead of overriding just the term path, this module overrides the actual rendering of the term page itself, and therefore has a bit more flexibility. It's also fairly easy to setup, just check out the documentation.
> 0 votes

---
Tags: views, taxonomy-terms, path-aliases
---


# Question
Title: Ajax callback does not replace the form but add a new field
I use his code to populate a select after giving à zipcode.

```
$form['responsible']['zipcode'] = array(
      '#type'               => 'textfield',
      '#title'              => t('Zipcode'),
      '#default_value'      => empty($account->Dossier->responsable->adresse->codePostal) ? Null : $account->Dossier->responsable->adresse->codePostal,
      '#required'           => True,
      '#maxlength'          => 5,
      '#ajax' => array(
        'callback' => 'ajax_get_cities_callback',
        'wrapper' => 'edit-city',
        'method' => 'replace',
      ),
    );

    $form['responsible']['city'] = array(
      '#type'               => 'select',
      '#title'              => t('City'),
      '#options'            => array(),
      '#required'           => True,
    );

```

My callback

```
function ajax_get_cities_callback($form, $form_state){
  $client = new SoapClient('myWebservice',array("trace" => true,  "exceptions" => true,));
  $requestParams = array(
    'parameters' => array (
      'numSite' => 1058,
      'typeListes' => array(
        'RechercheTypeListe' => array(
          'typeListe' => 'LST_VILLE',
          'param1' => $form_state['values']['zipcode']
          )
        )
    )
  );
  $dataresponse->requestParams = $requestParams;
  $response = "";
  try {
      $response = $client->__Call('GetListes',$requestParams);
  }
  catch (Exception $e) {
    var_dump($e);
    return False;
  }

  $form['responsible']['city']['#options'] = array(
    0 => "aaaa",
    1 => "test2",
    2 => "test3"
  );

  return $form['responsible']['city'];

}

```

When I give a zipcode, a new select is created behind the first one.( picture here: https://www.uploady.com/#!/download/zjKvglzRTSe/ZIMYkjSAAaLrUFUq) I tried to return only $form\['responsible'\]\['city'\]\['#options'\] but it does not fixe.

Any idea ?

Thank you

# Answer
You have to setup a wrapper on the field you want to update :

```
$form['responsible']['zipcode'] = array(
      '#type'               => 'textfield',
      '#title'              => t('Zipcode'),
      '#default_value'      => empty($account->Dossier->responsable->adresse->codePostal)
                                    ? Null
                                    : $account->Dossier->responsable->adresse->codePostal,
      '#required'           => True,
      '#maxlength'          => 5,
      '#ajax' => array(
        'callback' => 'ajax_get_cities_callback',
        'wrapper' => 'div_city_wrapper', // Changed here
        'method' => 'replace',
      ),
    );

    $form['responsible']['city'] = array(
      '#type'               => 'select',
      '#title'              => t('City'),
      '#options'            => array(),
      '#required'           => True,
      '#prefix'           => '<div id="div_city_wrapper">', // Added this
      '#suffix'           => '</div>', // Added this
    );

```

The callback function seems to be fine as it returns the wrapped form element ($form\['responsible'\]\['city'\])
> 0 votes

---
Tags: ajax
---


# Question
Title: The Expanding & Folding of the information related to a checkbox isn't working in drupal 7.34
I am using Drupal-7.34, and after enabling the following modules:

* Admin-Menu.
* Ctools.
* IMCE.
* IMCE Wysiwyg Bridge.
* insert.
* jquery-Update.
* Libraries.
* Link.
* Pathauto.
* Token.
* Views.
* Wysiwyg.
* Webform.

I got a problem about the "Expanding & Folding of the information related to a check box"

**For Example:** After enabling all the modules listed above, when I enter into the configuration of the "View UI" Module and try to "Add a view"; And after checking/unchecking the check boxes of "Description", "Create a Page View" or "Create a Block View", the information related to these check boxes is not expanded or folded. (Just the mark of checking/unchecking will appear/disappear and nothing else happen.

Note that before enabling the following modules listed above, this problem didn't appear and everything was great...

**any help will be appreciated, Thank you in advance.**

IN THE IMAGE BELOW, YOU CAN NOTICE HOT THE DESCRIPTION CHECK BOX IS CHECKED BUT THE TEXT BOX TO WRITE A DESCRIPTION ISN'T APPEAR AND ALSO HOW THE CREATE A PAGE CHECK BOX IS UNCHECKED BUT ALL THE INFORMATION RELATED TO IT STILL APPEARED AND DIDN'T DISAPPEAR OR FOLD...

# Answer
I had a similar issue back in August. It was the jQuery update module that was the problem. The configuration at this link finally worked for me: https://www.drupal.org/node/1810656#comment-8677587
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Why does default.settings.php suggest writing the value of the hash salt in an external file?
The default.settings.php file contains the following comment:

> For enhanced security, you may set this variable to the contents of a file outside your document root; you should also ensure that this file is not stored with backups of your database.
>
> Example:
>
> ```
> $settings['hash_salt'] = file_get_contents('/home/example/salt.txt');
>
> ```

Assuming the attacker was able to create a PHP file inside my Drupal installation, in which way does writing the hash salt in a file increases the security? In any case, the attacker would be able to read the value for `$settings['hash_salt']`. Eventually, the attacker could change the value for `$settings['hash_salt']`, but does doing this make any sense for the attackers to do?

# Answer
The main reason to do this is to prevent the salt from accidentally being committed to your content versioning system.

Most advanced hosting environments (both Drupal hosts and all-in-one Drupal stacks) provide ways to do this.

Similarly, it is useful to go through the trouble of abstracting DB settings and the like, both for security and to make it easier to move your code from one environment to the next.
> 4 votes

---
Tags: security
---


# Question
Title: Trying to using Rules to create page redirects to external links per node, but it's not working
I like using Rules and am trying to create a page redirect, for a certain content type i’ve created. So instead of the user viewing the node, they get redirected to an external website. the site address get’s input via a simple text field in the content type i’ve created. i’ve tried different setting for this field, plain text, full html.

In the action part of the Rule i’v set as System/Page Redirect and the value as \[node:field\_ext\_link\_text\]. But it’s doing something to the URL (decoding or encoding??) and instead say going to www.somewebsite.com, i get a page not found that reads

"/%3Cp%3E%3Ca%20href%3D%22http%3A//www.somewebsite.com%22%3Ewww.somewebsite.com%3C/a%3E%3C/p%3E%0A" could not be found.

i really don’t understand what it’s doing to this URL.

i also installed the link module and tried using a field type link but got similar results. i've also tried ommitting http://,

i also tried using Rabbit Hole module to accomplish the same thing, but got similar results.

Any help would be greatly appreciated. … have spent way to much time on this…(!)

# Answer
Use the field redirection module. A great overview was provided by llulabot

https://www.lullabot.com/blog/article/module-monday-field-redirection

Mind you I've used Views with Conditional Fields to allow a single link to be either internal or external using a views template override when clicked (based on a radio button in the content type). Field redirection is easier to use than your custom solution.
> 1 votes

---
Tags: rules, redirection
---


# Question
Title: Node custom property exposed as extra field
I'm trying to add custom property to node bundle, my code so far:

```
/**
 * Implements hook_entity_property_info_alter().
 */
function mymodule_entity_property_info_alter(&$info) {
  $properties = &$info['node']['bundles']['program']['properties'];

  $properties['last_episode_date'] = array(
    'label' => t("Last episode date"),
    'type' => 'date',
    'computed' => TRUE,
    'entity views field' => TRUE,
    'metadata controller class' => 'EntityDefaultMetadataController',
    'extra fields controller class' => 'EntityDefaultExtraFieldsController',
    'getter callback' => 'mymodule_last_episode_date_getter',
    'description' => t("Date of the last episode."),
  );
  return $info;
}

/**
 * last_episode_date property getter.
 */
function mymodule_last_episode_date_getter($data, array $options, $name, $type, $info) {
  return REQUEST_TIME;
}

```

The goal is to have this property available in views and in node as extra field - in views it is available, but I cannot make it to work as extra field. Anything is missing/is wrong? Documentation on this is kind of lacking :( .

# Answer
Looking at Entity module's hook\_field\_extra\_fields() implementation:

```
/**
 * Implements hook_field_extra_fields().
 */
function entity_field_extra_fields() {
  // Invoke specified controllers for entity types provided by the CRUD API.
  $items = array();
  foreach (entity_crud_get_info() as $type => $info) { ... }
  return $items;
}

```

It only looks for entity types provided by the CRUD API -- in other words, entities whose controllers inherit from EntityAPIControllerInterface. Node entities use NodeController.

You can still do this conventionally, outside of Entity API -- implement hook\_node\_view() to insert your pseudo-field in $node\['content'\], then implement hook\_field\_extra\_fields() to expose that pseudo-field to the node's "Manage display" tab.
> -1 votes

---
Tags: entities
---


title: Pager encoded commas

text:
# Question
Title: Pager encoded commas
I added a pager to a site I'm working on and the URL for a page comes out to: http://example.com/blog/0%2C0%2C0%2C0%2C0%2C5 which is an encoded version of \*/0,0,0,0,0,5. However, I'd like the URL to be http://example.com/blog/5 or similar.

I'm using Drupal 7.31 and have clean URLs enabled.

# Answer
> 1 votes
It sounds like you have a "Pager ID" value set in your view. From your example my guess is that it's set to "6" instead of the default "0". Check within the "Pager Options" of your view display to see if this is the case, and if so, change that value to 0 to restore the URL to a more standard form.

It's important to note that there are of course some situations where your need this pager ID to be set, notably if you have multiple views, each with pagers, displayed on the same page. If this is the case, and you *have* to use a pager ID \> 0 on one of your views, you could set it on your "secondary" view (the one users are less-likely to page through) and leave it at 0 for the "main" view.

It also looks like you have the "Clean Pagination" module installed, or something similar? Normally I think a paged URL would have the pager query string (?page=#) exposed, so you must be doing some special clean URL processing for that. Still, I think the "Pager ID" notes above would apply regardless.

---
Tags: paging
---


# Question
Title: Feed importer: field collection processor settings
I'm trying to import field collection to profile2.

I do not understand where to get in the Field Collection Processor information for the "Field/property name of Host entity GUID" and "Identifier field name" settings to fill in the text box?

Please see the image below.

Thanks!

# Answer
Finally got it to work!

**Settings for Field collection processor**

Do not update existing field collection item

Field name: (The machine-readable name of the field collection)

Host entity type: Profile

Is field: unchecked (FALSE)

Field/property name of Host entity GUID: pid

Identifier field name: pid

**Mapping for Field collection processor**

pid =\> Host Entity GUID

(and my other fields of course)

**Note:**

pid is the Profile ID.
> 0 votes

---
Tags: feeds, users, entities, importing-exporting
---


# Question
Title: Which files should I delete after a Drupal installation?
After installing Drupal, there are files in the root directory that I should delete. I know that install.php is one of those. Which other files should I delete?

# Answer
You shouldn't really delete any files. If you really wanted to, you could delete the install file and various txt files, but that's about it. A better solution if you are afraid of security is to not let the files be accessed through the web server. Drupal only use the index.php file for serving content.
> 17 votes

# Answer
The upgrade advice is the same as for installations.

http://drupal.org/upgrade/finished

The last step in an upgrade is to delete or move the following files from your site:

```
install.php
CHANGELOG.txt
INSTALL.txt
INSTALL.mysql.txt
INSTALL.pgsql.txt
LICENSE.txt
MAINTAINERS.txt
UPGRADE.txt

```
> 8 votes

# Answer
You just need to Change the file permissions if you wish for files like config.php but you don't need to delete any file, like some premium forum installations.
> 4 votes

# Answer
You shouldn't remove any files. You cannot obscure the fact that your site is running on Drupal. See: https://www.drupal.org/node/766404
> 2 votes

---
Tags: 7, security, installation
---


# Question
Title: Is there module that will add a drop down widget that auto-populates with a list of the site users?
Looking to have a "field widget" that creates a drop down populated with the site's users. I'm not sure "field widget" is the right term. I just mean a widget that's used in a field.

Does anyone know of such a module?

# Answer
You're looking for the References module

> This project provides D7 versions of the 'node\_reference' and 'user\_reference' field types, that were part of the CCK package in D6, at functional parity with the D6 counterparts. See http://drupal.org/node/533222 for details.

Similar module is Entity Reference

> Provides a field type that can reference arbitrary entities:

You can add a new field for user list by selecting ***User Reference*** as a field type and ***select list*** as Widget Type in your content type.

Here is the screenshot for that
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to programmatically render a contact form in a theme in D8
How to get the side-wide contact form (feedback) individually displayed in a custom block or other page then /contact (e.g. frontpage)?

I've tried this code, but it is not working (are contact forms entities?):

```
// get default form
// get the entity object
$default_form = \Drupal::config('contact.settings')->get('default_form');
$entity = \Drupal::entityManager()->getStorage('contact_form')->load($default_form);

// get view builder
// render view
$view_builder = \Drupal::entityManager()->getViewBuilder('contact_form');
$full_output = $view_builder->view($entity);

```

# Answer
> 7 votes
Contact form is an entity, but you can't view it.

What you want instead is an add form of a contact\_message with contact\_form as bundle.

See `ContactController::contactSitePage()` (EDIT: API docs) as example:

```
$message = \Drupal::entityTypeManager()
  ->getStorage('contact_message')
  ->create(array(
    'contact_form' => $contact_form->id(),
  ));

// This works in a controller, use \Drupal::service('entity.form_builder') elsewhere.
$form = $this->entityFormBuilder()->getForm($message);
$form['#title'] = SafeMarkup::checkPlain($contact_form->label());

```

EDIT (thanks @nilsun): Note that entityManager is deprecated in favour of entityTypeManager.

---
Tags: 8, entities, theming, emails
---


# Question
Title: myform_validate() and myform_submit() functions not responding
I have built a form from following examples on tutorials but neither the accompanying `_validate(`) nor `_submit()` functions are responding when I submit this form. This is my codes:

```
/**
*implementing foodmenu form
*/
function my_magic_foodmenu_form($form, &$form_state){
    $form = array();
    $form['choice'] = array(
        '#type' => 'select',
        '#title' => t('Choose your meal'),
        '#options' => array(
            'ricestew' => t('Rice with Stew'),
            'ricejollof' => t('Jollof Rice'),
        ),
        '#required' => TRUE,

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

    );

    return $form;
}

/**
*Implement form validation: Foodmenu
*/
function my_magic_foodmenu_form_validate($form, &$form_state){
    krumo($form_state);
}

/**
*Implementing form submition: foodmenu
*/
function my_magic_foodmenu_form_submit($form, &$form_state){
   // krumo($form_state);
}

```

From the code above, I have implemented the `'choice'` field to be `'#required'`. The `_validate()` function responds and prints the implemented `krumo()` when I submit this form without making a choice, so there is nothing wrong with the `_validate()` code then. Why does it not respond when I just submit the form after making a choice??

## EDIT:

I would really like to know why the default `_validate()` and `_submit()` do not work in my code, given that there is nothing apparently wrong with the code. I am not looking for alternatives. I just want to get the defaults above to work. Thanks

# Answer
I finally figured it out. The `_validate()` actually works but it has to actually test a form field in order for it respond like I wanted.

I am working with a video tutorial made by lullabot in 2011 and the first test they did with `_validate()` was just as in the OP. Just a `krumo($form_state)` without testing any form field and `_validate()` responded perfectly. So I am guessing that the Form-API has changed some since 2011 so that you must perform a test on form field in order for `_validate()` to react. So I did:

```
function my_magic_foodmenu_form_validate($form, &$form_state){
    if($form_state['values']['choice'] == 'ricestew'){
        form_set_error('choice', 'Sorry, but we have run out of Rice with Stew');
    }
}

```

It worked as expected.
> 0 votes

# Answer
1 . You can add how many submit handler you want by using this

```
 $form['actions']['submit']['#submit'][] = 'mymodule_what_ever_function';

```

if you want to add a submit handler after default submit handler one callback the next callback to be called you can use this, This submit handler will be called after submit call back.

```
form['#submit'][1] = test_function;

```

To unset submit handler

submit handler

```
unset($form["actions"]['submit']);

```
2. ```
$form['#validate'][] = 'test_validation_function';

function test_validation_function($form, $form_state) {}

```

this function will call before submitting the result.

Add these handlers and once clear your Drupal cache

Still you face issue look in to this url for example will help you out

https://www.drupal.org/node/717740
> 2 votes

# Answer
The behaviour you're experiencing is expected and correct. If you look at the comments on `form_execute_handlers()`:

> Button-specific handlers are checked first. If none exist, the function falls back to form-level handlers.

You've provided a button-level handler in `$form['buttons']['submit']`, so `form_execute_handlers()` doesn't need to fall back, and the default form-level handlers won't be run.
> 2 votes

# Answer
You can always force the issue by setting the submit function explicitly

```
$form['#submit'][] = 'my_magic_foodmenu_form_submit';

```

This may be a silly question, but is the issue the fact that the krumo is commented out in your submit function?
> 0 votes

---
Tags: forms
---


# Question
Title: Creating a view to show nodes with multiple aliases generated by Path Module
I got a tough problem that I don’t even know how to start, any help would be appreciated.

I am on a D6 site. The Path Module is installed and there are articles that have more than one alias because the previous admin didn't overwrite the previous alias when saving the new ones.

I am doing a data migration and the migration is grabbing the old alias and not the new one.

What I need to do is find all NIDs that have more than one Path aliases, display them, delete the old one with bulk views

When I create a view to show field Path, it only displays the current one. Any thoughts how to display both aliases or any other way to tackle this.

Thanks for looking!

# Answer
> 0 votes
As this is a one-off requirement, there's not a lot of point creating a view for this purpose, as it would mean writing code to add extra entries for path in views tables.

You will be better off writing SQL. Here's a query that'll give you what you are after:

```
SELECT src, COUNT(*) AS alias_count FROM url_alias WHERE src LIKE 'node/%' GROUP BY src HAVING alias_count > 1

```

The result will be every source path like 'node/nnn' which has more than one alias.

---
Tags: 6, path-aliases
---


# Question
Title: How can I get the node ID inside my implementation of hook_tokens()?
I am trying to implement a custom token using the following code.

```
/**
 * Implements hook_token_info().
 */
function hook_token_info() {
  $type = array(
    'name' => `enter code here`t('xyz'),
    'description' => t('module.'),
    'needs-data' => 'xyz',
  );
  $tokens['full_html_form'] =array(
    'name' => t('Full HTML Form'),
    'description' => t('Returns full HTML Form based on the node'),
  );
  return array(
    'types' => array('abc' => $type),
    'tokens' => array('mno' => $tokens),
  );
}

/**
 * Implements hook_tokens().
 */
function hook_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if ($type == 'abc') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'full_html_form':
        $output = core_module_get_node($node->nid);
          $replacements[$original] = $output;
          break;
      }
    }
  }

  return $replacements;
}

```

I don't understand how to pass node ID to `core_module_get_node()`. How can I do it?

# Answer
> 1 votes
Since you are defining your own token type, you need to pass the node object to `token_replace()` in the `$data` array, for example as `$data['node']` or `$data['abc']->node`, as you are telling Drupal the token requires the 'abc' data.

Your `hook_token_info()` implementation is wrong, anyway. The correct one would be the following one.

```
function mymodule_token_info() {
  $type = array(
    'name' => t('xyz'),
    'description' => t('The tokens for the xyz data.'),
    'needs-data' => 'xyz',
  );
  $tokens['full_html_form'] =array(
    'name' => t('Full HTML Form'),
    'description' => t('Returns full HTML Form based on the node'),
  );

  return array(
    'types' => array('abc' => $type),
    'tokens' => array('abc' => $tokens),  /* << */
  );
}

```

From your code is not clear, but if the token is generated for a node, then you should implement code similar to the following one. (See `token_token_info()` as guideline.)

```
function mymodule_token_info() {
  $info['tokens']['node']['full_html_form'] = array(
    'name' => t('Full HTML Form'),
    'description' => t('Returns full HTML Form based on the node'),
  );

  return $info;
}

```

Modules can define new tokens for token types defined from other modules. The Token module is an example of such a module.

---
Tags: tokens
---


# Question
Title: EntityFieldQuery gives error on adding propertyCondition
I have to list down taxonomy term ids which should be greater than a specific tid. Below is the code I am using:-

```
$query = new EntityFieldQuery();

$tid = variable_get('last_player_update'); //last index of player update

$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition( 'tid',  'value', $tid, '>=')
  ->propertyCondition('vid', 3)
  ->propertyOrderBy('tid', 'ASC')
  ->range(0, 1000);

$result = $query->execute();

```

On executing the script I am getting the following error:-

```
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '9174 'value') AND (taxonomy_term_data.vid = '3') ORDER BY taxonomy_term_data.ti' at line 1: SELECT taxonomy_term_data.tid AS entity_id, :entity_type AS entity_type, NULL AS revision_id FROM {taxonomy_term_data} taxonomy_term_data WHERE (taxonomy_term_data.tid 9174 :db_condition_placeholder_0) AND (taxonomy_term_data.vid = :db_condition_placeholder_1) ORDER BY taxonomy_term_data.tid ASC LIMIT 1000 OFFSET 0; Array ( [:db_condition_placeholder_0] => value [:db_condition_placeholder_1] => 3 [:entity_type] => taxonomy_term ) in EntityFieldQuery->execute()

```

What I am missing in the above code snippet?

# Answer
> 0 votes
*Fields* have columns. Properties do not. You want:

```
$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition( 'tid',  $tid, '>=')
  ->propertyCondition('vid', 3)
  ->propertyOrderBy('tid', 'ASC')
  ->range(0, 1000);

```

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


# Question
Title: Access denied for admin user after new drupal 6 install
I just installed Drupal 6 (Don't ask why) from a fresh install (Version 6.29). I followed the install steps, created an admin user, set the correct time zone, etc.

But when I login and attempt to proceed to the admin panel, I get `Access denied
You are not authorized to access this page.` I have read about this issue many other places, and have attempted many solutions, but none seem to work for me.

I noticed that there is nothing in the `sessions` table of my MySQL database for this drupal install (but there is data in other tables). I think that this has something to do with it, but ti could be that there is info in the table, but it is immediately removed due to a session/cookie issue.

I have repeatedly removed all my browser cookies each time I have tried a solution. I have tried many solutions on drupal.org, many of which have been also referenced on other sites, but none have worked.

OS: `Mac OSX 10.9 (Mavericks)`

Web Server: `Apache/2.2.24 (Unix) PHP/5.4.17 mod_ssl/2.2.24 OpenSSL/0.9.8y DAV/2 Server at XX.XX.XXX.XXX Port 80`

Not using SSL for this drupal install.

# Answer
It may be that your cookie domain is not set correctly, this is a known cause of Access Denied errors when logging in, and it might be worth removing cookie domain info from settings.php and see if that works, and go from there.
> 1 votes

# Answer
Running Drupal 6 on PHP 5.4 is unreliable at best. PHP 5.2 is recommended, 5.3 could work, but you would probably run into issues with contributed modules.

That said, you could try what has been outlined here, basically:

1. Create a temporary session.
2. Clear all caches.
3. Updated php.ini with correct timezone info (and reload Apache settings).

Cheers,
> 0 votes

# Answer
It is probable an issue with a cookie.

If you are using chrome (1) go to : chrome://settings/cookies.

(2) paste the link of your website to the search bar.

(3) delete the session cookie.

(4) Try access your site again..
> 0 votes

---
Tags: 6, users, installation, sessions, cookies
---


# Question
Title: how to display sub menu under the respective main menu
I want to display main menu in custom menu block and display all sub menu below the main menu block on clicking the respective main menu. Iam able to display main menu but not able to display respective sub menus below the clicked main menu. Please help

I would like to give a reference if my reqiurement is not clear. The submenu created in the site http://stmarksumc.com/node/159 is what I am looking for.Can anyone please suggest me any solution to the issue Drupal 7?

Thanks for your help.

# Answer
> 1 votes
You have to use the module menu block. This module allows you to display child items of a certain parent item of a menu.

---
Tags: routes
---


# Question
Title: Is it possible to create a custom theme function?
I want for example to create a `mytheme_table` function to override `theme_table` etc. (in template.php) but I do not want to use it everywhere in my project.

I need to replace the table with a div or to remove some hardcoded wrappers.

```
$output .= theme('table_custom', array('header' => $header, 'rows' =>
$rows, 'attributes' => array('id' => $table_id, 'class' =>
array('field-multiple-table'))));

```

# Answer
you don't have to use hooks in your theme functions. you could create your own function called theme\_table\_custom() and use that in your template files.

if for some reason you must use the hook, you could include the original drupal code in the function and include a check for a table id or something, which would then fire your custom code.
> 0 votes

---
Tags: hooks, theming
---


# Question
Title: Search Api Autocomplete doesnt filter by language
We're using Search API Autocomplete with Search API 7.x-1.9 on a site set up with Solr (Websolr) serving nodes in both English and German.

I'm looking to be able to filter the results by ss\_search\_api\_language field which is presently not happening and as such i get autocomplete results for all both languages.

What would be the correct approach to deal with this?

# Answer
This issue has been fixed by fons vandamme via the drupal module issue tracker

```
function filter_by_language_search_api_query_alter(SearchApiQueryInterface $query) {
  //if query is of type search_api_autocomplete we will add our extra language filter
  if (strpos($query->getOption('search id'), 'search_api_autocomplete:') !== false) {
      dsm($query->getOption('search id'));

      global $language;

      $filter = $query->createFilter('AND');
      $filter->condition('language', $language->language, '==');
      $query->filter($filter);

  }
}

```

Make sure the language of your nodes are in the index.

https://www.drupal.org/node/2166113
> 0 votes

---
Tags: search, ajax
---