# Question
Title: remove 'publishing options' and other settings from node/add
I have a role which allows users to add nodes, viewing the admin form, but I don't want the user to be able to see Is there a way to remove it?

# Answer
Although the @jdu answer is correct and should suffice for most people, it's just two lines of code but might save some time for someone:

```
/**
* Implements hook_form_alter().
*/
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

  if (isset($form['#node']) && $form['#node']->type == 'article') {
    // hide article options
    $form['options']['#access'] = 0;
  }
}

```
> 1 votes

# Answer
hook\_form\_alter() or use CSS if you don't care if the values are overridden.
> 1 votes

---
Tags: users
---


# Question
Title: Programatically save comma-separated string as value of taxonomy field
I have a comma-separated string `$string` of the form "term1,term2,term3" and I would like to save it as the value of a taxonomy term field that is attached to my node. I have tried

```
$node->field_taxonomy[LANGUAGE_NONE][0]['value'] = $string;
node_save($node);
```
but this throws me an error "Warning: Illegal string offset 'tid' in taxonomy\_field\_presave()" coming from Taxonomy module.

What is the correct way to set the value of `$node->field_taxonomy`?

I also need that when `node_save($node);` is executed, taxonomy terms that had not been taxonomy terms before are created, just like it would happen when I set the value of `$node->field_taxonomy` via the user interface. I was expecting this to happen automatically when I set and save the taxonomy field value.

---

**Edit:** Actually, I am trying to attach taxonomy terms to *files*, but I thought that the analogous setup of nodes would be more familiar to most people.

I have attached a **description field** (`field_description`) and a **taxonomy field** (`field_hashtags`) to files via the user interface, using File Entity Module. I now want to upload files and fill in their attached fields using a custom file upload form, but on the custom file upload form there is only

* a field for the file itself (`$form['file']` of type `managed_file`) and
* a field for the description that the file should be given (`$form['description']` of type `textarea`).

My `CUSTOMMODDULE_form_submit()` function now defines `$submitted_file = file_load($form_state['values']['file']);`, i.e. as the submitted file, and `$submitted_description = $form_state['values']['description'];`, i.e. as the submitted description.

It then sets `$submitted_file->field_description[LANGUAGE_NONE][0]['value'] = $submitted_description;` and, as expected, when saving the file via `file_save($submitted_file);` the description field of the file is saved being populated with the submitted values.

However, before saving the file I run a custom function that returns a comma-separated string of hashtags (all words from the submitted description that start with '#') that were used in the description. I now want to set `$submitted_file->field_hashtags` as exactly those terms from the string that my custom function returns, just like I would enter a comma-separated string into a taxonomy field by hand from the user interface.

**Edit 2:** I further tried the following code from taxonomy.module

```
$terms = explode(',', $string);
$voc = taxonomy_vocabulary_machine_name_load('vocabulary_name');
$vid = $voc->vid;

foreach ($terms as $key => $term) {
  if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($term), 'vid' => $vid))) {
            $term = array_pop($possibilities);
        }
        else {
        $term = array(
          'tid' => 'autocreate',
          'vid' => $vid,
          'name' => $term,
          'vocabulary_machine_name' => 'vocabulary_name',
        );
        }

        $term_array = (array) $term;
        $node->field_taxonomy[LANGUAGE_NONE]['$key'] = $term_array;
    }
```

but this gives me "Error Error message PDOException: SQLSTATE\[HY000\]: General error: 1366 Incorrect integer value: '$key' for column 'delta' at row 1:"

# Answer
try that:

```
$terms = explode(',', $string);
foreach ($terms as $key => $term) {
  $node->field_taxonomy[LANGUAGE_NONE][$key]['value'] = $term;
}

```
> 1 votes

# Answer
This function worked for me:

```
/**
 * Return the term id for a given term name.
 */
function _get_tid_from_term_name($term_name) {
  $vocabulary = 'tags';
  $arr_terms = taxonomy_get_term_by_name($term_name, $vocabulary);
  if (!empty($arr_terms)) {
    $arr_terms = array_values($arr_terms);
    $tid = $arr_terms[0]->tid;
  }
  else {
    $vobj = taxonomy_vocabulary_machine_name_load($vocabulary);
    $term = new stdClass();
    $term->name = $term_name;
    $term->vid = $vobj->vid;
    taxonomy_term_save($term);
    $tid = $term->tid;
  }
  return $tid;
}

```

In your case it can be called like this:

```
$terms = explode(',', $string);
foreach ($terms as $term_name) {
  $tid = _get_tid_from_term_name($term_name);
  $node->field_taxonomy[LANGUAGE_NONE][] = array('tid' => $tid);
}

```

I just tested it for myself and it worked.

If you are using another vocabulary (different from **Tags**), then modify in the code above the line:

```
$vocabulary = 'tags';

```
> 0 votes

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


title: What data type is "Date" in Postgres?

text:
# Question
Title: What data type is "Date" in Postgres?
I don't have access to a client database, but need to know how a "Date" CCK field stores its information.
I'm using MySQL, and this easily found in the structure of the table. Anyone use Postgres and can check?

Is it a `timestamp` or a `date`?

# Answer
> 2 votes
Why do you need access to the database for this information?

Have you looked here? http://drupalcode.org/project/date.git/blob/b7502f3a86628e5c4995c01f20ac64d5cee5888b:/date.install

```
/**
 * @file
 * Install, update and uninstall functions for the Date module.
 */

/**
 * Implements hook_field_schema().
 */
function date_field_schema($field) {
  $db_columns = array();
  switch ($field['type']) {
    case 'datestamp':
      $db_columns['value'] = array(
        'type' => 'int',
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
    case 'datetime':
      $db_columns['value'] = array(
        'type' => 'datetime',
        'mysql_type' => 'datetime',
        'pgsql_type' => 'timestamp without time zone',
        'sqlite_type' => 'varchar',
        'sqlsrv_type' => 'smalldatetime',
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
    default:
      $db_columns['value'] = array(
        'type' => 'varchar',
        'length' => 20,
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
  }
  // ... more stuff

```

The answer to your question is that depending on the Drupal "Date" value you're storing it -- for `Postgres` it is 1 of the following values:

* (drupal field of) `datestamp` = `int` DBMS field
* (drupal field of)`datetime` = `timestamp without time zone` DBMS field
* (other drupal field of) date = `varchar` DBMS field analyzed by Date module on save and usage

**EDIT**

My answer is for Drupal 7. The same module API can be referenced for Drupal version 6 if needed. You didnt specify what version of Drupal you are using and "CCK" can be apart of both.

---
Tags: entities, datetime, database
---


# Question
Title: Looking for a hook called before any session is created
I am using Drupal 7 and am looking for a hook which is called before any session is created.

According to the the API page, `hook_boot()` is called after `DRUPAL_BOOTSTRAP_SESSION`. The link is for Drupal 6, I assume nothing changed in Drupal 7.

Is there a hook I can call which is called before any session is created?

# Answer
> 4 votes
If you wish to manage the session as mentioned in your comment, you can completely replace the default session handling by setting the variable session\_inc to the path of an include file that defines the functions expected by Drupal.

In your settings.php file:

```
$conf['session_inc'] = 'sites/all/modules/my_session_handler/session.inc';

```

And in session.inc you will need to implement the following functions:

You may want to start by copying Drupal's default session.inc and modifying it to suit your needs. Keep in mind that any of the functions in the default session.inc starting with an underscore are considered private, and not necessary to implement in your custom session.inc.

---
Tags: sessions
---


# Question
Title: Migrate Drupal 8 install from one server to another
I've been using Drupal since 4.6 and it's always been easy to copy a site from one server to the other. Make up a tarball, do a database dump, go to the new machine, unpack the tarball and load in the data and you're good to go.

I'm not finding this to be the case at all in D8. Every time I try to move between servers, I end up with fatal errors.

I find that I have to end up doing an install from scratch and then loading the database into the new install. That works, but then my /sites/default/files/config\_\[hash\] are different, so the sites are out of sync.

What am I missing? In theory, the Configuration Initiative was supposed to make this easier, but so far for me that has not been the case.

BTW \- instructions on "rebuild" - https://drupal.org/documentation/rebuild \- managing config: https://drupal.org/documentation/administer/config

# Answer
I recommend using Drush as version `8.x-6.x` is compatible with Drupal 8. You can then use `drush archive-dump` and `drush archive-restore` to move a `.tar.gz` file of your database and site files around as-needed.
> 3 votes

# Answer
So I didn't want to just do the drush archive-dump because how I wanted to move this with git push/pull.

I found that I needed to exempt the /sites/default/files/config\_\[hash\] file in my .gitignore

I had previously copied it over, but for whatever reason, it didn't work.

I'm not sure whether I'm just doing something wrong, but if it's true that you need the config\_\[hash\], then it seems like the default .gitignore that ships with D8 is going to cause problems.

I could not get negation to work

sites/\*/files

!sites/*/files/config\_*

So I ended up instead ignoring dir by dir (not ideal). So instead of sites/\*/files

I have

sites/\*/files/php

sites/\*/files/css

sites/\*/files/js

sites/\*/files/styles
> 2 votes

---
Tags: 8
---


# Question
Title: Add element inside main menu block, but outside navigation
I need to add an element *somewhere* within, or directly before/after, the main menu block. For example, the generated HTML should be something like this:

```
<div id="main-navigation">
  <div class="block block-system" id="block-system-main-menu">
    <div class="block-inner clearfix">
      <div class="content clearfix">
        <ul class="menu">
          <li class="first expanded">
            <a href="">About</a>
            <ul class="menu">
              <li class="first leaf">
                <a href="">General Info</a>
              </li>
              <li class="leaf"><a href="">Video</a></li>
                <!-- ... other menu items -->
            </ul>
          </li>
        </ul> <!-- this ends the top level main ul.menu -->
        <!-- a div added here would be ok -->
      </div>
    </div>
  </div>
</div>
<!-- or a div added here would be ok -->

```

I am currently trying `hook_block_view_alter()` and have tried multiple variations of something like this:

```
function theme_block_view_alter(&$data, $block) {
  if ($block->delta == 'main-menu'
    && $block->region == 'menu') {
    $data['content'][] = array(
      '#markup' => '<div class="."><a href="#top">Close Mobile Menu</a></div>'
    );
  }
}

```

which is the closest I have come. This adds the div within `ul.menu` (top level) after the last `li` element; that won't work.

I can't seem to find a theming function for the menu as a whole, just `theme_menu_links()`. I see the theme wrapper `menu_tree__main_menu` within `$data` in `hook_block_view_alter()`, but I don't see a file or function that resembles that.

I'm aware that there may be a much better solution that I'm just not thinking of, so I'll state the final goal:

1. Absolute positioned menu. (I can work with `#main-navigation` being absolute and the element coming after it **or** with `ul.menu` being positioned, and the element coming after it.)
2. A link that follows the menu in markup, but is outside of the absolute positioned menu, so that I can position relative to window, not the `ul`.

Thanks!

# Answer
To accomplish all your goals, you need to implement these three functions:

Create one template file for the block with your menu.

### template.php

```
/**
 * Implements hook__preprocess_block().
 */
function YOURTHEME_preprocess_block(&$variables, $hook) {
  // allow to use block templates depend on delta
  // example: delta = main-menu ; template file: block--main-menu.tpl.php
 if ($variables['block']->delta == 'main-menu') {
    $variables['theme_hook_suggestions'][] = 'block__' . str_replace('-', '_', $variables['block']->delta);
 }
}

/**
 * Main menu
 * Implements theme__menu_tree().
 */
function YOURTHEME_menu_tree__main_menu($variables) {
    global $level;
    $div = ($level == 1) ? '<div> ... some div next to the main ul ... </div>' : '';
    $ul = '<ul class="menu">' . $variables['tree'] . '</ul>' . $div;
    return $ul;
}

/**
 * Main menu
 * Implements theme__menu_link().
 */
function YOURTHEME_menu_link__main_menu($variables) {

  $element = $variables['element'];
  $title = $element['#title'];
  $sub_menu = '';

  // global menu level variable.
  // within theme_menu_tree() at first level has always value = 1
  // but not here, that's why $depth will have to be defined separately
  global $level;
  $level = $element['#original_link']['depth'];

  // if you will need $depth, it must be defined separately
  // $depth = $element['#original_link']['depth'];

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

  // link output
  $output = l($title, $element['#href'], $element['#localized_options']);

  // if link class is active, make li class as active too
  if(strpos($output,"active")>0){
    $element['#attributes']['class'][] = "active";
  }

  $attr = drupal_attributes($element['#attributes']);
  return  '<li' . $attr . '>' . $output .$sub_menu . "</li>\n";
}

```

### block--main-menu.tpl.php

```
<?php
/**
 * @file
 * theme's implementation to display a block with the main menu.
 */
?>
<div id="main-navigation">
  <div class="block block-system" id="block-system-main-menu">
    <div class="block-inner clearfix">
      <div class="content clearfix">
        <?php print $content; ?>
      </div>
    </div>
  </div>
</div>

<!-- or a div added here would be ok -->
<div> ... some div next to the main navigation div ... </div>

```

### Results
> 2 votes

# Answer
What about page.tpl.php? It will allow you the add the extra markup before / after the menu. I think that theme\_preprocess\_page may also do the job.
> 1 votes

---
Tags: 7, theming, routes, blocks
---


# Question
Title: How do I show Device Geolocation share location prompt only on specific pages?
I am working with the Device Geolocation module packed with Smart IP. I got all the functionality working great, but I would prefer if the prompt to share your location wasn't given on every page of the website. The location service is only needed on two pages of the site, so I was wondering if there's any way to only load the Device Geolocation service on those pages, or somehow limit it to only ask to share location on one page and remember that (independent of browser settings).

# Answer
In the smart ip setting pages there is a setting to limit asking on specific pages.

Ask user's geolocation on specific Drupal native pages

Specify pages by using their paths (not the aliased path). Enter one path per line. The '*' character is a wildcard. Example paths are blog for the blog page and blog/* for every personal blog. is the front page. Leave blank if all pages.
> 1 votes

---
Tags: location
---


title: How to get the nid of current node

text:
# Question
Title: How to get the nid of current node
I need a function to return the `nid` of the current `node` that the current `user` is watching. Can you help me?

# Answer
If you are insisting on a **function** then you are looking for `arg` function.

`arg(0)` will return `'node'` and `arg(1)` will return `node nid`.

Provided you must be inside a node.

\[**Updated Answer**\]

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $nid = arg(1);
  if ($nid) {
    $node = node_load($nid);
    /** do something **/
  }
}

```

**Alternately**

you can get `nid` from node object `$node->nid`
> 8 votes

# Answer
You can access `$node` object. `$node->nid` will return you NID of the node.

There is a hook to help you further to achieve something when user is viewing node - hook\_node\_view().

There are three parameter of the hook - `$node` (will return node object), `$view_mode` (view mode of the node like full or teaser) & `$langcode` (language code for rendering).

You can use this hook in your module & write your logic like -

```
function MYMODULE_node_view($node, $view_mode, $langcode){//replace your module name with MYMODULE here
  if($node->type == 'article' && $view_mode == 'full'){ //if content type is article & user is on full node view
    //do domething
  }
}

```
> 2 votes

---
Tags: nodes
---


title: Adding block below Header Logo

text:
# Question
Title: Adding block below Header Logo
I am placing a couple of static elements into the header, the issue is that the elements are being placed below the menu instead of below the header logo. Is this possible to put the block below the header logo image? I had to hack the css with a negative left margin and absolute top for now but it does not behave properly when elements are declared above it. (e.g. if admin logs in, or is not logged in, will affect the position vertically, etc)

# Answer
> 0 votes
If you are trying to place some block below the site logo, there should be a region below it. CSS come later.

If your block is going below menu, that means the region where you are placing are rendered below menu in the `page.tpl.php`

You have two choice here - either render the same region just after site logo or create another region in there.

Open your page.tpl.php & try to find -

```
<?php if ($logo): ?>
  /*more text*/
<?php endif; ?>

```

Render your region just after it (assuming your region name is header) --

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

```

You can add DIV class or ID according to your need around it or do it in `if-else`, like -

```
<?php if ($page['header']): ?>
  <div class="header" >
    <?php print render($page['header']); ?>
  </div>
<?php endif; ?>

```

You can add your own region in **theme.info** file if you don't want to use the same where you were trying to place your static content.

---
Tags: blocks, theming
---


title: Show access denied page to the user

text:
# Question
Title: Show access denied page to the user
I need a function that checks a condition; for example, if `$a == $b` it should return the access denied page to the current user.

What function should I use?

# Answer
> 0 votes
I think you are looking for the function which returns the access denied page; that is drupal\_access\_denied(). Just call this function inside your conditional statement.

---
Tags: 7
---


# Question
Title: Saving Theme returns TImeout error in Drupal 6.16 after changing server
Everything was working fine till I was on my old server. After migrating it to a new server with same configuration (better memory and added load balancer), when I try saving the theme from the theme page http://mysite.com/admin/build/themes, after waiting for some time I get a 504 Gateway Timeout error from nginx.

Hope I get some response here and the experts can help me resolve this question.

**EDIT**

I just noticed if I perform any postback operation that is related to Drupal core modules, the issue is present. I am able to add/edit/delete data and do postbacks on admin pages that are created via a custom module, but the page just does nto work when on Core Druapl admin pages -

1. Save Theme
2. Clear Cache
3. Add Node

# Answer
The issue at my end was related to server configuration. Nginx server was timing out and the load balancer was not redirecting the urls properly.
> 0 votes

# Answer
Have you made sure that you've allowed enough time for script execution on your new server? Changing this to a higher value might help:

```
ini_set('max_execution_time', YOURVALUE);

```

Changing theme settings and installing / uninstalling modules needs a longer execution than most other operations I would imagine.

Sorry if my suggestion was already obvious to you.
> 0 votes

---
Tags: 6, migrations
---


# Question
Title: Trying to migrate Date values using migrate module.
I'm trying to migrate some data from a csv to a field\_collection in a user profile. Everythings works fine but not for a field of Date (with range) type.

I'm on Drupal 7.22 and I'm using Migration and Migration Extra modules

I do not receive any error message, but the data is not entered, please help me

My code in the migration class:

```
[...]
$source_file = drupal_get_path('module', 'module_name') . '/data/user_employments_info.csv';

$columns = array(
  [...]
  array('employment_period_start', 'employment_period_start'),
  array('employment_period_end', 'employment_period_end'),
  [...]
);

$this->destination = new MigrateDestinationFieldCollection(
  'field_usr_bkg_emplo',
  array('host_entity_type' => 'user')
);

[...]

$this->addFieldMapping('host_entity_id', 'user')->sourceMigration('User');

[...]

$this->addFieldMapping('field_usr_bkg_emplo_time', 'employment_period_start');
$this->addFieldMapping('field_usr_bkg_emplo_time:to', 'employment_period_end');

```

# Answer
> 1 votes
At the base there was a problem: the module dates was patched. The final code that have worked:

my.info

```
dependencies[] = migrate
dependencies[] = migrate_extras
dependencies[] = date
dependencies[] = date_migrate

```

my.make

```
projects[migrate][subdir] = "contrib"
projects[migrate][version] = "2.6-rc1"
projects[migrate_extras][subdir] = "contrib"
projects[migrate_extras][version] = "2.5"
projects[date][subdir] = "contrib"
projects[date][version] = "2.6"
projects[date][patch][] = "https://drupal.org/files/date-consolidated_migrate-1.patch"

```

my\_migration.inc

```
$this->addFieldMapping('field_date', 'date_from');
$this->addFieldMapping('field_date:to', 'date_to');
$this->addFieldMapping('field_date:timezone', 'UTC');

```

---
Tags: 7, datetime, migrations
---


# Question
Title: How to add field collection date field in scheduling component drupal 7?
I am using drupal 7 , I have used date field in field collection , I want to send email before one week of field collection date , I have made one Rule component which sends email to author , when I made a new rule of after adding new field collection item and make an action to schedule my component , in there I never got the option in date selector to set field collection date value

please help me out Thanks

# Answer
Im working on a similar scenario and I'm also stuck with the same issue. Try adding Entity has field and Data comparison conditions. Check this link: http://www.drupalcommerce.org/faq/rules-field-data-selection
> 0 votes

---
Tags: entities, rules
---


# Question
Title: Exporting a view from one site to another
I'm a Drupal beginner with a problem.

I'm gonna do some updates on a live site which requires some new views to be created, and with that some new content types and blocks. I'm working off my local dev site doing these changes there first and then I'd like to be able to export these views as a package with the content types and blocks that they handle. Is this possible?

Of course I could just export my local database and import it on the live site, but the problem is that the live site is very active so the database is always changing. And my updates will take at least a week to do, so I can't keep up.

Any suggestions?

# Answer
> 5 votes
By Default views have option to `import` and `export`. By using that we can do it.

In drupal7 views3.x has option of import link in this url `admin/structure/views`

With this image you will get clear view of how to import and export a view.

# Answer
> 3 votes
In addition to the views module I also recommend you to use the Features module that allows you to export your content types and lot more to code and then just commit the new code and revert it to DB on production.

# Answer
> 1 votes
Surely, Import/Export of Views will do the job (for exporting views only), but I would invest time in Configuration Management module. It has ALL the possible options, not only for views, but also for nodes, content types. I don't recommend using Features module, since I experienced a lot of bugs and unexpected behaviour with it. In case you want to copy content types (quick-dirty solution), I recommend the module BundleCopy Regards.

---
Tags: views, importing-exporting
---


# Question
Title: Create views from combination of various vocabularies' terms
I am trying to find out if there is a module that can work out this magic or if I need to make a custom solution.

The problem: I have Vocabulary1, Vocabulary2, Vocabulary3. The ideal would be to have something like tagadelic for all 3 vocabularies on the side, so whenever a tag is clicked the content displayed is additionally filtered by that extra tag.

# Answer
> 1 votes
You can have nice block displaying all terms coming from your mentioned vocab by help of Cumulus.

Though its in DEV mode but it works fine. This requires module Tagadelic to be enabled first.

You can create a cumulus block by visiting `admin/structure/block/add-cumulus-block`, where you can mention name of the block & setting for it such as `Vocabulary IDs to be included`, `Number of tags to display`, `Width`, `Height` etc..

---
Tags: views, search, nodes
---


# Question
Title: Drupal 6 - theme the standard nodequeue admin view
I have a site where a client needs a 'visual' way of re-ordering their content. Is there a way to basically add more cck content to the nodequeue admin interface? so that it is not just showing a list of titles but instead maybe some cck content that the user can drag around?

I am thinking that I need to hack the module, which is fine, but wanted to know if there was some sort of recommended approach to this.

Thanks!

# Answer
> 0 votes
You can use views to prepare you listing according to your need. You can add as many CCK fields in column & expose filters too to use it further.

You can add your prepared views block at the dashboard which your admin can use.

---
Tags: nodes
---


title: Views filter by contextual filter

text:
# Question
Title: Views filter by contextual filter
I have an interesting question regarding Views, Taxonomy and Contextual Filters AND Views-\>Filters

I have a content type Basic Page with additional field -\> *industry category* (term reference, taxonomy).

There are multiple Basic Pages on the website but only 5 with industry category field filled in.

I have second content type Industry Page (Page Title, Body with additional field -\> \*industry categor\*y (term reference, taxonomy), pointing towards the same vocabulary.

I have a view should display nodes of type industry page depending on the page you are in (The “*basic page*” with the additional *field-\> industry category*.)

I need to do something with contextual filter to display all nodes of type “industry page” **where** the basic page-\>field industry category = “industry page”-\>industry category.

Can you help me with it, since I am a bit stuck.

Regards

Oleg

# Answer
I think you are looking for creating a block of similar node by term with one more filter "another content type". There is a module to do this exactly but it doesn't have the content type filter in it. I will still recommend you to have a look at it - Similarterms.

You can achieving the same with view. Please look into the answer given at these links, it has been explained in details --

https://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3

Recommend nodes based on current node field value in view block
> 0 votes

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


# Question
Title: How to display only content assigned to a user?
I have created a content type with a CCK field named 'executor' of 'User reference' type. So the admin can select a different user as an executor in creating content.

I want to create a page using views to display all tasks a user is assigned to as executor. But I don't know what I should put in fields and filters.

# Answer
Create views by filtering the content type which you want to list in there.

Then add a argument in the view, which will be the field you are using to reference the user in your content type.

Supply UID of currently logged in user as default arguments & your content will be filtered for logged in user.

User will see all the fields values added by you on the page, fields are totally dependent upon your selection which you can add in views.
> 1 votes

---
Tags: views, 6, entities
---


# Question
Title: What is difference between #value and #markup?
I had gone through drupal link which contains something as shown below
https://drupal.org/node/224333

Use '#markup' not '#value' for markup

(Issue) The new default type for items in forms or other structured array data (e.g. node content) passed to drupal\_render() is '#type' =\> 'markup'. In Drupal 6 and earlier, the HTML content was added to the array using the #value attribute. In Drupal 7, this needs to be changed to #markup. This change also applies to those form elements of '#type' =\> 'item'. This change reduces the confusion between form values and markup and allows the code in drupal\_render() to be simplified.

Example 1, from system.admin.inc In Drupal 6:

```
<?php
  $screenshot = $screenshot ? theme('image', $screenshot, t('Screenshot for %theme theme', array('%theme' => $theme->info['name'])), '', array('class' => 'screenshot'), FALSE) : t('no screenshot');

  $form[$theme->name]['screenshot'] = array('#value' => $screenshot);
?>

```

In Drupal 7:

```
<?php
  $screenshot = $screenshot ? theme('image', array('path' => $screenshot, 'alt' => t('Screenshot for %theme theme', array('%theme' => $theme->info['name'])), 'attributes' => array('class' => 'screenshot'))) : t('no screenshot');

  $form[$theme->name]['screenshot'] = array('#markup' => $screenshot);
?>

```

---

I have a code in drupal 6 which is as shown below :

```
$form['in_title'] = array(
  '#type' => 'button',
  '#value' => t('ort'),
  '#executes_submit_callback' => false,
  '#attributes' => array('class' => 'hide-submit-exclude'),
);

```

I want to convert this code to D7 .
So When and where should I use #markup and #value ?
I just want to know the difference between #markup and #value

# Answer
`#markup` is

> Used to set HTML that will be output on the form.

`#value` is

> Used to set values that cannot be edited by the user. Should NOT be confused with #default\_value, which is for form inputs where users can override the default value.

For `#value` this might include submit buttons, hidden elements, etc. - basically anything that needs a value for the form submission, but where that value should not come from the user.

The only change you need to make in your sample code is to allow for the fact that classes in the attributes array must now be in an array themselves:

```
$form['in_title'] = array(
  '#type' => 'button',
  '#value' => t('ort'),
  '#executes_submit_callback' => false,
  '#attributes' => array('class' => array('hide-submit-exclude')),
);

```
> 2 votes

---
Tags: 7, forms
---


# Question
Title: Is it possible to POST values to next page with a Drupal URL?
I have the following link that works if I link to an external page outside Drupal. However, when I place the same code in a Drupal page that is on orangeEDIT, and change this URL to point to the Drupal location, it says the page cannot be found.

```
<a href="http://host/drupal1/?q=node/17?orange_id=<?= $row['orange_id']; ?>">Edit</a>

```

I should probably use the Form API for this, as it is a link that allows a form to be edited, but it seems a way too complicated, compared to the PHP solution.

# Answer
The problem is that you have two ? characters and you are not actually printing the php variable. It should be like this:

```
<a href="http://host/drupal1/?q=node/17&orange_id=<?php print $row['orange_id']; ?>">Edit</a>

```

Notice that because you have multiple query parameters (q & orange\_id), that are to be separated by an ampersand (&). Also, use the print function to print $row\['orange\_id'\];

**Edit**

If you enable clean urls you could do this:

```
<a href="http://host/drupal1/node/17?orange_id=<?php print $row['orange_id']; ?>">Edit</a>

```
> 0 votes

# Answer
To prepare links in Drupal, use the `l()` function:

```
$options = array('query' => array('orange_id' => $row['orange_id']));
$link = l('Edit', 'node/17', $options);

```

You can also add `'absolute' => TRUE` to your options array to get the full URL; full options are on the docs page.

Using `l()` you can ensure that your URL is valid at all times.
> 3 votes

---
Tags: uri
---


title: Drupal 7: Theme hook for form not found

text:
# Question
Title: Drupal 7: Theme hook for form not found
Drupal doesn't call the theme function for my form in my module (error log: Theme hook wc\_challenge\_actions not found.). I found similar posts on stack exchange, but none of the solutions works for me.

Form declaration

```
    function wc_challenge_actions($form, &$form_state, weACT_Challenge $challenge) {
      $form['action_groups']['#tree'] = TRUE;
      $form['action_groups']['#type'] = 'fieldset';
      $form['action_groups']['#title'] = t('Action groups');
      $form['action_groups']['#theme'] = 'wc_challenge_actions';

      // rest of form definition, works correctly

      return $form;
    }

```

Theme function

```
    function theme_wc_challenge_actions($variables) {
      drupal_set_message('The theme worked!');

      // rest
    }

```

Drupal never calls this function... Any ideas?

# Answer
You have not defined your theme function in `hook_theme`

```
 function yourmodule_theme() {
   return array(
     'wc_challenge_actions' => array (
       'render element' => 'element',
     ),
   );
 }

```
> 5 votes

---
Tags: 7, forms, hooks
---


title: Date problem after restore

text:
# Question
Title: Date problem after restore
I had to restore a drupal 7 site from scheduled backup using backup & migrate. Since then I seem to have problem with date/timestamp.
I have a view (3.6) filtering on node created date with options between "today" and "tomorrow".
All users are in GMT+7 timezone.
It is now 18:01pm here and the sql query generated has:
node.created BETWEEN 1375959700-25200 AND 1375959700+61200

So "today" is current time instead of today at 00:00:00

Any suggestion ?

# Answer
In Drupal 7 They are not using the datetime field. instead of that you can use the int field and add your date in unixtime stamp format.

You can expose the data using hook\_views\_data hook. Check following URL for more help:

https://api.drupal.org/api/views/views.api.php/function/hook\_views\_data/7
> 0 votes

---
Tags: backups
---


# Question
Title: Get Fields of a custom Content Type from Database in Drupal 7
I'm trying to get custom `fields` of my custom `content-type` "slideshow". I've chosen to get the *fields* from template (`.tpl.php`) file for some reasons *(mainly because I've to write lots of formatting HTMLs and modifying lots of template files did not sound good)*.

So far, What I've got is individual `nodes`:

```
$result = db_query_range('SELECT n.nid
                      FROM {node} n WHERE n.type = :ntype', 0, 10, array(':ntype' => 'slideshow'));
foreach ($result as $record) {
    $node = node_load($record->nid);
    // Got $node! What to do now????
}

```

The code works & I've got nodes in `$node`. Now What to do to get individual **custom fields** & work with the raw data of these fields? Please help.

PS I've tried Get content type with PHP from database but the code does not work... guess it's for older Drupal versions.

# Answer
You could always try field\_get\_items if you know the names of the fields you want. `field_get_items('node', $node, 'field_name');`

Although node\_load() *should* be providing the fields for you and can be found at `$node->field_name`

Also Attiks advice is sound, I would also not recommend doing this in tpl
> 2 votes

# Answer
First a bit of advise, take it or leave it: but don't do this in the tpl.php files, try to use some preprocessing hooks.

To see what fields are available on your $node, add a print\_r($node) after the node\_load, it will show you everything that's defined on the $node.

If you want total control over your display without writing lots of template files have a look at Display suite and custom\_formatters
> 1 votes

# Answer
Attiks is right! first use print\_r($node), or var\_dump($node). if you view the source of the page where the info is printed it will probably display in a readable form.

Use the following format or similar (depending on what you need) to get your data:

```
$node->field_my_cck_field['und'][0]['value']

```
> 1 votes

# Answer
To get a list of fields for a node content type in Drupal 7, try the field\_info\_instances function. Here is an example usage that will retrieve all the fields for a custom node content type:

```
$my_fields = field_info_instances("node", "my_custom_content_type");

```
> 1 votes

# Answer
Use this function to get an array of content type with its fields

```
 function get_content_fields_array() {

$list = node_type_get_names(); //get the list of content types
$contenttypes = array();
$type_count =0;
foreach ($list as $key => $value) {
    $field_list = field_info_instances('node', $key); //get field list for content type
    $field_count =0;
    $field_max = count($field_list);
    foreach ($field_list as $field_key => $field_value) {
        if($field_count == 0) {
            $contenttypes [$type_count]['label'] = $value;
            $contenttypes [$type_count]['machine_name'] = $key;
        }
        $contenttypes [$type_count]['fields'][$file_field_count]['machine_name'] = $field_key;
        $contenttypes [$type_count]['fields'][$file_field_count]['field'] =  $field_value;

        if($field_count == ($field_max -1)) {
                $type_count ++;
        }
        $field_count++;
    }
}

 return $contenttypes;
}

```
> 0 votes

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


title: Translating modules

text:
# Question
Title: Translating modules
How do I translate drupal modules, or download existing translations? I downloaded the translation from https://localize.drupal.org/ but not everything is translated.

# Answer
There are many ways to translate. At the first you should enable the Content translation and Locale modules.

* You can download your translates from Drupal localize and you can search for your modules translates.
* You can download and install the Localization update module. This module automatically installs the module translations when you install a new module.
* You can install the Localization client module, which helps you to translate and save your own translates in your site.
* You can translate the strings of your site manually in admin/config/regional/translate/translate.
> 4 votes

# Answer
try to look at this url it's very useful for u http://www.lullabot.com/blog/article/localized-and-multi-lingual-content-drupal-7
> 3 votes

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


# Question
Title: Views table aggregation with counts per value of a field
A person can log multiple cases: Case 1, Case 2, Case 3

a case can have multiple states: New, Active, Resolved

Using a views table I want to generate a view where each person has one row, and I can see how many new, Active and Resolved cases each has:

```
Person   | States
Person 1 | New(1), Active(3), Resolved (13)
Person 2 | New(5), Active(3), Resolved (1)

```

Or something like this:

```
Person   | New | Active | Resolved
Person 1 | 1   | 3      | 13
Person 2 | 5   | 3      | 1

```

With normal aggregation all I can achieve is:

```
Person   | Cases
Person 1 | 17
Person 2 | 9

```

Surely I am missing something?

# Answer
> 5 votes
Views\_merge\_rows module will save your day! Assuming that the States field is a list field.

1) In your **aggregation enabled views with table display** add a User:Name (Group results together), a States field (COUNT, Excluded from display) and again a States field (Group results together, Rewrite Results \> Rewrite the output of this field: `[field_states] ([field_states_1])`).

So you will get a list of users with states but with one row per node. Here is a screenshot:

2) Then, enable the **views\_merge\_rows** module. In you **Merge rows** settings do this:

So you get what you want!

# Answer
> 1 votes
You can achieve this by using the Views Field View module. More specifically

1. Install and enable the above module.
2. Create three (3) different views (of users) one for each state (for example new\_state\_view, active\_state\_view & resolved\_state\_view).
3. At each view firstly remove any default Sort Criteria (and don't add anything in that section). Then use aggregation to count the states for every user. Don't forget to use a "user:uid" contextual filter in every view and to filter them appropriately for each state. Each view will provide you the number of states for every user.
4. Create another user view, add "user:uid" as field and exclude from display. Then add a field of "user name" and finally add three (3) consecutive global view fields. Note: it is very important to keep the "user:uid" field before the global view fields.
5. In the settings of each global view field choose the corresponding \_state\_view and display of that view (master display is fine). Last but not least use the \[!uid\] token (from replacement patterns: \[!uid\] == User: Uid (raw)) in the "Contextual Filters field" of those settings.

After the above you will have a view displaying a table of user names and next to them the counts of each state. You can theme the global view fields (inside views) accoridingly to present them the way you like.

# Answer
> 0 votes
You could add three custom PHP fields to your view using https://drupal.org/project/views\_php, one for each case. Within each field's code you would then load the number of corresponding cases.

---
Tags: 7, views
---


# Question
Title: What is the proper permission settings to create a moderated, private organic group (in commons 3)?
I'm trying to create a private group in Drupal Commons. It is my assumption that one follows open, public groups.

However, I've marked a few groups as private using the default roles and permissions. I anticipated seeing a *Register* option for that group.

I guess I'm trying to create a moderated group where the user is approved by the group owner. How does this happen?

I'm also seeing that Commons Groups may be interfering with the group permissions by graying out the *Member subscribe only* with the approval option (drupal ticket link).

In the group field settings, I have the following fields attached to groups and content types.

>

>

The group settings for one example group I wish to make private are the following.

>

However, while masquerading as authenticated user, I still see the *Follow* button. I would expect to see a *Register for this group* option.

# Answer
> 1 votes
I understand your confusion. In Drupal Commons, follow is not the same as registering as a group member.

If you check off the non-member checkbox on the Subscribe to group line then non-members can apply to register for that group. AS you have your other settings then an administrator can approve this registration.

Becoming a member of a group allows you to post. However, in the default configuration, posts in even private groups are visible unless additional permissions are applied and users may still follow the group.

---
Tags: organic-groups, 7
---


# Question
Title: Can I simulate a hook using Devel's PHP execution?
Let's say, for instance, that I want to quickly view the variables sent to `HOOK_preprocess_node()`, but I'm too lazy (if I'm just being honest) to edit my template.php file just to do that one check.

Can devel's Execute PHP block allow me to do something like this?

```
function SOMETHING_preprocess_node(&$vars) {
  dpm($vars);
}

```

Or is it impossible to use hooks in this context?

To clarify, my somewhat lofty goal is to be able to experiment with virtually *any* hook function quickly using Devel's PHP execution, and if there's a syntax for doing that. I realize there are some problems with that concept from the get-go, not the least of which is that you need to artificially create a context in which certain hooks will even be called, but I want to see what's available.

**EDIT:** Tenken's answer got me thinking. I could create a global array called, say, `$devel_hooks`. In a module, I could populate this variable with the contents of various hooks like so:

```
$devel_hooks = array();

function devhooks_preprocess_page(&vars) {
  global $devel_hooks;
  $devel_hooks['preprocess_page'] = $vars;
}

```

The contents of `$devel_hooks` could then conceivably be accessed at will, BUT there's a problem: Devel's Execute PHP block evaluates its content immediately on form submit and *before* the page loads again, so I couldn't put, say, `dpm($devel_hooks['preprocess_page']);` in there and get anything out of it because the page and its hooks haven't been processed yet, so $devel\_hooks is completely empty or may even be undefined when that PHP is evaluated.

So maybe I could populate another global array with the information I want to request from `$devel_hooks`, and have the latest possible page hook (which might be `HOOK_page_alter()`?) parse that array and run a `dpm()` on the requested components of `$devel_hooks`. You would then, obviously, need to execute the PHP on a page that would use the desired hooks, but that's on you. I just haven't quite figured out how to connect those dots.

I could, conceivably, populate the array with strings and map those to array keys, but what if I want to dpm() something deeply nested in one of the hook arrays, like `$devel_hooks['preprocess_node]['elements']['body']['#markup']` (just as an example, may not be accurate to what that array would look like)?

# Answer
The main problem with simulating *any* hook is that the hook only makes sense in the context of whatever is doing the invoking.

Hooks get fired either from a `module_invoke()` or a `module_invoke_all()`. These functions assume that the hooks have already been found and exist in the registry. They also take into account the invocation order (by weight, then alphabetically by module name).

The process and preprocess hooks are little different as the hook parameters get passed in by reference, and there is a more complex calling scheme, so the order really does matter for what is present in `$variables`.

The net result is that you can't really fake out a hook without actually implementing the hook somewhere.

Personally, I keep a devel module around with the most common hooks stubbed out as empty functions. I also stub out common process/preproess and form alters. This way I can `dpm()` something whenever I want without needing to do a cache clear. For example, I have a high-weigh module with

```
/**
  * Implements hook_form_alter().
  */

function mytestmodule_form_alter(&$form, &$form_state, $form_id) {
  // dpm($form_id, 'form_id');
  // dpm($form, 'form');
  // dpm($form_state, 'form_state');
}

```

in it. This way, Drupal already knows about the hook in the registry. All I need to do is uncomment / edit the function as needed.
> 4 votes

# Answer
You can use either the devel tab on the content, or devel\_themer to see all of this.
> 1 votes

---
Tags: hooks, debugging
---


# Question
Title: How to import csv file for "field collection" using feed-importers
In Drupal7, In node processor settings -\> we can't map field collection values. However they are multiple values, Is there any way of possibilites to import data through CSV file. I tried using field collection feeds module, In Processor Settings -\> I selected "Field collection processor", then alert error is dispalying as shown "Missing Feeds plugin FeedsFieldCollectionProcessor". Is there any other way to solve this issue?

# Answer
> 4 votes
I recently had the same issue. Follow along with what I did:

1. Do NOT install the field collection feeds module.
2. Go here: https://drupal.org/node/1063434 and apply the patch in comment #16. (See https://drupal.org/patch/apply for details. Or you can just apply it manually, by copy & pasting the patch directly into /drupal/sites/all/modules/field\_collection/field\_collection.module).

EDIT: You may find more luck with one of the other listed patches on that page. #16 worked for me, so that is the one I suggested.
3. If the field collection fields have more than one instance, use the drupal module 'feeds tamper' to 'explode' the field collection mapping.
4. Clear your site's cache
5. Set new mappings to your field collection values (they should show up now as mapping targets).
6. Import your nodes, field collections and all!

# Answer
> 3 votes
This is a known issue and appears to be related to caching. The suggested fix is to clear your caches at /admin/config/development/performance.

---
Tags: feeds, entities
---


# Question
Title: How can I change the <title> on a View filtered by NID so that it is the referenced Node's Title field?
I have a view which only displays a single result and I am using NID as the contextual filter. I cannot change that, it needs to be NID.

I want my page `<title>` to be the "Title field" of the node that was filtered rather than its NID.

As it is, in my contextual filter I can "Override title" by typing in "%1" which results in the terrible `<title>1234 | My Site</title>`. Assuming node/1234 is titled "John Doe", I want my title to be `<title>John Doe | My Site</title>`.

How can I accomplish this?

# Answer
> 2 votes
You need to "Specify validation criteria" in your contextual filter.

In your Contextual filter scroll down and check the box "Override title" but leave the text box empty.

Next, check the box "Specify validation criteria" and select "PHP Code" from the validator menu.

In the code box enter the following:

```
if($argument) { // Check that argument is present
    $myNode = node_load($argument); // Load node based on NID
    $myTitle = $myNode ->title; // Parse node data to get title
    $handler->options['title'] = $myTitle; // Change the view's page title to node's title
}
return true;

```

---
Tags: 7, views
---


# Question
Title: Is it possible to bypass form validation, but still save form data?
I have an ECK (Entity Construction Kit) form with several required fields. The form contains a series of submit buttons.

The 'complete' button does a regular form submit, triggering the appropriate validation & submit handlers.

The 'save & close' button needs to submit the form & save the data without doing any validation, and this is what I'm having trouble with. I know I can use the `#limit_validation_errors` property on the 'save & close' button to remove validation, but that also removes the submitted data from `$form_state['values']` in the submit handlers.

I tried rebuilding that data in a custom submit handler, re-inserting it into `$form_state['values']`, and then triggering ECK's original submit handler (which, in theory, should save the data), but that doesn't work:

```
function my_custom_form_submit($form, &$form_state) {
  if (isset($form_state['values']['no_validation_submit'])) {
    // make copies of the form variables, since they get passed by reference & modified in form_builder();
    $form_copy = $form;
    $form_state_copy = $form_state;

    // rebuild the data to get correct ['values'] in $form_state_copy;
    $form_copy = form_builder($form['#id'], $form_copy, $form_state_copy);

    // place the rebuilt ['values'] into original $form_state & call ECK's submit handler
    $form_state['values'] = $form_state_copy['values'];
    eck__entity__form_submit($form, $form_state);
  }
}

```

Any ideas for how to achieve this?

# Answer
> 0 votes
The solution dawned on me this morning; to get this functionality in place I need to work backwards: rather than having Drupal validate the required fields and conditionally disabling the validation, we should remove the validation requirements from the form, and conditionally add them (doing custom validation, if need be).

So, the `#required` parameter is set to `FALSE` for all fields, and a custom validation handler conditionally checks the 'required functionality.'

---
Tags: 7, forms
---


# Question
Title: How can I automatically restore my site from a backup using the command line for testing purposes?
I am on Mac OS X using MAMP PRO as my local development environment. I want to quickly reset my site to a known state in order to run some tests I have prepared in Selenium.

I have the Backup and Migrate module installed which makes it easy to restore from the command line via drush, but if I restore using Backup and Migrate it appears to only overwrite the existing data and leaves other data in place, which I don't want-- I want to erase all of this other data as well so that I can be sure that the database is in exactly the same state as the backup file.

Currently, I log in to PHPmyadmin, drop all of the tables in the database, and then re-import from the backup. This seems somewhat inefficient to me; is there a way to automate this from the command line?

# Answer
> 1 votes
I use `/applications/mamp/library/bin/mysqldump -uUSERNAME -pPASSWORD DATABASE >backup.sql` to back my database up and then `/applications/mamp/library/bin/mysql -uUSERNAME -pPASSWORD DATABASE <backup.sql` to restore it.

# Answer
> 1 votes
You can also use the Demo module. It's not command line but through the Drupal admin UI. It lets you create 'snapshots' of your database and lets you reset your database to those snapshots.

# Answer
> 0 votes
If you're looking to script this process, I would recommend using drush.

If space is a concern than pipe the results to gzip as well. drush sql-dump | gzip \> ../backup/FILENAME.sql.gz

Remember it's a good idea to clear out your database prior to running your restore.

drush sql-drop - This drops the tables on your existing database. drush sqlc \< path/to/FILENAME.sql - This imports the file into your database.

With a compressed backup:

gunzip \< ../backup/FILENAME.sql.gz | drush sqlc

---
Tags: 7, backups, testing
---


title: Custom module not indexing in search

text:
# Question
Title: Custom module not indexing in search
I'm using drupal search module to search/find/filter content in my **CUSTOM MODULE** and it's not returning any results when I search for a word listed in content of my custom module content type. It return results only when i search for a users and others content type.

Any body knows what can i do to fix this? Do I have to implement any hook to index the content of my custom module?

**PS:**

1) My **custom module** it's based in the **drupal core blog** module

2) I was using **Custom Search** module, but i've disabled it

3) I've tried the search api module and views exposed filter (Search Terms) and nothing

Thank you

# Answer
This is a shot in the dark, but I would do the following. This assumes you are on Drupal 7.

On, admin/structure/types/manage/page/display, open **Custom Settings** and select **Search Index**. Save. Then click on the **Search Index** tab and configure the view mode for all of the fields that you want to search in.

On admin/config/search/settings, make sure that you have **Node** selected.

On admin/config/search/custom\_search/content, double check that you have selected the content types that you want to search (or leave that fieldset empty). Also check that you aren't excluding any types that you actually want to search.

If your site isn't that big, I would dump the search index and rebuild id. I normally do this from drush:

```
drush search-reindex
drush search-index

```

Then, open your MySQL tool of choice, and look for a few keywords that you know you should have hits on:

```
SELECT
    *
FROM
    search_index
WHERE
    word = 'foo'

```

If all of that works, then you shouldbe getting search results. If not, you need to find what is interfering with the indexing, which could be specific to your system.
> 3 votes

---
Tags: search
---


# Question
Title: drupal on postgresql vs mysql vs mariadb
Anybody using PostgreSQL with Drupal? I know MySQL is preferred for Drupal but I have an existing PostgreSQL instance running on the server. I might as well use it rather than use more resources by running MySQL (MariaDB) unless there are major drawbacks in using PostgreSQL.

So, how does running Drupal on MySQL compare to Drupal on PostgreSQL?

Also, are there differences between running Drupal on Oracle's MySQL vs MariaDB?

# Answer
The occasional issue you can hit, is that a contrib module is either just badly written because the author didn't know better, or, more rare, deliberately used mysql specific functionality for some reason, meaning that the module simply won't work on your site.

I've only had this on a single occasion though, and it caused issues during installation. A quick hack of the modules install file, and everything worked out well from there on.

It's unlikely to be much of an issue, and I'm myself running some personal things on postgresql just get familiar with it.

Drupal doesn't care if you use mysql or mariadb. They're the same thing to Drupal.
> 2 votes

---
Tags: database
---


title: Drupal 7 -Resize image from URL

text:
# Question
Title: Drupal 7 -Resize image from URL
At present I am working on a demo site. I am pulling in sample images from from lorempixel for place holders. That is working great. In my content type I have an image field and it includes the url to the image like this: http://lorempixel.com/output/people-q-g-605-186-6.jpg

I will be creating views soon and I want to adjust the image size using image styles. How can I apply the image style to the text field that holding the url? Is this possible, if so, how? if not, is there another way to accomplish this?

I don't want to create various image size, just adjust them as they are being referenced.

Thank you in advance.

# Answer
> 0 votes
For this one - I am going to adjust the size via css in each of the views. Would still like to know if the above is possible, but this will resolve my current issues

# Answer
> 0 votes
You can use image\_style\_url function to create a url to your image with your custom image style.

---
Tags: media
---


title: Ubercart shipments are not entities

text:
# Question
Title: Ubercart shipments are not entities
So I am interested in logging signed, scanned copies of my Ubercart packing slips. Cool right? The problem is that Ubercart shipments are not fieldable entities. Thus I cannot add a file field or even a checkbox to say that I received a signed packing slip.

My plan was to make an entity called 'Signed Packing Slip' with the file field and use entity reference to link it to at least uc\_order (because, again I can't link up with Ubercart Shipments because they are not entities).

Can anyone think of a hack or workaround to make this work? Is there any way to incorporate custom PHP code or database calls through ECK/EntityReference

# Answer
> 0 votes
Migrate to commerce. ;)

I think you'll have to do this the old manual way.

1. Create your own entity with an image field to store the data.
2. Hook\_form\_alter the relevant form to insert your own widget.
3. Handle form submission, and push the data to it's relevant entity, then hand over form submission to the original handler.

---
Tags: 7, ubercart, entities
---


title: Fillable Fields in a View

text:
# Question
Title: Fillable Fields in a View
I want to submit several items with Views Bulk Operations - is there a module or method to add fillable fields to a view?

# Answer
I think you need editablefield module. once this module is enable you can set any fields editable in your view. So when you visit your view page or block you can edit the field value there itself.. Nice Ajax is implemented in here, so it works very nice.. You can set it like double click to edit..

NOTE - I am not able to link the module with original URL at drupal.org so you can search for it in google with same name.
> -1 votes

---
Tags: views
---


# Question
Title: Drupal 7 Calendar - How do you disable the number link to the day page?
How would you disable the links to the daily page on a calendar page view?

# Answer
That functionality is automatic and means that you have month- and day-type calendar views defined.

If you don't want to use the daily display on your site, just find the calendar view that defines the daily display and disable that display or view.

That'll automatically disable the functionality of displaying a daily calendar on your monthly view.

Here's a step-by-step: Look in the calendar view's format settings

If the calendar type is 'Day', then that's the one that's automatically being linked to your month's date number, just disable that view or display:

Hope this helps!
> 2 votes

---
Tags: 7, navigation, datetime
---


title: LDAP module and AD global catalog

text:
# Question
Title: LDAP module and AD global catalog
Does anybody successfully authenticate against AD global catalog? I've got the following configuration:

```
LDAP server:
ldaps://service.mydomain.com
LDAP port:
3269
Binding Method:
Service Account Bind
Base DNs for LDAP users:
DC=service,DC=mydomain,DC=com
DC=otherdomain,DC=mydomain,DC=com
AuthName attribute:
userPrincipalName

```

The module successfully authenticates users, which are members of parent domain called "service", but LDAP search can't find any user from "otherdomain", which is connected to parent domain inside AD domain forest. I´m able to test LDAP search using ldp.exe and using this tool I can find any user from any domain.

Also, there is the following error message in the Drupal watchdog:

> ldap\_search() function error. LDAP Error: Referral, ldap\_search() parameters: ldap\_search() call: base\_dn: DC=otherdomain,DC=mydomain,DC=com, filter = (userPrincipalName=somebody@otherdomain.mydomain.com), attributes: , attrsonly = 0, sizelimit = 0, timelimit = 0, deref = , scope = 3

Any help will be greatly appreciated.

# Answer
> 0 votes
I know it's been over half a year so you may have already found the answer to this, but I thought I would weigh in as it is a process that I am working on myself.

For the **Base DN**, consider simply using `DC=mydomain,DC=com`. I have not had to do this yet, so it was just a thought from their suggestion of using a higher Base DN.

I had problems authenticating until I made sure of these items:

* **AuthName attribute** and **AccountName attribute** set to: `sAMAccountName`,
* **PUID** set to: `objectGuid`
* then check the box with the question "Does PUID hold a binary value?

After that, authentication went perfectly. Good luck!

---
Tags: authentication-authorization
---


title: Nested Relationships

text:
# Question
Title: Nested Relationships
I have three content types: A, B and C. C references B (one to many) and B references A (one to many). Each content type has a *Title* field; A also has a *Type* field.

I want to output the titles of all the nodes from a C node, where *Type* in an A node is equal to *XY*. I don't seem to be able to set up relationships in view for B -\> A.

Can anyone point me in the right direction?

# Answer
your question is not clear.I don't understand what you want. But I think it can help you. Node relationship
> 0 votes

---
Tags: views
---


# Question
Title: How to calculate the average ratings for the post when the user submits 3 field ratings?
I need to implement ratings in my site. I have user five star rating and voting API module, I created a content\_type with "beach", and created some field in the manage field settings, name, id, etc. And also I configured the five star module with tags like location ratings, beachratings, facilites ratings and overall (average ratings) ratings. I display all the rating stars in the page by using the code.

```
$bid=explode("/",$_GET['q']);
$node = node_load($bid['1']);// we get the node id here//
$fivestar = field_view_field('node', $node, 'field_overall_ratings');
echo render($fivestar);
$beachrating=field_view_field('node', $node, 'field_beaches_ratings');
echo render($beachrating);
$locationrating=field_view_field('node', $node, 'field_location_ratings');
echo render($locationrating);
$easyrating=field_view_field('node', $node, 'field_easy_to_get');
echo render($easyrating);

```

When I submit the ratings, they are stored in the database but the average is not updating. But I need to calculate the overall ratings when the user votes for the three section. Can anyone help me how can we implement this in my site?

# Answer
Use `fivestar_get_votes` to get individual widgets **average** and get **average** of them to have **average** rating of the entire node.
> 0 votes

---
Tags: nodes, entities, rating
---


# Question
Title: How to get the nid of nodes created by user (on the event of logout)?
I have a content type 'XYZ' for which the user has created nodes. Is there any way I can use to get the node ID of all the nodes created or deleted by user at the time of logout?

I am using `hook_user_logout()`, but I am not able to get the node IDs for the node created by the user.

# Answer
> 2 votes
`hook_user_logout()` is probably called only when the user uses user/logout to log out. If users don't log out all the times after they used the site, that hook is probably not going to be invoked. (For example, I have never logged out from Drupal.org, and I log in back once my session expires for the browser I am using.)
Furthermore, once a node is deleted, there is no track of it in the database, and since `hook_user_logout()` is going to be eventually invoked when it is too late, it is not going to find any information about the nodes deleted by the user.

I would rather use hook\_node\_insert() and hook\_node\_delete() to collect the data that will be used from another hook. For example, the following code would work.

```
function mymodule_node_insert($node) {
  $_SESSION['created'][$node->nid] = TRUE;
}

function mymodule_node_delete($node) {
  $_SESSION['deleted'][$node->nid] = TRUE;
}

```

If that is helpful information, instead of `TRUE` you can use `REQUEST_TIME`; in that way, you would log when the user created or deleted a node.

Eventually, you can use a database table instead of a session variable, but in that case you should clean it after the user logged out, if you want to reset the information you collected once the user logs out. With the code I shown, you would lose the information when the session expires for the user, so it is probably preferable for you to store the information in the database.

The method suggested by the other users doesn't work when the user creates a node and deletes it. Counting the number of nodes associated with a user ID doesn't include the nodes that have been deleted before the user logged out. Also, since users with the permission of administering nodes can associate a node with a user different from the user who created it, counting the nodes associated with a user ID is going to give wrong information.

# Answer
> 1 votes
Like Nikhil M said, you can use EntityFieldQuery.

But I think it would be more efficient to use db\_select in this case since no fields are manipulated.

It will look like something like this

```
function hook_user_logout($account) {
  $nids = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('n.uid', $account->uid)
    ->execute()
    ->fetchCol();

  if (isset($nids)) {
    //$user_nodes = entity_load('node', $nids);
 }
}

```

# Answer
> 0 votes
You could try EntityFieldQuery

```
function hook_user_logout($account) {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'XYZ', '=')
      ->propertyCondition('uid', $account->uid);
    $result = $query->execute();

    if (isset($result['node'])) {
        $news_items_nids = array_keys($result['node']);
        //$news_items = entity_load('node', $news_items_nids);
        // Do Whatever....
     }

}

```

Give it a try and let me know the results.

---
Tags: 7, nodes
---


# Question
Title: How to pass parameters to same form after form submission?
I have created a module that creates and displays a table and with a filter element. What I would like to do is when the user enter a string into the filter can submits it, I then use that string to filter the results of the table. What I am having an issue with is how to pass that string back into the form creation function to filter the results.

This is what I have in the submit function:

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

  $filter = array();
  if (isset($form_state['values']['filter_user'])) {
    $filter['username'] = $form_state['values']['filter_user'];
  }
  return $filter;
}

```

Which is not right obviously. How do I get the $filter variable to be passed back into the submission\_list\_form function that creates the page? This is being done with Drupal 7.

Thanks.

# Answer
> 5 votes
You can use the following code, to achieve what you want.

```
function submission_list_form_submit($form, &$form_state) {
  $filter = array();

  if (isset($form_state['values']['filter_user'])) {
    $form_state['filter']['username'] = $form_state['values']['filter_user'];
  }

  $form_state['rebuild'] = TRUE;
}

```

The form building function should then check if `$form_state['filter']` is set.

```
function submission_list_form($form, &$form_state) {
  if (isset($form_state['filter'])) {
    // …
  }

  // …

  return $form;
}

```

If the code doesn't work, use another array index instead of `$form_state['filter']`; it is probable that in such case the array index conflicts with the one used by Drupal or a third-party module. I would rather prefix the array index with the short module name, to be sure to avoid conflicts with other modules or future Drupal versions.

### References

# Answer
> 0 votes
In `submission_list_form_submit()`, instead of returning `$filter`, you can set this value on the `$_GET` variable, and then get this value back when you're in your form building function.

# Answer
> -1 votes
I'm not sure but I think you should use `variable_get` and set to pass it. Hope that helps.

---
Tags: 7, forms
---


# Question
Title: How can i create two register forms for different users?
How can i have two register forms and show register form for two sets of users.

One register form for one set of users and another register form for another set of users?

one can be default drupal form that is user/register. But i want url to be varied.

# Answer
> 4 votes
Use the Profile2 Registration Path module. It can help you in creating as many registering forms as you need. I have used this one.

> This module enables administrators to set unique registration paths per Profile2 profile type.
>
> ## Overview
>
> ### The Problem
>
> By default, the Profile 2 module permits you to add fields from chosen profile types to the default user registration form. Unfortunately, there is only one user registration form. Thus, every user will be presented with these fields during registration. If you have two profile types targeted at two different audiences, you cannot have two separate registration forms.

Profile 2 use this module to get different set of fields. While editing the profile you have created, you can check this one.

# Answer
> 3 votes
Check out the Profile2 Registration Path and the Profile 2 modules.

**Profile2 Registration Path**

> This module enables administrators to set unique registration paths per Profile2 profile type.

**Profile 2**

> * The module is aimed to provide a simple, but extensible solution providing a similar end user interface like the core profile module
> by default.
> * Multiple profile types may be created via the UI (e.g. a general profile + a customer profile), whereas the module provides separated
> permissions for those.
> * Optionally, profile forms are shown during user account registration.

Here is a quick tutorial you can also follow to set it up.

> * Download Profile2 and profile registration path
> * Enable the modules
> * Create the 'consumer' and 'service provider' roles
> * Go to admin/structure/profiles and add a new profile type named 'consumer'
> * Check 'Enable unique registration path'
> * Enter a URL path to use for this profile type, e.g., 'consumer/register'
> * Select the role(s) that you would like to apply to users registering from this path. In this case, 'consumer'
> * Add a few fields to the profile type
> * Create additional profile types as needed
> * Configure your permissions so that the correct roles can edit the correct profile types. E.g., only users with role 'consumer' can edit profiles of type 'consumer'

---
Tags: 7, users
---


# Question
Title: restrict user from certain role to change their email
Is there any way I can restrict users from certain role to change their email address. Once they are registered I need them no to be able to change it in the edit settings page. I found how to restrict to change the username but not the email.

I am using Drupal 7. Thanks in advanced :)

# Answer
> 8 votes
Another way is programmically in your custom module

```
function mymodule_form_alter(&$form,$form_state,$form_id) {
   global $user;
    if ($form_id == "user_profile_form") {
       if(in_array('your role',$user->roles) && isset($form['account'])) {
           $form['account']['mail']['#disabled']=TRUE;
          }
      }
 }

```

# Answer
> 6 votes
Use the User protect module:

> This module allows fine-grained access control of user administrators, by providing various editing protection for users. The protections can be specific to a user, or applied to all users in a role.

# Answer
> 3 votes
zhilevan – thanks for the nice code to get me started in solving this problem quickly. I have a site where there is a generic user role "client" login so that clients can upload and download files. The user account will be shared between potentially many clients for a "one off" upload or download and we don't want them to alter the user name, password or any other stuff for this generic account. I'm sure there are more elegant ways to do this but here's my code for "shutting the edit option down" based on user role. (I tried the user protect module, but couldn't get it to work). Here's my code in case anyone else finds it useful.

```
function mymodule_form_alter(&$form,$form_state,$form_id) {
   global $user;
    if ($form_id == "user_profile_form") {
       if(in_array('Client',$user->roles) && isset($form['account'])) {

           $form['account']['name']['#disabled']=TRUE;
           $form['account']['current_pass']['#disabled']=TRUE;
           $form['account']['current_pass']['#description']='';
           $form['account']['mail']['#disabled']=TRUE;

           unset($form['picture']);
           unset($form['overlay_control']);
          }
      }
 }

```

---
Tags: 7, users, emails
---


# Question
Title: Problem creating nodes from XML using Feeds/ Feed XPath Parser
I'm trying to create nodes from an XML feed using Feeds XPath Parser.

Some of the data appears to import, but not all fields are being populated or populated correctly.

Here's a snippet of the feed:

```
<merchantProductFeed>
<script/>
<SCRIPT/>
<merchant id="2607" name="Business IT Online Office Shop">
<prod id="49194411">
<pId>571895</pId>
<text>
<name>
Avery afterBURNER Label System Software with Applicator 10 Inserts Ref AB1800 [24 Labels]
</name>
<desc>
Avery afterBURNER Label System Software with Applicator 10 Inserts Ref AB1800 [24 Labels].- Includes software, applicator, 24 labels and 10 inserts.- For Professional CD labels and inserts.- No Touch labels - unique design of the label sheets mean you can apply the label to the CD/DVD without touching the printed design or the adhesive.- 20 premium matt and 4 photo quality glossy labels.- The curved design of the applicator means the label is rolled smoothly onto the CD/DVD.- Inserts include a CD jewel case insert cover and tray (including spine) - allowing design and print in one effort.- The software contains over 2000 clip art images, 120 pre-formatted label designs and much more.
</desc>
</text>
<uri>
<awTrack>
http://www.awin1.com/pclick.php?p=49194411&a=953&m=2607
</awTrack>
<awImage>
http://images.productserve.com/preview/2607/49194411.jpg
</awImage>
<mLink>
http://www.businessitonline.com/avery-afterburner-label-system-software-with-applicator-10-inserts-ref-ab1800-24-labels.bprod?inctax=true
</mLink>
<mImage>
http://www.businessitonline.com/eCommImages/571895.jpg
</mImage>
</uri>
<price curr="GBP">
<buynow>15.56</buynow>
<delivery>5.95</delivery>
</price>
<cat>
<awCatId>68</awCatId>
<awCat>Software</awCat>
<mCat>Machines and supplies>Computer Software</mCat>
</cat>
<brand/>
</prod>

```

There are several more products in the document, structured in the same way.

In the feed importer, I've set the context as `//merchantProductFeed/merchant/prod`.

I have two fields to populate: 'title' (text) and 'cost' (decimal).

The XPath query I'm using for title is 'text/name' and the query for cost is 'price/buynow'.

When creating the nodes, the title field is populated with the correct data, but includes the and element tags.

The cost field doesn't get populated.

I can't see where my XPath query is going wrong, so I'm unsure if it's a problem with that or something that isn't happening properly elsewhere in the XPath Parser module. So far as I can see, the mappings are set up as they should be.

Can anybody see if my XPath queries are correct for the XML feed above?

# Answer
> 1 votes
Have you tried turning on debugging in the Xpath Parser? It can give you an idea of what is going into the field before any interference like the formatting of the field itself.

I also use Firepath which is an add-on for Firefox for use with Firebug. I don't use Xpath very often- kind of a quick means to an end- and the two of these tools have been invaluable. Firepath will help you find out if your Xpath is correct.

---
Tags: 7, feeds
---


title: Fail to enable booking time slot in D7

text:
# Question
Title: Fail to enable booking time slot in D7
I am newbie to Drupal. I am trying to install booking timeslot module in D7. I've installed 7.x-1.x-dev version. However, I fail to enable the module.

The description for the booking time slots as below:

> Provides features for Booking Time Slots
> Requires: Booking Timeslots (disabled), Addressfield (missing), Calendar (enabled), Views (enabled), Chaos tools (enabled), Date API (enabled), Date Views (enabled), Date (enabled), Entity (missing), Entityreference (missing), Features (missing), Hierarchical\_select (missing), Hs\_taxonomy (missing), Hs\_taxonomy\_views (missing), List (enabled), Field (enabled), Field SQL storage (enabled), Options (enabled), Number (enabled), Opening\_hours (missing), Taxonomy (enabled), Text (enabled), Workflow (missing)

Can anyone help to tell me what to do so that I can enable it?

# Answer
> 2 votes
The modules that in that list are followed by "(missing)" are the modules that are not present in the Drupal installation, and that are required from the module you are trying to install. Just install them, and you will be able to install the Booking Time Slots module.

The trick is understanding which modules you need. Since the modules are not found on the server, what the module page shows is not the module name, but the short name of the module capitalized.

The list of the modules that site needs is the following:

As you see, the module pages says that the Opening\_hours module is missing, but the module name is *Opening hours*, while opening\_hours is the short name of the module, the same used in the URL for the project page. Join https://drupal.org/project with opening\_hours, and you get the complete URL of the project page for the module you are looking for: https://drupal.org/project/opening\_hours.

The list of modules is shorter because there are modules that are sub-modules of modules already listed as requirements.

The *Opening hours* module then depends from the following modules:

# Answer
> 1 votes
Simply download and install all the missing modules listed. So for example, download features(missing), entityreference(missing) and anything looking like that

---
Tags: 7
---


# Question
Title: How do I filter a view within a view based on an Enity Reference field when NID is not in the URL of the container view's page?
I have 2 content types: Artist & Artwork

Artwork contains an *Entity reference* field pointing to a single Artist called "Artist"

I have 2 views:

1. **Artist Detail** \- A page view showing a single artist using title (artist's name) as contextual filter so url is human readable. eg. myexhibit/pablo-picasso
2. **All artwork by an artist** \- A block view listing art by a specific artist using the "Artist" Entity reference field as contextual filter

I want to embed view #2 into the header of view #1 so that art tied to that artist appears on the Artist Detail page view.

I can get it to work if I change my filter on #1 to filter by Node ID and then pass that Contextual Filter to the embedded view. But I don't really want my URL to be myexhibit/213.

Is there a way to pass the node ID of the node matching the argument "pablo-picasso" to the embedded view? Or a way to get the embedded view's contextual filter to work using a node *title* rather than the *NID* referenced in the Entity Reference field?

# Answer
You can use *myexhibit/NID* url for this view page and then set up an alias (for example *myexhibit/TITLE*). If you want to make this page only for certain artists you can filter them by node ID.
> 1 votes

# Answer
The embedded view doesn't work with node title argument because it's a title of parent node (*Artist*). To get it working you should add relation to the *Artist* node type and specify it in argument settings.
> 0 votes

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


# Question
Title: How do I add tags to the taxonomy data via node and the fields?
I need to store the tags which newly created in the taxonomy\_term\_data table, and also in the node field. I created the node field as field\_beaches\_tags (term reference) using "Select list" as widget.

I need to store the value in this and also in the taxonomy term data table with reference vid as the tags. I have the location name field in the form; when I submit the form the location, I must store the tags in the taxonomy table and also in the node field.

```
 function My_beaches_create_submit($form, &$form_state) {
    $node = new stdClass();
    $node->language = LANGUAGE_NONE;
    $node->promote = 0;
    $node->uid = 1;
    $node->type = 'content_type';
    $node->taxonomy[1] = $values['location_name'];
}

```

1 is the vid of the tags in the taxonomy, but I am able to store the value in the database table.

# Answer
In drupal 7, Taxonomy terms are attached as regular fields. So `$node->taxonomy` is no longer a standard property that Taxonomy module picks up.

If your field name is `field_beaches_tags`, assign tags to the node as below.

```
$node->field_beaches_tags[$node->language][]['tid'] = 23;

```

Note that the `23` above is the term ID of the taxonomy term. If you have an array of terms, you can assign all of them like below:

```
$terms = array(23, 45, 678, 1212);
foreach ($terms as $tid) {
  $node->field_beaches_tags[$node->language][]['tid'] = $tid;
}

```

Keys in the `$node->field_beaches_tags[$node->language]` array will be used as delta values of the field.

### Create a new taxonomy term

```
$term = new stdClass();
$term->name = ‘My New Term Name’;
$term->vid = 'vocabulary_id';
taxonomy_term_save($term);

```

Now, `$term->tid` will be populated with the new term ID that you can use. See taxonomy\_term\_save() for the API doc.

taxonomy\_get\_term\_by\_name() can be used to load terms by a given name.

```
$term = taxonomy_get_term_by_name('my existing term name', 'beach_terms');
// $term->tid will now be in place.

```

Your overall code can be like the following.

```
$terms_given = array('Miami', 'Colombo', 'Pizza');
$node = new stdClass();
$node->language = LANGUAGE_NONE;
$node->promote = 0;
$node->uid = 1;
$node->type = 'content_type';

foreach ($terms_given as $term_name) {
  $terms_matched = taxonomy_get_term_by_name($term_name, 'beach_terms'); // "beach_terms" is the machine name of vid 1.
  if ($terms_matched) {
    //We blindly use the first match. Not very elegant.
    $first_term = current($terms_matched);
    $node->field_beaches_tags[$node->language][] = (array) $first_term;
  }
  else {
    $term = new stdClass();
    $term->name = term_name;
    $term->vid = 1; // Vid from the question.
    taxonomy_term_save($term);
    $node->field_beaches_tags[$node->language][] = (array) $term;
  }
}

```
> 5 votes

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


title: Drupal Perfomance

text:
# Question
Title: Drupal Perfomance
I am creating a website with Drupal, where users will upload various content. I want to scale Drupal at the rate the site is growing on. I will have more than 45,000 nodes and over 1,000,000 comments on the site.

This is a multi-site installation. I was wondering if I should use the Pathauto module to alias node paths and tags paths or use the following code for taxonomy.

```
function site_function_term_path($term) {
  $t = taxonomy_get_term($term->tid);
  $term->name = $t->name;
  return 'tags/' . urlencode($term->name);
}

```

Which is better way to implement this?

# Answer
> 1 votes
Since you still need to generate path aliases for nodes, I would rather use the Pathauto module. The code you show has the following *problems*:

* It doesn't work for Drupal 7, since hook\_term\_path() is not used from Drupal 7
* It works only when the module handling the vocabulary is not the Taxonomy module, since the hook is invoked from the following function.

```
function taxonomy_term_path($term) {
  $vocabulary = taxonomy_vocabulary_load($term->vid);
  if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
    return $path;
  }
  return 'taxonomy/term/' . $term->tid;
}

```
* There should not be the need of calling `taxonomy_get_term()` since the taxonomy term object is already passed to the hook.

A Drupal 7 solution would be implementing hook\_url\_inbound\_alter() and hook\_url\_outbound\_alter(), for which the equivalent in Drupal 6 are two functions to add to the settings.php file: custom\_url\_rewrite\_inbound() and custom\_url\_rewrite\_outbound().

As for when that hooks/functions should be used instead of using path aliases with the Pathauto module, you can look at What is the difference between implementing hook\_url\_inbound\_alter() and hook\_url\_outbound\_alter(), and using a path alias?

> Using `hook_url_outbound_alter()` has some potential performance issues because it is executed by every single URL on a page via the url() function. This means a module could implement `hook_url_outbound_alter()` with some complex and slow code that is called 100's of times per page.
>
> Also hook\_url\_outbound\_alter() allows a link's `$options`, including its query string, to be altered, which is impossible to do to path aliases and a very useful feature. For example, I have altered internal RSS URLs to point to their respective Feedburner and iTunes URLs.
>
> Conceptually, the Path module should be calling the `hook_url_*_alter()` hooks but it is probably slightly faster to have the `drupal_get_path_alias()` calls directly in `url()`.

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


# Question
Title: Can taxonomy terms contain special characters e.g. ampersands, apostrophes and dashes?
What characters are legal in taxonomy terms in Drupal 7? I haven't been able to find a list of illegal characters. Does this mean all characters are legal? I am particularly interested in knowing if ampersands, apostrophes and dashes are safe to use. Thanks

# Answer
They are safe to use, however you may have issues with your url paths. so in your url if you have a term Theology & Scripture", it becomes this: 'theology%20%2526%20scripture. This kind of urls are not good for search engine optimisation.

You can however use the pathauto module, to correct this issue.

> The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.
> 2 votes

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


# Question
Title: How to call a SOAP function to send Drupal user data to a SOAP server?
I'm trying to send user data to a remote SOAP server with the Rules module. I have installed the `wsclient_soap` module (a sub-module of the Web service client module) and put in the URL for the WSDL file. It seems to work as I get a few of the data types back on the Drupal end.

What I do not see, is a way to use the SOAP "operation" to send the values of a Drupal user back to the SOAP server.

Has anyone had any luck sending this type of data to a *remote* SOAP server?

Here is the code for my php evaluation I'm using to test:

```
$client = new SoapClient('http://something.wsdl', array('trace' => 1));
syslog(1, print_r($client->__getFunctions(), TRUE)); //this shows the correct function
$newuser = array(
     'email' => 'test@test.com',
     'phone' => '+33 06 12 34 56 78',
);
$client->__soapCall("availableFunctionFromGetFunctions", $newuser);
syslog(1, print_r($client->__getLastRequest(), TRUE));
syslog(1, print_r($client->__getLastResponse(), TRUE));

```

For the available functions, when printed to syslog, it shows the one I want with THREE variables, the two I want to send and one called "authentication". The documentation I was given does not say what the value of authentication is supposed to be, so I have a feeling the "error" that is being thrown when I act out the rule is caused by this.

I will update as I get more information.

# Answer
You say you use the wsclient SOAP binding but your code doesn't use it. Instead, your code uses a direct query to the PHP SOAP interface.

This thread discusses the difference between the two binding and which one is preferrable.

From the module's readme file:

* You can create web service descriptions in code, see for example wsclient\_examples.module
* You can easily invoke web services by loading the description and executing an operation (the operation name can be used a dynamic method name):

```
$service = wsclient_service_load('google');
$result = $service->translate('Hallo Welt', 'de|en');

```
> 0 votes

---
Tags: rules, services
---


# Question
Title: Trying to rewrite url for a custom module with an extra custom variable using PathAuto
I needed to create a custom module to show product information. It's a custom module because the data comes from a remote database. This module has a block which I add to a basic page. (It was my first drupal website from some time ago, and I know it's not the conventional method.)

Now in this module I do a $\_get call from a product id in the url. For example if the page is /product?id=50, it will get the product of id 50 and show that information in the block. Now at request of the client the url needs to look like /product/50 for SEO reasons. Also true for categories for example categories/boots instead of categories/category=boots

I tried using http access file but I can't get it to work. Also see: Drupal does rewrite url but can't load css/themes

Now they suggested to use Pathauto module. So I've installed the module. But it won't create those url's taking the custom variables into account. Is there a way so I make Pathauto take into account those extra variables needed for my $\_get? Or is there a better method?

I've never used this module before, so noob proof advise is appreciated.

# Answer
To solve my problem I've written a custom module with the hooks url inbound and outbound

(https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_url\_inbound\_alter/7)

This worked for me. I still don't know why the .htaccess approach didn't work tough.
> 0 votes

# Answer
You have a 2-step problem.

1) User friendly URLs

Pathauto is the wrong solution. Setting URLs in custom modules is the job of `hook_menu`.

```
function mymodule_menu() {
  $items['product'] = array(
    'page callback' => 'mymodule_product_view',
  );
  return $items;
}

function mymodule_product_view($id = 0) {
  //Do database call here for product id = $id
}

```

Using this simple example, you can visit the page `product/50`. Drupal will then call the `mymodule_product_view` function with the second parameter (in this case 50) as the arguement.

2) Creating a block to show product information

What you need to get is the product name or id. If that is already in the url you can use `arg(2)` assuming your URL is "examples.com/product/50". Here is the api page for Drupals arg function.

Ideally you would then do database calls etc. with this arguement within a custom modules block. You can find out how to create a block in custom code here
> 0 votes

---
Tags: 7, path-aliases
---


# Question
Title: How add a custom page template for an article node
Hi I want to create an article then define a alias path for it then change template of that page. For example I add an article with title "categories" and no other content like body or image. Then I define "categories" alias for it. Now when I add "page--categories.tpl.php" in my theme template folder nothing happened to page http://example.com/categories and I just see a white page in content region.

# Answer
> 0 votes
The main issue is that templates rely upon the system path, not the alias.

So, while you are surfing to `categories` on your system, Drupal still really sees that as `node/###` in your case.

All is not lost, however, as there are several avenues available to you:

If you know the nid of the article, you can create a template for it like so:

```
page--node--###.tpl.php

```

eg

```
page--node--123.tpl.php

```

and no matter what the alias, Drupal will use this template when displaying that node.

If you don't know, or it might for whatever reason change later, but the title will always be the same, you can do something like this:

```
YOUR_DRUPAL7_MODULE_OR_THEME_preprocess_page(&$variables) {

   if (!empty($variables['node']) && $variables['node']->title=='Categories') {
     $variables['theme_hook_suggestions'][]='page__categories';
   }

}

```

Further reading and a lot more information on this can be found here:

https://drupal.org/node/1089656

and here:

https://drupal.org/node/223440#custom-suggestions (includes Drupal 6 methods as well)

# Answer
> 0 votes
Refer this url http://drupalknowledge.blogspot.in/2012/01/different-page-template-for-different.html

You can print $vars\['node'\] variable and get the particular node path to give different template.

I hope this will help you.

# Answer
> 0 votes
The new version of drupal should be able to do this automatically for you. Just copy page.tpl.php and rename it to page--node.tpl.php or page--category.tpl.php and then head to /admin/config/development/performance and clear the cache then refresh your site the new custom page should be loaded and ready for customization to your liking

# Answer
> -1 votes
In template.php theme\_preporcess\_page() if this fuction exist in template.php otherwise you need to create it .

then function themename\_preprocess\_page($variables) { you need to print\_r($variables); }

for node you can do similar function themename\_preprocess\_node($variables) ;

then this array find \[theme\_hook\_suggestions\] variable .here in array given page template suggestions ..

---
Tags: theming, path-aliases
---


title: Content type add node reference

text:
# Question
Title: Content type add node reference
I am adding a content type in Drupal 7. I want to add a simple node-reference field. Isn't this included in Drupal 7?

# Answer
> 3 votes
I agree with H.NiK both modules can help you to accomplish what you are looking for. However, I tend to think that the Relation Module is used for complex relationship. I use Entity Reference because it is exactly what I need because I don't need to use very complex relationship. You can find in this question some opinions about those modules. I will not recommend Reference because it will be deprecated in favor of Entity Reference. They mentioned in the page module.

You can find how to use entity reference from several sources one of my favorites is nodeone. Here are the links:

# Answer
> 5 votes
Use 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

or Entity reference:

> Provides a field type that can reference arbitrary entities

or Relation:

> Relation is an API module and storage model for both simple and the most complex relations between entities. The module can handle both directional and symmetrical relations very well.

# Answer
> 1 votes
I used both modules, References is more simple than Entity reference. If you don't need complex redefences between nodes i think References is better.

---
Tags: 7, nodes
---