# Question
Title: Drupal as (powerful) relational database
I’d like to make a Drupalsite, providing a platform for people around the world who are working on the same research topic to collaborate and communicate. (I’m sure Drupal is therefore an excellent choice).

However, this website should also include a relational database (which will be a very interesting research tool for the visitors of the website). A test version of this database already exists in ooo base: it has 50 tables with a lot of many-to-many and one-to-many relations between them. Very basically it records the relations between persons, events and organisations.

I know it’s possible to create a relational database in drupal by creating custom contenttypes and by using the entity connect module. However, having a look at the way Drupal stores these data in its mysql database, I’m afraid this way of building a database isn’t very useful for me, as it seems very difficult to query the data (or to use \[social network\] analysis software on them). The possibility of querying the data easily, is crucial for my database.

I know it’s possible to add a second database to the drupal site (cf http://drupal.org/node/18429). However, I’m not sure whether that’s the solution for my problem.

Very short I’d like to know:

(1) Whether it’s possible to change the way Drupal saves the data of some content-types in its mysql database, to a way which seems more “natural” for analyzing data (and being able to query them easily)

(2) Whether it’s possible to add a second mysqldatabase to the drupal site, which organizes the data of some content-types on a custom (more ‘natural’) way. If possible, the users of the drupal site have to be able to add content and to analyze these data, as if they were saved in the same database.

I’d be very thankful if someone could help me!

# Answer
> 3 votes
You have a good start on working with the databases. From my own experience I am loath to rely/allow Drupal to maintain any sensible data. And since you already have a robust database it sounds like it would not be a good option for you either.

With all that said, it seems like you want to simply hook into the node/content saving that occurs in drupal. You will then be able to connect to an external database and process and insert the data anyway you choose.

Node API Hooks \- D6 has similar functions, just named differently. There are a lot of hook points in the process. You can even alter forms and add your own submit functions.

# Answer
> 2 votes
If you want have your own workflow to save content types and its fields in database you may take look at Field Storage API. It is used to perform all "database access".

For example, you can take look at MongoDB module to see how it can be implemented. (I see that you need SQL DB just use this module as example).

Also take look at article "Remote entities in Drupal 7" that describes how the whole entity (i.e content type) can be saved in other place than default Drupal DB.

# Answer
> 1 votes
I recently started a sandbox for Drupal \<=\> Neo4J integration.

http://drupal.org/sandbox/Letharion/1861580

It's still in very early stages, but Neo4j sounds like it would be a way for you to allow much better querying. The idea is however not to change the way Drupal stores it's data, but rather duplicate the links between content.

---
Tags: database
---


title: How to render a view in a form

text:
# Question
Title: How to render a view in a form
I am building a configuration form in an admin menu. I'll have some input fields inline at top, and below, a table of data. I'd like to render a view of the data in the table so it can handle the paging, etc.

How can I access the view and render it?

# Answer
Use `view_embedd_view` function and you will get the view.

```
$output = views_embed_view($viewName,$display_id);
print $output;

```
> 1 votes

---
Tags: 7, forms
---


title: Add button on block body using php

text:
# Question
Title: Add button on block body using php
How To Add PHP code to the body of a Drupal 7 Block

I just want to make a button on block body. Is that possible?

this link will explain what i want to do \[add button\]: http://drupal.org/node/1046700

> This article is for Drupal 7 developers who have tried to put PHP code in the body of a Custom Block, but can't get it to run.

# Answer
I'm not sure why you need this and you want a similar module of PHP filter which adds a new text format.

If you are familiar with custom moduling and hooks, I would give you a straightforward solution. You could implement this using hook\_block\_view\_alter by defining custom patterns (tokens).

```
<?php
function mymodule_block_view_alter(&$data, $block) {
    $patterns       = array('[add button]'); # more replacement patterns here
    $replacements   = array('<button type="button">Button</button>');
    if(isset($data['content'])){
        $content = $data['content'];
        if(is_string($content)) {
            $data['content'] = str_replace($patterns, $replacements, $content);
        }
        elseif(is_array($content)) {
        }
    }
}

```

Here is the result.

You may expand the code as you like such as defining more tokens, adding criteria for certain blocks, user roles, etc. You can even create an administration page at **admin/config** to define token replacements from UI.
> 3 votes

# Answer
Enable the `PHP filter` in the core modules
> 0 votes

---
Tags: forms, blocks
---


title: Checked checkboxes after form submit

text:
# Question
Title: Checked checkboxes after form submit
i have a basic admin form, which shows all content types with checkboxes and save button:

```
function MYMODULE_admin_settings() {
    $types = node_type_get_types();

    $form['content_types'] = array(
        '#type' => 'fieldset',
        '#title' => t('Content types'),
        '#description' => t('test'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
    );
    foreach ($types AS $typename => $type) {
        $form['content_types'][$typename] = array(
            '#type' => 'checkbox',
            '#title' => $type->name,
        );
        }
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Submit'),
        );
        return $form;

}

```

When i submit i want to save checked content types somewhere(i don't know what is the best way - save to database or somewhere else like `variable_set`). And the question is how to show checked content types after submit form - `#default_value`. For example if i check `Article` and `Basic page` c.types submit it and save them to `db` i want to see them checked after page reload, how can i do this?

# Answer
> 7 votes
Most core (and contrib) modules make use of the `system_settings_form()` function which handily wraps around a form, and saves element values as variables automatically.

```
function MYMODULE_admin_settings() {
  $types = node_type_get_types();

  $form['content_types'] = array(
    '#type' => 'fieldset',
    '#title' => t('Content types'),
    '#description' => t('test'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  foreach ($types as $typename => $type) {
    $form['content_types']["MYMODULE_settings_$typename"] = array(
        '#type' => 'checkbox',
        '#title' => $type->name,,
        '#default_value' => variable_get("MYMODULE_settings_$typename", 0)
    );
  }
  $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
  );

  return system_settings_form($form);

}

```

You can then grab the value anywhere else in code like this (using the 'page' content type as an example):

```
$val = variable_get('MYMODULE_settings_page');

```

Which is a bit counter-intuitive. You might want to make use of a `checkboxes` type instead, e.g.

```
$options = array();
foreach ($types as $typename => $type) {
  $options[$typename] = $type->name;
}
$form['content_types']['MYMODULE_content_types'] = array(
  '#type' => 'checkboxes',
  '#title' => $type->name,
  '#options' => $options,
  '#default_value' => variable_get('MYMODULE_content_types', array())
);

```

Then you can get an array of all selected content types like this:

```
$selected_types = array_filter(variable_get('MYMODULE_content_types', array()));

```

---
Tags: forms
---


title: I have images missing between pages

text:
# Question
Title: I have images missing between pages
I have edited the page.tpl.php file to include an image in the header and another in the footer of the page.

When I am in the home page of the site ie. '/product\_range' the images are there. If I navigate to another part of the site ie. '/node/1' they are missing. Coincidently this is actually the same page just referenced differently in the url.

In the page.tpl.php template I have referenced the image like this:

```
<img src="<?php global $base_path; print path_to_theme(); ?>/images/brand_icons.gif" alt="" />

```

This is the actual path to the images: '\sites\all\themes\MySubTheme\images'

This is most frustrating... Thank you in advance for your assistance.

# Answer
> 1 votes
The return path from `path_to_theme()` doesn't have a slash at the front of it and so becomes relative to the path you're currently at. That would probably explain why it works for pages in the root of your site, but not those that are at least one directory down.

You should be able to fix it easily by adding a forward slash to the start of the image path:

```
<img src="/<?php print path_to_theme(); ?>/images/brand_icons.gif" alt="" />

```

On another note, make sure you fill the alt in...people with screenreaders will thank you for it :)

---
Tags: theming, media
---


# Question
Title: change custom css class to block content
When I create new block `drupal` auto create this `html` `tags` and default `css class` for block content:

```
<div class="content-block"></div>

```

now i need to edit `css/class` like this:

```
<div class="content-block2"></div>
<div class="content-block3"></div>
<div class="content-block4"></div>

```

It is possible? If YES, How To?

# Answer
> 1 votes
you can also use Block Class Module to manually add classes to each of your block.

# Answer
> 1 votes
You can override the template for the block.

To see what the template should be you can use the following in your themes template file.

**/sites/all/themes/YOURTHEME/template.php**

```
function YOURTHEME_preprocess_block(&$vars) {
   var_dump($vars['theme_hook_suggestions']);
}

```

Also make sure you have a copy of block.tpl.php in your themes template folder. You can get this by going to **/modules/block/** and copying the file to **/sites/all/themes/YOURTHEME/templates**.

This is handy because you can copy the code from the default block template to your custom block template and make any changes you want there. If you were to delete your custom block template it will default back.

Heres more on template (theme hook) suggestions http://drupal.org/node/1089656

---
Tags: 7, blocks
---


# Question
Title: Force capitalization of terms on entry with Autocomplete Deluxe module
I would like to force the capitalization of taxonomy term entries, or alternatively make them case insensitive so that 'book' and 'BOOK' are not different taxonomy terms. Is there a way to enable this. The context is this form http://www.wequest.co.uk/user/register on the 'skills' and 'resources' field... I need these to be standardised because they represent catalogues of skills and resources and I don't want duplicates either: of terms or due to different cases.

# Answer
> 2 votes
The Taxonomy dupecheck module would probably help for most of that (I'm not entirely sure about the case-sensitivity issue but give it a try; MySQL queries for term names will be case-insensitive so my gut instinct is this would work)

> Taxonomy dupecheck module prevents Drupal administrators from adding duplicate taxonomy vocabularies and/or terms. It's helpful when entering large amounts of terms or vocabularies in situations where each value must be unique. This saves time by preventing administrators from having to enforce a unique value policy through later cleanup of duplicate terms.

To force title-case on the term you could implement `hook_taxonomy_term_presave()` in a custom module and force it like so:

```
function MYMODULE_taxonomy_term_presave($term) {
  if (some_condition_applies_to($term)) {
    $term->name = ucwords($term->name); // Or ucfirst() depending on your requirement
  }
}

```

---
Tags: taxonomy-terms, ajax
---


title: Integrate forums with OG groups?

text:
# Question
Title: Integrate forums with OG groups?
i am using drupal 7.

I want to add forums in OG groups so that forums added in OG groups can only be accessible by members of the OG groups.

Is there any other option to grant access restriction on forms except using Form Access, because it will not integrate groups with forums?

# Answer
Check the module called OG Forum D7. This module allow to make some forum and their topics owned by an Organic group, just like any other group content.
> 0 votes

---
Tags: organic-groups, users, nodes
---


# Question
Title: Use VBO to send tokenised email in Drupal 6
I have a view table with bulk operations, and I have enabled the send tokenised email field. What I want to do with this is when this is selected and executed, it will take the email of the node which I have selected and send a mail with some content in it to the user. (e.g. we are looking at your support ticket). When I select a node in the table currently, select send tokenised email from the dropdown and click execute, it does nothing.

# Answer
> 3 votes
The Views Send module solved my issue.

> Views Send enables you to send mass mailing from a View.

---
Tags: 6, views
---


# Question
Title: Rule to send out content of newly created forum-topic or comment
I have a rule that will send me an email with the username of the person that creates a new comment or forum-topic. However, I would really like the URL and actual content to show up in the email. How can I accomplish this in that order of importance. Because right now I have to click on content on the site and look for the newest items to find the new content.

# Answer
Using rules, you can send the URL of the updated content as per the solution provided by @mohit\_rocks, but I was not able to find a solution to send the content / body (full / teaser) in the mail, using rules.

If you wish to send the content of the body too, you'll need to take help of the Notify module.

Steps to enable the send mails with the content of forum/topic in mail with the help of notify module:

1. Download and install notify module.
2. Under *admin \> people \> permissions*, set give the permission of *access notify* to the user role you wish the mails to go to. **Note:** The users of these roles need to enable the notification to enable receiving of the mails. You can keep this role limited to admin and let admins decide who receives the mail by following next step.
3. Go to *admin \> config \> people \>notify* and enable notification for *forum* content type: If you set time less than the time of your cron run, still the mail will be sent on cron run.
4. Go to *user \> uid \> notify* (replace uid with the the user id of the user). Admins can go to *admin \> people* select *edit* against any user, and go to *Notification settings* tab and check the following options: You can check the *Title + Body + Fields* under *Detailed settings* section to send the values in fields as well.
5. To check the list of users who will receive the mails, go to *admin \> config \> people \> notify \> users*:
6. That's it! Now the selected users should start receiving the notifications mails with content!

**Note:** If you have revisions enabled for the content type, and want to be notified when the content is edited, then check this feature request I've made at the module's issue queue. I've also created a patch for the same. If you have such requirement, then you can test the patch. If you post your findings on the issue, it'll be appreciated!
> 4 votes

# Answer
You can pass the parameters in the Rules module. See the screenshot below

By adding these parameters you can send any content /latest added contetn to mail body. When you click on **Edit** link of send mail, you will find the follwoing page and you can send any content you want to send.
> 2 votes

---
Tags: rules
---


title: Alternative to the Inline module

text:
# Question
Title: Alternative to the Inline module
I've been using inline images with the Inline module to display the attached image like `[inline:dreamspark.jpg=DreamSpark]`, but this module doesn't have a Drupal 7 version, yet.

Is there any alternative to this module? I have many nodes using this module.

# Answer
> 1 votes
There is a Drupal 7 version of that module, it's just in dev at the moment.

I think it's highly unlikely someone else will be developing a competing module along side the development of this one.

I'd advise downloading and installing the dev version of the module, if you get any errors report them back to the issue queue to help push it along.

You can actually check the current issue queue to see if there are any known problems that may stop you being able to use this in your new site...at least you'll know as early as possible.

# Answer
> 0 votes
My answer is not to use the inline module. In fact i suggest using an alternative setup that seems to work well with content editing. May i suggest the use of ckeditor and ICME. ckeditor is a nice WYSIWYG style editor that allows you to perform all of the necessary editing including images. ICME will give you a decent interface to upload images, setup quotes for users and few other things. check the docu for more info. you'll be able to get your images into content very easily. both are fully supported in D7.

---
Tags: 7
---


# Question
Title: Translating interface - same word duplication
I have "problem" i want to do one word translation e.g. 'Location' (same case) I use that word with t() function in (menu, module, template tpl, taxonomy) when I go to translate interface it show me same string: 4x"Built-in interface", 2x"taxonomy", 1x"fields". I have 4 languages and I have repeat everything for same word. Is it possible to do one translation and Drupal apply on all exact strings.

Thanks

# Answer
You need to translate each of these strings individually. It is not enough to do it only once.
> 2 votes

# Answer
It is enough to translate it only once; Drupal will use that translation for all strings that are the same.
> 0 votes

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


# Question
Title: drupal_http_request and stream_socket_client
The D7 core function drupal\_http\_request uses the stream\_socket\_client() php function. For many serious web hosters, sockets and stream\_sockets functions are a security bad practice and most of them disable these functions.

Why the D7 developpers don't make drupal\_http\_request rely on cURL functions ? Is there any alternative ? Thanks, J.

# Answer
> 2 votes
The cURL HTTP Request module was built for exactly that:

> This is a module intended for developers, as it provides just one API to call: curl\_http\_request().
>
> The function curl\_http\_request() is an alternative implementation of Drupal core function drupal\_http\_request() using cURL. The function intends to be backwards compatible with drupal\_http\_request(), by accepting the same parameters in the same form and by returning the response in the same format.

I can't comment as to the decision the original developers took, but don't forget that cURL isn't necessarily available on every system either.

# Answer
> 1 votes
I use Guzzle for anything requiring an HTTP-client. It's the official D8 http client, so future upgrades will require minimal work, and it's used by some of Amazon's official tools, so it should be "good enough" for most uses.

For the contrib module, there is currenly a problem with how to handle PSR-0 with composer loading in D7. If you don't need other composer loaded libraries, just stick with the 758860bdb0782aa6ec766655ba48b056c011bb59 commit for Guzzle. If you need others, you will need to head to the issue queue and see more details about solutions there.

I believe the reason curl wasn't relied upon was that curl-support in php wasn't considered widely enough available.

---
Tags: http-request
---


title: Output form result after form_submit

text:
# Question
Title: Output form result after form_submit
I have custom module, where after form\_submit, i do some calculations, and get result of those calculations in a variable.

After i hit "submit", i can output those calculations with **drupal\_set\_message** , but i would like to format results (array), and print it bellow the submit button. How can i output resulting variable bellow the form or in the form, after submission ?

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

$a=$b+$c;

// on submit, i would like to print/format $a on the reloaded form page

}

```

Thanks!

# Answer
What you want to do is use something like `$form_state['temporary']` in your `myMod_submit` function. Set `$form_state['temporary'] = $someValue` and rebuild your form. You also want your `myMod_form` function to have a place holder for your data. When the form is loaded, simply check to see if your temp holder is populated. if it is then you know you have a result and display it.

See code below.

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

    ...

    if(!empty($form_state['temporary'])) {
        $form['results'] = array(
            '#type'     => 'item',
            '#markup'   => $form_state['temporary'],
        );
    }

    return $form;
}

function myMod_submit($form_id, &$form_state) {
     ...

     $results = callSomeFunctionToGetResults();

     $form_state['temporary']   = $results;
     $form_state['rebuild']     = TRUE;

     ...
 }

```

i omitted all my code that would populated `$results` but this should get you to where you need to go.

***quick addition here.***

I just realized that you wanted it to go to another page and not the same page. I believe in your `myMod_submit` function you can use `drupal_goto()`. pass it a url and also pass it some options. you can then parse out the options as your values in the other page. See drupal\_goto. however, i haven't tested this option out.
> 5 votes

# Answer
If its a node form you can add an extra form submit handler to get the values Printed if not you probably have a submit function try `print_r`

As its a form submit you should try `exit` OR `die`

```
function my_module_my_form_submit($form, &$form_state) {
    //drupal_set_message(t('The form has been submitted.'));
    //drupal_set_message('<pre>'.print_r($form_state, 1).'</pre>');
    print_r($form_state, 1);
    die('Check the die !');
}

```

Basic form with submit handler

How do I add an additional submit handler
> 0 votes

# Answer
A simple solution to access variables outside the function in other function is to make the scope of the variable as global.

```
function mymodule_form_submit($form, &$form_state) {
  global $a;
  $a=$b+$c;
}

```

And on submit, in other function you can access this variable by something like:

```
function some_page_load_function() {
  global $a;
  //print/format $a according to requirement.
}

```

I've written the function name to be `some_page_load_function`, as I'm not sure about the function you're wishing to access the value; as you also mentioned that this module might be a part of admin region.
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Views Search Ignoring Custom Node Access permissions
I have a hook\_node\_access function that denies users view access to a page node if the node has a certain tag and they are not an authenticated user.

This is working fine for viewing the page directly but unregistered users can still see the nodes that they should be denied in a views powered search page. When they click through to the page they are denied access.

I was using the taxonomy access control module to do this before and that hid the result from search, I had to disable it because of a conflict with another module.

Is there anything extra I need to do to make views recognise these permissions?

Here's my hook and helper function:

```
function mymod_page_perms_node_access($node, $op, $account){
  if ($op === 'view' && in_array($node->type, array('page','publication'))){
    $access_level = field_get_items('node', $node, 'field_access_level');
    if (count($access_level)){
      $access_level = $access_level[0]['tid'];

      $accessIDtoRoleID = array(
        '68' => '7',
        '69' => '2');
      if (isset($accessIDtoRoleID[$access_level])){

        global $user;
        $requiredRole = $accessIDtoRoleID[$access_level];
        if (mymod_page_perms_check_allowed_roles_array(array($requiredRole),$user->roles)){
          return NODE_ACCESS_ALLOW;
        } else {
          return NODE_ACCESS_DENY;
        }
      }
    }
  }

  return  NODE_ACCESS_IGNORE;
}

function mymod_page_perms_check_allowed_roles_array($allowedRolesIds,$roles){
  foreach ($roles as $rid => $role){
    if (in_array($rid, $allowedRolesIds)){
      return true;
    }
  }
  return false;
}

```

thanks

# Answer
It seems that a better way to control node access is through hook\_node\_access\_records and hook\_node\_grants as described in the Drupal documentation writing a module that handles node access . This works with views properly.

I wrote this simple module based on the instructions in the link above:

```
define('MYMOD_REALM', 'mymod');
define('MYMOD_GRANT_ID_PUBLIC', 0);
define('MYMOD_GRANT_ID_MEMBER', 1);
define('MYMOD_GRANT_ID_BOARD', 2);
define('MYMOD_BOARD_MEMBER_RID', 7);
define('MYMOD_MEMBER_TID', 69);
define('MYMOD_BOARD_MEMBER_TID', 68);

/**
  * Implementation of hook_node_grants().
  */
function mymod_node_grants($account, $op) {

  if ($op == 'view') {
    $grants[MYMOD_REALM] = array( MYMOD_GRANT_ID_PUBLIC );
    if (array_key_exists(DRUPAL_AUTHENTICATED_RID, $account->roles)) {
      $grants[MYMOD_REALM][] = array( MYMOD_GRANT_ID_MEMBER );
    }
    if (array_key_exists(MYMOD_BOARD_MEMBER_RID, $account->roles)) {
      $grants[MYMOD_REALM][] = array( MYMOD_GRANT_ID_BOARD );
    }
    return $grants;
  }
}

/**
 * Implementation of hook_node_access_records().
 */
function mymod_node_access_records($node) {

  $grant = array(
      'realm' => MYMOD_REALM,
      'gid' => MYMOD_GRANT_ID_PUBLIC,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 0,
    );
  if (in_array($node->type, array('page','publication'))){
    $access_level = field_get_items('node', $node, 'field_access_level');
    if (count($access_level)){
      $access_level = (int)$access_level[0]['tid'];

      switch ($access_level) {
        case MYMOD_BOARD_MEMBER_TID:
          $grant['gid'] = MYMOD_GRANT_ID_BOARD;
          break;
        case MYMOD_MEMBER_TID:
          $grant['gid'] = MYMOD_GRANT_ID_MEMBER;
          break;
      }
    }
  }
  $grants[] = $grant;

  return $grants;
}

```
> 5 votes

---
Tags: views, search, users
---


# Question
Title: Seperate Drupal instance as files server for other Drupal instances
My task is to create files gallery which is files library for other Drupal instances.

Other instances can upload files to library and browse them. File metadata are stored in library (A) and client, but physical file is stored only in A. So instance A acts like some kind of CDN.

Could someone share with me his thoughts about this problem? Which modules to use? (besides CDN which I am testing now)

I can accept only free solutions.

# Answer
> 1 votes
You could use feeds module to periodically import file URIs from XML on your file server to you individual drupal instances. You might then be able to hook that up with the media module and use the files on all your different sites.

Edit: If you're just looking for a cdn for your images you could probably just use Amazon S3. Looks like there's a few modules already built to work with it

---
Tags: 7, cdn, media, files
---


# Question
Title: How can I limit a list of node tokens to only a particular node type?
We have many content types and fields, and the "Edit Node Type" page is taking about 30 seconds to load. The culprit appears to be a module that lists all of the available "node" tokens, using this code:

```
$form['modulename']['token_help'] = array(
  '#theme' => 'token_tree',
  '#token_types' => array('node'),
);

```

'#token\_types' =\> array('node') gives Node tokens for every content type, even though the form will only pertain to the one Content Type.

Is there a way to limit the token tree to display only node tokens pertaining to a specific content type (without using Token Tweaks module)?

# Answer
> 3 votes
I'll just answer this as a "No". Token Tweaks is what I needed to use to prevent long page loads (30 seconds at times...)

---
Tags: 7, tokens
---


# Question
Title: Manually deleting images (from db and file_usage table)
I was given 'temporary' images for a number of bio pages, and now have better quality images to replace them with. Removing or replacing the old images in the Admin UI is failing (without giving me any error messages or indications of anything wrong: the old image is just there no matter what I do). If I connect to the server by SSH and `rm CEO.jpeg` from bash, then the database is out of sync with the file system, and when I upload the new version of CEO.jpeg, I get an error because that is already in the database.

If I just edit the `file_usage` table and set `count` to `0`, will that have any nasty side effects? (I will also, of course, manually delete the file from the file system.) Do I have to manually track down each node and edit it too? Or can I just go to those nodes in the Admin UI after manual removal and add the new versions of the images?

(I've checked answers to this question and this question but the situation in those is very different.)

# Answer
> 1 votes
This is probably more of a comment but the code won't fit in...there should be no reason for the UI to fail on the file delete, unless the web server daemon doesn't have write permission to the files folder. That would be the first thing I'd check, then try again.

If that fails, you might want to give it a go manually:

```
$nids = db_query("SELECT nid FROM {node} WHERE type = 'the_type'")->fetchCol();

foreach (node_load_multiple($nids) as $node) {
  $node->field_name[LANGUAGE_NONE] = array();
  node_save($node);
}

```

That will take care of the whole lot (removing the data from file\_managed, file\_usage, and deleting the file from the disk if it exists and is writeable).

---
Tags: 7, media, files
---


# Question
Title: Drupal 7 Syntax Highlighter not applied when logged in as user or admin
I have a Drupal 7 website.

I installed the syntax highlighter module and downloaded the library. I was very careful following instructions when configuring the module. I also configured it to get the "insert syntax highlighter button" when using the ckeditor library through the wysiwyg module. Yet, the highlighting is only applied when I preview an article.

If I do save that article, the highlighting is gone. Then if I logout, it is applied as an anonymout user. So my question is... Is this normal? I've been trying to fix this for hours but no luck.

# Answer
Well, since nobody seems to want to answer my question, I will provide my solution to the problem. As I have discovered. Drupal do not load all javascripts, go figure why.

So, what I did is go to the admin panel. In configuration/performance you can aggregate all javascript files into one big file which apparently helps minimize server requests. When I did that, it worked. The syntax highlighting is now applied all the time, with a nasty side effect.

I got my code-hightlighting effect working but now, the wysiwyg shows up in comment's textarea field with a background that matches my websites... How unfortunate!
> 0 votes

---
Tags: users, input-formats
---


# Question
Title: 2 seperate feeds updating the same set of nodes (feeds module)
I'm using the feeds module to pull in a set of publications into a Drupal content type. They are set to run at regular intervals using cron. I have two separate feeds, which should work as follows:

* Feed 1 (pure\_feed) - pulls in the bulk of the fields
* Feed 2 (harvard\_format) - accesses a separate url source and updates one field on the content type.

The problem I have is that feed 2 always creates a new set of nodes rather than updating the existing nodes (that were created using feed 1). I have used the debug options at /import and can see that the GUIDs for feed 2 match the GUIDs for feed 1, but it still creates 2 sets of nodes rather than updating the 1 set of nodes.

Here is an excerpt from the feeds\_items database table:

As you can see they both have the same GUID but they are mapped to separate nodes. Is there any way to have the second feed map to the same nodes as the first feed?

# Answer
> 0 votes
EDIT: there's a patch in this thread: https://www.drupal.org/node/1539224

I knocked something together that allows my second feed to update the nodes from my first feed. Not sure if this is the right way of doing things but it works. Here's what I did in case it helps someone else in future:

* Created a custom processor that extends FeedsNodeProcessor
* Copied across all of FeedsNodeProcessor's functions to the new class.
* Overrided the existingEntityId function as follows (harvard\_format is my secondary feed and pure\_feed is my primary feed):

protected function existingEntityId(FeedsSource $source, FeedsParserResult $result) {

```
if($source->id == 'harvard_format') {

  $query = db_select('feeds_item')
    ->fields('feeds_item', array('entity_id'))
    ->condition('feed_nid', $source->feed_nid)
    ->condition('entity_type', $this->entityType())
    ->condition('id', 'pure_feed');

  // Iterate through all unique targets and test whether they do already
  // exist in the database.
  foreach ($this->uniqueTargets($source, $result) as $target => $value) {
    switch ($target) {
      case 'url':
        $entity_id = $query->condition('url', $value)->execute()->fetchField();
        break;
      case 'guid':
        $entity_id = $query->condition('guid', $value)->execute()->fetchField();
        break;
    }
    if (isset($entity_id)) {
      // Return with the content id found.
      return $entity_id;
    }
  }
  return 0;
}
elseif ($nid = parent::existingEntityId($source, $result)) {
  return $nid;
} else {

  // Iterate through all unique targets and test whether they do already
  // exist in the database.
  foreach ($this->uniqueTargets($source, $result) as $target => $value) {
    switch ($target) {
      case 'nid':
        $nid = db_query("SELECT nid FROM {node} WHERE nid = :nid", array(':nid' => $value))->fetchField();
        break;
      case 'title':
        $nid = db_query("SELECT nid FROM {node} WHERE title = :title AND type = :type", array(':title' => $value, ':type' => $this->config['content_type']))->fetchField();
        break;
      case 'feeds_source':
        if ($id = feeds_get_importer_id($this->config['content_type'])) {
          $nid = db_query("SELECT fs.feed_nid FROM {node} n JOIN {feeds_source} fs ON n.nid = fs.feed_nid WHERE fs.id = :id AND fs.source = :source", array(':id' => $id, ':source' => $value))->fetchField();
        }
        break;
    }
    if ($nid) {
      // Return with the first nid found.
      return $nid;
    }
  }
  return 0;
}

```

}

* Copied across the the Process and newItemInfo functions from FeedsProcessor.
* Overrided newItemInfo as follows:

protected function newItemInfo($entity, $feed\_nid, $hash = '') {

```
$entity->feeds_item = new stdClass();
$entity->feeds_item->entity_id = 0;
$entity->feeds_item->entity_type = $this->entityType();
// Specify the feed id, otherwise pure_feed's entries in the feeds_item table will be changed to harvard_format
$entity->feeds_item->id = ($this->id == "harvard_format") ? "pure_feed" : $this->id;
$entity->feeds_item->feed_nid = $feed_nid;
$entity->feeds_item->imported = REQUEST_TIME;
$entity->feeds_item->hash = $hash;
$entity->feeds_item->url = '';
$entity->feeds_item->guid = '';

```

}

---
Tags: 7, feeds
---


# Question
Title: Unlimited text field type and unordered list with links
I'm continually amazed at how powerful drupal can be. Im using **Drupal 7** and right now I am curious to see if its possible to **create a field for a custom content type where I enter text that becomes links via an unordered list**. I would love if I could enter this into the CMS without having to go into the code.

I managed to find a way of creating the unordered list by customizing the field template file (field.tpl.php) which is great, but curious if there is a way to wrap the text items in an href.

```
<ul>
<li><a href="link1.com">Link 1</a></li>
<li><a href="link2.com">Link 2</a></li>
<li><a href="link3.com">Link 3</a></li>
</ul>

```

Thanks all!

# Answer
> 0 votes
I found out a perfect module to do just what I wanted called Link.

---
Tags: theming
---


# Question
Title: how can have this url car1?category=blue car?category=red car2?category=blue
for drupal 6.x I have a vocabulary with terms car1 car2

and a vocabulary with terms red blue yellow

how can to do this 2 menu 1) car1 | car2 (this really how a select)

2) Allcolor | red | blue | yellow

3) here the results

when I click on car1 I have a page with all the car1's color nodes (and the Allcolor menu active) url think so must to be: /car1

if I click on red I have the result of car1 red nodes /car1?category=red if select blue /car1?category=blue

when am on red under car1 and click on car2 I have the red car2 results /car2?category=red

not sure if the url is so, but which is solution for to do this functionality?

I know that is simple with only one vocabulary type this car1 red blue yellow car2 red blue yellow

but I must to do with distinct vocabulary; the terms really are more

# Answer
> 0 votes
for every views is necessary to have one exposed; but isn't possible manage the

1) car1 | car2 menu1 2) Allcolor | red | blue | yellow menu2

menu2 how a submenu of menu1, also if isn't a unique vocabulary?

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


# Question
Title: Problem with escaped characters in attributes
The default `theme_image()` is implemented as

```
function theme_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

```

`drupal_attributes()` is implemented as

```
function drupal_attributes(array $attributes = array()) {
  foreach ($attributes as $attribute => &$data) {
    $data = implode(' ', (array) $data);
    $data = $attribute . '="' . check_plain($data) . '"';
  }
  return $attributes ? ' ' . implode(' ', $attributes) : '';
}

```

and `check_plain()` as

```
function check_plain($text) {
  return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

```

Since `htmlspecialchars()` is being called with `ENT_QUOTES`, single quotes in my title and alt text on the image are being escaped as `'` and double quotes as `&#quot;`, so hovers look weird.

Is there an acceptable, safe, secure way to handle this situation?

# Answer
> 3 votes
Make sure you aren't `check_plain()`ing the value before calling it, eg, don't do:

```
... theme('image', array('path' => 'test.jpg', 'alt' => check_plain($foo));

```

or otherwise use a $value that has been processed by any 'safe' filters.

---
Tags: theming
---


# Question
Title: How do I resolve this conflict between two Feature modules?
I have two content types with various menus, views, menus, etc. which I have packaged as two Feature custom modules. The two content types both use a taxonomy and use several of the same fields in the database. When I load these Feature modules in a new site, they show conflicts with each other over these common fields and vocabulary and I am not certain what would be the best way to resolve the conflict.

Although the Feature modules are intended to work together, they do not need to both be present on the same site. Each may also work with other different features as well. They both use the taxonomy and fields for views filtering etc so it makes sense that they each include these components in their Feature definition. Should I:

* Remove the fields and taxonomy from one of the modules, and declare a dependency to the other? This is not desirable since each can work without the other.
* Make two versions of the features, one for independent use, and one for collaborating.
* Define the fields and taxonomy as a separate feature?
* Ignore the conflict and enable the modules? (If I do, will they both share the field?)
* Another solution?

I have not yet tested this, but will disabling or uninstalling one of the two Features modules remove the fields from the database even though the other module requires it?

# Answer
> 17 votes
Create a third Feature defining the components(\*) used by the other two independent Features.

In the other two Features, remove the components which are now claimed by the third Feature, and instead, list the third Feature as a dependency.

(\*) ~~In Features for Drupal 7, however, this functionality isn't yet committed — see http://drupal.org/node/1064472, and help review the proposed code there.~~ — This patch has been committed to Features 7.x-2.x.

# Answer
> 1 votes
This solution on d.o worked great for me, far more robust to be exported to various sites than creating a third feature, which would create orphaned fields in another unrelated site.

http://drupal.org/node/1698290

# Answer
> 0 votes
One solution that worked for me was to attach the two Features into one bigger feature.This solved the conflicts.

---
Tags: features
---


# Question
Title: Block not showing on a matching path (menu item duplicate)
I have a strange situation and would like to verify it with you.

I have a menu block of main manu level 2+ links.

```
Corporate     [<--block title, level 1 of Main Menu]
  About Us    [corporate/about-us]
  Services    [corporate/services]
  Contact Us  [corporate/contact-us]

```

It is configured to appear only for pages with addresses matching the pattern `corporate/*`. So far so good. But in order to better communicate the Contact Us page, I created manually a duplicate of the Contact Us (with the same `[corporate/contact-us]` alias) at level 1 of the Main Menu. Once that duplicate is there, the block disappears from the Contact Us page.

Is there a Drupal culprit I bumped into? Is there a workaround for this?

# Answer
Perhaps on the Contact Us page, the block is trying to display child menu entries for the new level 1 "Contact Us" item, and there are none? The block won't get rendered if there's no content.
> 0 votes

---
Tags: routes, path-aliases, blocks
---


# Question
Title: cout rows of a view for new content and comments
I have made a view getting the new content added and new comments

But i need to get its count and so i usedthe following code

```
$view = views_get_view('new_activity');

$view->set_arguments(array(arg(2)));

$view->execute();

return l(count($view->result), 'new-activity/' . arg(2));

```

but i see untrue number related to the view page

how to fix it espicially using history\_timestamp attribute of each row

the main problem is that the views gets , data and hide the viewed rows and only shows the unviewed rows which gives me wrong count

please help or advice with a better scenario

thanks in advance

# Answer
`count($view->results)` will only give you the number of the results on the current page if using a paged View. Try using `$view->total_rows` instead, which will give you the total number of rows returned by the View:

```
return l($view->total_rows, 'new-activity/' . arg(2));

```
> 0 votes

---
Tags: views
---


# Question
Title: How to load to panels a referenced node?
I have the user profile panel and I want to load in the panel a node that is referencing this user. There is a trick to load a view in the panel,but I don't know exactly how to do this... Can somebody help me on this?thanks

# Answer
> 2 votes
You'll want to add a display to your view of type "pane". Give it a descriptive title so you can find it from your Page Manager.

Then you'll create a Page Manager variant that displays on the entity (user) to which you want to attach this view. Under "content" you'll click the gear that appears in the top left, and click "add content". Select "view panes" and then select the view pane you just created.

In order to pass the node ID to the view pane, you'll go back to the view. Under "pane settings" select "argument input" and set it to "from panel argument". You'll probably want the first argument.

---
Tags: views, panels, 7
---


# Question
Title: Video.module: Rendering playablefiles programmatically
I am trying to pull the "playablefiles" URIs from the array for a video field (hereafter: field\_video).

Here's a look at how the array is set up.

I'm trying to pull a list of the files by this method, which seems to be in error:

```
  foreach($node->field_video['und']['0']['playablefiles']) {
    echo $node->field_video['und']['0']['playablefiles']['uri'];
  }

```

Can anyone tell me what I'm doing wrong here?

# Answer
There are a few things that could do with attention...

* A `foreach` statement needs an `as` keyword to keep a reference to the current object in the iteration (the docs explain it better than that, it's worth having a read). This error should throw an exception.
* From the looks of the array each 'playablefile' is an object (not an array) so you need to access its members with `->` not `[]`. If the interpreter makes it this far this should also throw an exception.
* You can also make use of the API and make your code language safe using the `field_get_items()` function

The resulting code should be:

```
$field_items = field_get_items('node', $node, 'field_video');
foreach ($field_items[0]['playablefiles'] as $file) {
  echo $file->uri;
}

```
> 1 votes

---
Tags: entities, files
---


# Question
Title: How do I duplicate a menu item properly?
Say I need to have the same menu item appear in two different menu trees or at two different level of the same menu. How do I properly "duplicate" a menu item using `hook_menu()`?

To my understanding, if the original item has its path `corporate/contact-us`, then putting in the `hook_menu()` the same path will override the original rather than create a copy. Am I right? How do I clone, or should I say: alias, a menu item programmatically?

(And I need to do that for each language defined for my site.)

---

I have used this piece of code, using `hook_menu_alter()` which for some reason did not work; once an item has been created it did not change its label and produced buggy, combined paths (/en/polish/path). Hence the attempt to unset the custom item first.

```
function MYMODULE_menu_alter(&$items) {
  global $language;

  $custom_items = array(
    'pl' => 'firma/kontakt',
    'en' => 'corporate/contact-us',
  );

  foreach($custom_items as $langcode => $path) {
    unset($items[$path]);
  }

  switch ($language->language) {
    case 'en':
      $items['corporate/contact-us'] = array(
        'title' => 'Contact Us',
        'page callback' => 'node_load',
        'page arguments' => array(285),
        'access callback' => TRUE,
        'menu_name' => 'main-menu',
        'type' => MENU_NORMAL_ITEM,
      );
      break;

    case 'pl':
      $items['firma/kontakt'] = array(
        'title' => 'Kontakt',
        'page callback' => 'node_load',
        'page arguments' => array(286),
        'access callback' => TRUE,
        'menu_name' => 'main-menu',
        'type' => MENU_NORMAL_ITEM,
      );
      break;
  }
}

```

---

Similarly, the following `hook_menu` approach did not work for me, with similar problems. This one was even worse in that the 'fake paths' with '2' in the title where visible to the user in the status bar.

```
function sint_newsnavi_menu() {
  global $language;

  switch($language->language){
  case 'en':
    $items['corporate/contact-us2'] = array(
      'title' => 'Contact Us',
      'page callback' => 'drupal_goto',
      'page arguments' => array('node/285'),
      'access callback' => TRUE,
      'menu_name' => 'main-menu',
      'type' => MENU_NORMAL_ITEM,
    );
    break;
  case 'pl':
    $items['firma/kontakt2'] = array(
      'title' => 'Kontakt',
      'page callback' => 'drupal_goto',
      'page arguments' => array('node/286'),
      'access callback' => TRUE,
      'menu_name' => 'main-menu',
      'type' => MENU_NORMAL_ITEM,
    );
    break;
  }
  return $items;
}

```

# Answer
> 1 votes
The code that works in any case, whatever corporate/contact-us is a view, a menu item defined from another module in its `hook_menu()`, or a path alias for a node, is similar to the following one.

```
function mymodule_menu() {
  $items['the menu path you prefer'] = array(
    'page callback' => 'mymodule_page_callback',
     // …
  );

  return $items;
}

function mymodule_page_callback() {
  drupal_goto('corporate/about-us');
}

```

The only problem with this code is that it could redirect users to a page to which they could not have access, and for which they would get an access denied error. If the users don't have access to a menu item, the menu item should be hidden to them, and that can be done by adding the right access callback to the menu item.

```
function mymodule_menu() {
  $items['the menu path you prefer'] = array(
    'page callback' => 'mymodule_page_callback',
    'access callback' => 'mymodule_access_callback',
     // …
  );

  return $items;
}

function mymodule_page_callback() {
  drupal_goto('corporate/about-us');
}

function mymodule_access_callback() {
  if ($router_item = menu_get_item('corporate/about-us') && !empty($router_item['access'])) {
    return $router_item['access']);
  }

  return FALSE;
}

```

In this case, the access callback just checks the users have access to the menu item to which they are going to be redirected.

---
Tags: routes
---


title: Code in the template or in a module?

text:
# Question
Title: Code in the template or in a module?
Is it better to write hook functions in `template.php` (or a .inc in my theme folder) or is it better to put them in custom modules? Or, does it matter? Is it just a matter of organizational preference? Does it depend?

# Answer
> 3 votes
Id say its simple case of organisation and relevance. Hooks fit into three different categories, alter, process and theme so probably best to organise these into separate include files.

```
inc/
template.alter.inc
template.process.inc
template.theme.inc

```

If your going to add a class to a button in a certain contrib module or similar then obviously creating a custom module is overkill.

Probably the best strategy to have is to work on the theme layer and it will soon be apparent if its worth putting the relevant code into its own module. Either way, you have achieved what you wanted.

Does it matter where the code is? Probably not, it's a few checks or calls wherever it is. Your probably get many an argument on best practices from various developers on this.

# Answer
> 1 votes
> Is it better to write hook functions in template.php, or is it better to put them in custom modules?

First off, themes can just implement theme functions, or alter hooks; themes cannot implement `hook_user_load()`, `hook_node_update()`, or `hook_menu()`, which are not alter hooks (i.e. hooks whose names end in \_alter, such as hook\_form\_alter()).

As for implementing a functionality in a theme, or in a module, I would rather implement the functionality in a theme if it is dependent from the theme. If the functionality must be present independently from the theme, then it should be implemented in a module. The latter case is also true when the functionality needs to be implemented when the enabled theme is one between two, or three possible themes.

---
Tags: theming
---


# Question
Title: Is possible to choose the file_default_scheme to save avatars?
I'm using amazonS3 module and if I choose Amazon Simple Storage Service as my default download option, user's avatars are uploaded to my bucket in Amazon. I wish I could choose the default\_scheme for avatars but checking the user\_save function code I found these:

```
 if (!empty($account->picture->fid) && (!isset($account->original->picture->fid) || $account->picture->fid != $account->original->picture->fid)) {
    $picture = $account->picture;
    // If the picture is a temporary file move it to its final location and
    // make it permanent.
    if (!$picture->status) {
      $info = image_get_info($picture->uri);
      $picture_directory =  file_default_scheme() . '://' . variable_get('user_picture_path', 'pictures');

```

So I think that it uses the default scheme selected. Is it possible to change it?

Thanks

# Answer
> 0 votes
`file_default_scheme()` returns a variable using `variable_get()`, unfortunately it just returns it straight without hooking out to any other modules.

For modules that call `user_save()` directly I don't see any way around this without patching the user module, there's just no way to intercept it.

For the user profile and registration forms you might be able to override the submit handlers, and call your own version of `user_save()` which contains logic to choose the right file scheme. I don't have time to test it but it would probably look something like this:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    // Remove the standard submit handler
    if(($key = array_search('user_profile_form_submit', $form['#submit'])) !== FALSE) {
      unset($form['#submit'][$key]);
    }
    // And add the custom one
    $form['#submit'][] = 'MYMODULE_user_profile_form_submit';
  }
}

function MYMODULE_user_profile_form_submit($form, &$form_state) {
  // Copy the code from user_profile_submit() and change the user_save()
  // line to MYMODULE_user_save()
}

function MYMODULE_user_save($account, $edit = array(), $category = 'account') {
  // Copy the code from user_save() and change the file scheme as required.
}

```

There might be some caveats to that I haven't though of but hopefully it'll provide a good place to start.

# Answer
> 0 votes
The code you show is executed from `user_save()` right after invoking hook\_entity\_presave(). You could implement that hook using the following code.

```
function mymodule_entity_presave($entity, $type) {
  if ($type == 'user' && is_object($entity) && !empty(entity->is_new)) {
    if (!empty($entity->picture->fid) && (!isset($entity->original->picture->fid) || $entity->picture->fid != $entity->original->picture->fid)) {
      $picture = $entity->picture;
      if (!$picture->status) {
        $info = image_get_info($picture->uri);
        $picture_directory =  'your scheme://' . variable_get('user_picture_path', 'pictures');

        file_prepare_directory($picture_directory, FILE_CREATE_DIRECTORY);
        $destination = file_stream_wrapper_uri_normalize($picture_directory . '/picture-' . $account->uid . '-' . REQUEST_TIME . '.' . $info['extension']);

        if ($picture = file_move($picture, $destination, FILE_EXISTS_RENAME)) {
          $picture->status = FILE_STATUS_PERMANENT;
          $entity->picture = file_save($picture);
          file_usage_add($picture, 'user', 'user', $entity->uid);
        }
      }
    }
  }
}

```

It's the same code used by `user_save()` with the exception that it doesn't use the scheme returned from `file_default_scheme()`, but it uses `'your scheme://'`. (Remember to change that with the scheme you want to use.)

Once that code is executed, `$picture->status` is not 0, and the equivalent code used from `user_save()` will not be executed.

My code doesn't change `picture->status` when `file_move()` fails, which is what `user_save()` does too.

This is the code I would use, as it makes you duplicate as less code as possible.

---
Tags: users, media
---


# Question
Title: How do I load information for views programmatically?
I have a view for a blog page that has the basic fields associated such as title, body, post-date, image, and author. What I need is a way to get access to the fields of the view to show on parts of the site with out creating a page or block. I just need the view to organize my information and will be using jQuery to parse the data.

# Answer
> 4 votes
Sounds like you could use views\_get\_view\_result().

> **views\_get\_view\_result($name, $display\_id = NULL)**
>
> Get the result of a view.

Also take a look at this answer for a more complete solution.

# Answer
> 3 votes
It sounds like you may want to use an Entity Field Query

To do something like gather the nodes tagged with taxonomy term of tid = 2 in `field_your_taxonomy_field`, do something like the following:

```
 $query = new EntityFieldQuery;

 $result = $query
   ->entityCondition('entity_type', 'node')
   ->propertyCondition('status', 1)
   ->fieldCondition('field_your_taxonomy_field', 'tid', 2, '=')
   ->execute();

```

This returns a list of IDs (in this case `nid`s) of entities that meet the conditions specified. To get info beyond the ID, you would load the entity and extract the value, with something like:

```
foreach($results['node'] as $result) {
  $nid = ($result->nid);
  $node = node_load($nid);
  print($node->title);
}

```

To be clear, this cannot load information from a view that has already been created, but it can be used *instead* of a view. This can be good if you don't need the view for purposes other than the fields you're trying to display right now or you need to display fields other than the way your view does.

---
Tags: views, javascript
---


# Question
Title: How can I handle restricted items on a Drupal Commerce site with special display and checkout rules?
I'm about to undertake the building of a Drupal Commerce site that has special restrictions around purchasing some of it's items. Specifically these items will not have displayed prices and a sales rep must approve their purchase. I'm new to Commerce but not Drupal I'm basically looking for advice here...

The use case is not set in stone but the case that I would like to achieve is basically this:

user can see restricted item and can add it to their cart but the price displays as 'request a quote' (I thought maybe views could do this with rewrites but I need logic it doesn't offer) I need to add other actions regarding line items as well ('request a sample' in particular).

when request a quote item is added to the cart trigger modal legal mumbo jumbo

once in the cart view the order is categorized into 'purchasable items' and 'request a quote items'

When the cart is submitted only purchasable items will be actually purchased, request a quote items will sent via email to reps/automated in some way/saved in the cart for later.

Maybe a rep can trigger user status change and prices become reveled/items are moved to purchasable, perhaps not?

**I'm guessing I'm going to need a custom module? Is this even possible, processing part of a cart like this? Any of you E-comm pros build something similar, how did you do it?**

# Answer
> 1 votes
So found that I was mostly in uncharted water on this but I waded through and I am mostly done building, so I will explain how I did it for the next guy.

I used quite a few modules, including a few custom modules...

Commerce wishlist was used as a template to create two custom modules 'request a quote' and 'request a sample'.\` They are essentially extra carts with custom actions.

Another custom modules was used to alter/disable parts of the commerce line item based on CCK field values. It will also be responsible for altering the checkout process/adding safety coniditions when I get around to that.

Taxonomy maintains a multi-dimensional product hierarchy. Tokens, Url Aliases and Views with 'global exposed filter' + views\_php create the catalog. Views are embedded into tpl files and passed arguments programmatically from node properties in lue of using product references (I needed more customization/arguments) than they offered.

The answer in short to building most of my problems was to be very Drupal-y about it and ignore a lot of the out of the box functionality of commerce...Aka: Take the views hammer to it!

That's about it. Good luck future Drupal Commerce dev!

---
Tags: 7, views, commerce, rules
---


# Question
Title: Help outputting Drupal View JSON data using getJSON function
I'm trying to return the view data and display it in a list for verification.

It is sending for the data and seems to receive it (I get a 200), but it is not outputting the data.

Any help much appreciated!

```
<div id="ajax"></div>

<script type="text/javascript">
$(document).ready(function(){

    $.getJSON('/views/ajax?view_name=latest_new&view_display_id=page_1&view_args=city', function(data) {
        var items = [];

        $.each(data.items, function(i, item) {
            items.push('<li id="' + i + '">' + item + '</li>');
        });

        $('<ul/>', {
            'class': 'my-new-list',
            html: items.join('')
        }).appendTo('#ajax');

    });

});
</script>

```

# Answer
> 1 votes
For anyone interested in my (current) solution.

My view outputs all nodes date descending. My secondary menu consists of taxonomy terms that can be passed to the view as arguments. The code below works for displaying nodes containing the specified taxonomy term.

It needs work, but so far so good.

```
$('#block-menu-secondary-links a').bind('click', function(){
    var arg = $(this).attr("title");
    $.get('views/ajax?view_name=latest_new&view_display_id=page_1&view_args='+arg, null, response);
    return false;
});

var response = function(data) {
    var result = Drupal.parseJson(data);
    $('#content').html(result.display);
}

```

# Answer
> 2 votes
```
$.ajax({
  url:'views/ajax',
  dataType: 'json',
  data:{
    view_name: 'my view name',
    view_display_id: 'default',
    view_args: 'view argument goes here',
  },
  success: function(data, textStatus, jqXHR){
    if(data[1].data !== undefined){
      // the view results will be in data[1].data
    }
  }
})

```

# Answer
> 0 votes
I don't think `/views/ajax`'s result is as you expect it to be. On Drupal 7, it returns an array of Ajax Commands, not the views results as an array of strings. See `views_ajax()` (or `views_ajax()` for Drupal 6).

If you want to retrieve the results of a views as a JSON array, it's probably easier to use the Views Datasource module.

After viewing the Firebug screenshot, there is no `items` properties on the `data`argument of the `$.getJSON`'s callback. Your `$.each(data.items, function(i, item) {...});` loops over an `undefined` value and does nothing. The response to your `$.getJSON` request contains a `display`property which seems to be the **rendered** results from the view. Again, I don't thing that the data your are looking for and you need something to get the results as structured JSON data.

---
Tags: views
---


title: Create a menu item with arguments

text:
# Question
Title: Create a menu item with arguments
I am trying to manually create a menu link item in the User Menu that contains a wildcard, But I cant make it work. I can get it to work if I have a static path, but I cant get it to work with wildcards args

```
function hook_menu() {
  $items['user/%user/bookmarks'] = array(
    'title' => 'My Bookmarks',
    'description' => 'Link to My Bookmarks',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'user-menu'
  );

  return $items;
}

```

# Answer
When I tried to use user wildcards first, I too came across this problem; and after some trial and error, found that the `%user` wildcard doesn't work with the menu type MENU\_NORMAL\_ITEM, instead it works if the type is MENU\_LOCAL\_TASK.

So, the code should be:

```
function hook_menu() {
  $items['user/%user/bookmarks'] = array(
    'title' => 'My Bookmarks',
    'description' => 'Link to My Bookmarks',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_LOCAL_TASK,
    'menu_name' => 'user-menu'
  );

  return $items;
}

```

Usually, this menu type is rendered as a tab in user menu.

I didn't get enough time to figure out why it doesn't work with MENU\_LOCAL\_TASK, but when I do find the reason, I'll post it back.
> 1 votes

# Answer
You forgot to define the page callback for that menu item, which means Drupal will use the one for the parent menu item, as reported in the hook\_menu() documentation.

> **"page callback"**: The function to call to display a web page when the user visits the path. If omitted, the parent menu item's callback will be used instead.

As the parent menu item for user/%user/bookmarks is user/%user, this means that, instead of showing the page you want, Drupal is showing the user profile page.

As you are creating a menu item for a view, there is normally no need to implement `hook_menu()`, as a view can be associated with a menu item.

If you need to show the view using more than one menu item, just clone the page, and change the path for the cloned page. With two pages, you will be able to use two menu items; with three pages, you will be able to use three menu items.
> 1 votes

---
Tags: 7, routes
---


# Question
Title: Will image styles be applied when they do not logically apply?
I have a set of biography images in the site I'm working on, and I have an image style that will enforce the correct size for these. Of course I'd rather not have them resized if they don't need it, so I'm wondering if the resize & crop effect will be skipped if the image is already the perfect size.

In other words, if the image is 130 x 170, and the effect of the image style would be to resize & crop it to make it 130 x 170, will the Image module be clever enough to skip that effect and leave it alone (so as not to degrade quality)?

If it will process the image anyway, then obviously I'll want to simply display the original image. It would be very useful if the module were clever enough to know when not to run, so the image style could be there as a failsafe in case some future content editor is too lazy to crop the images beforehand.

# Answer
> 1 votes
It is all up to the PHP toolkit used to manipulate images. The code that is executed from the image effect is the following one. (See image\_scale\_and\_crop\_effect().)

```
function image_scale_and_crop(stdClass $image, $width, $height) {
  $scale = max($width / $image->info['width'], $height / $image->info['height']);
  $x = ($image->info['width'] * $scale - $width) / 2;
  $y = ($image->info['height'] * $scale - $height) / 2;

  if (image_resize($image, $image->info['width'] * $scale, $image->info['height'] * $scale)) {
    return image_crop($image, $x, $y, $width, $height);
  }
  return FALSE;
}

```

The IF-statement is only used because image\_resize() can return `FALSE` if the PHP image toolkit doesn't support the operation being executed on the image. The function called from `image_size()` (image\_toolkit\_invoke()) is generic, and it doesn't make assumptions about the operations currently enabled from the selected image toolkit.

---
Tags: 7, media
---


title: Using theme regions from .tpl.php file

text:
# Question
Title: Using theme regions from .tpl.php file
I have defined many regions in my theme template. I would like to have a home page that uses these regions ... how can i use them? I have made a home.tpl.php but i don't know how to assign code to regions ... is it possible to do it even outside the page.tpl.php?

# Answer
> 1 votes
If you define a region you would normally then do the following in your **page.tpl.php** file...

```
<?php if ($YOUR_REGION): ?>
    <?php print $YOUR_REGION; ?>
<?php endif; ?>

```

You should have some similar examples setup already especially if you are using a theme that ships with Drupal.

You can create specific page templates...

```
function YOURTHEME_preprocess_page(&$variables) {
  if (arg(0) == 'my_page') {
    $variables['template_file'] = 'page-my_page';
  }
}

```

**Template suggestions**

See: http://drupal.org/node/1089642

**Context module**

Also, the Context module is brilliant for this sort of thing if you intend on having different regions for different pages you can use Context layout.

http://drupal.org/project/context

---
Tags: 6, theming
---


# Question
Title: Relation and Entity Share a Field / Reference Each Other
I can't seem to get this to work. I've searched and search, and maybe I'm not using the correct terminology, but I need to add a custom field to a Relation that reads a value from the Entity its related to. Or another way to put this, I need a field from the Relation to update a field in an Entity when the Relation is updated. Example:

Entity -\> Worker
Relation -\> Employed At
Entity -\> Company

I want to update my custom field "classification" through the Employed At Relation and then see that change reflected in the "classification" custom field in my Worker Entity.

# Answer
> 0 votes
If you are talking about the Relation module, then you can use Rules to trigger entity updates whenever a relationship (which is also an entity) changes.

The workflow would be like this :

1. Trigger on entity update.
2. Check that entity is a relation.
3. Update linked entity.

Check the video documentation on Relation, there are two (, ) of them talking about Rules.

---
Tags: 7, entities
---


# Question
Title: Taxonomy Term Block View Show Nodes For All Terms in Node?
Hello i achived this once but for some reason i am having a problem with it this time.

Using D6 and Views 3. I have a block view for random videos.

* Taxonomy Term ID from URL
* Load default argument from node page,
* Validator: taxonomy term
* Argument Type - Term id's by , or +

Iv checked and unchecked both-

Allow multiple terms per argument

and

Allow multiple arguments to work together

without much success. The desired output would be on a node tagged with 'science' and 'spirituality' the block view would show nodes that are either tagged 'science' or 'spirituality'. At the moment i seem to be getting no results or only nodes tagged with both 'science + spirituality'.

Does anyone know the correct settings for me to show nodes with any of the node's tags?

Thanks

# Answer
> 1 votes
I am not sure for d6, but in d7 you can do it like this(i believe it can be done same way in d6)

In Contextual filters(your Arguments) you need to add `Nid` like you did, after add new argument `has taxonomy term ID` and in `WHEN THE FILTER VALUE IS NOT AVAILABLE` -\> provide default value chose not `content from URL` but `PHP code` and do this:

You need to load node and get your taxonomy terms from field.

```
 $node = node_load(arg(1));
  if($node) {
  $field = field_get_items('node', $node, 'field_YOURFIELDNAME');
  if($field) {
      foreach($node->field_YOURFIELDNAME[LANGUAGE_NONE] as $term) { $terms[] =  $term['tid'];          }
    return implode('+',$terms);
  }
}
  else { return; }

```

it will return tids of selected taxonomy terms. But its a d7 way with Views 3.

---
Tags: 6, views
---


# Question
Title: Running a customized cron task very often
I have a custom cron task that needs to be run every ten minutes. The task connects to remote servers to retrieve some data and update the drupal db.

In order to achieve that I have to execute drupal cron **at least** every 10 minutes (I do it via `crontab` on a GNU/Linux system), so my questions are :

* Is it overkill to run drupal cron so frequently ?
* What are the main tasks that drupal cron is executing ?
* I understand that every task run within cron must check the last time it was executed so it is not run too frequently, is it generally understood this way ?

# Answer
> 8 votes
> Is it overkill to run drupal cron so frequently ?

The answer to that is...it depends. If your cron task needs to run every 10 minutes, then no, it's not overkill. If it doesn't, then it is overkill. What you probably need is something like Elysia Cron, which lets you schedule cron jobs for specific modules on a an individual basis. That way you can run your custom labour-intense function as often as you need to without invoking the rest of the system's cron hooks.

> What are the main tasks that drupal cron is executing ?

There's a list of core hooks that will be invoked on a cron run here, I don't think listing each one of those here would be prudent (there are 16 of them) - suffice say to say quite a lot happens; the caches are flushed which is probably a point of interest.

Bear in mind that many contrib modules also implement `hook_cron()`, so if you want an exhaustive list of functions that are invoked on cron you'll need to go through those files manually.

> I understand that every task run within cron must check the last time it was executed so it is not run too frequently,

The *must* part of that is not true, there's no 'rule' for whether a task run on cron needs to check its last run time. There are plenty of situations where such a mechanism would be advantageous, but you absolutely don't *need* to do it. Again it depends on what each task is actually doing.

---
Tags: 7, cron
---


# Question
Title: Profile2_path form_alter - Anonymous user form - access denied problem
I have created a custom profile type and given it a unique registration path using profile2 registration path. I am attempting to form alter the custom fields but I cant seem to find a way to view the from as admin in order to view the form array.

Whenever I go to the custom path of offers/register as admin I get an 'access denied'. How can I view this form that is for anonymous users whilst logged in as admin so that I can kpr($form);?

Thanks in advanced.

# Answer
> 1 votes
I set devel module permissions of 'Access developer information' to anonymous user . Make sure to disable this module on a production site.

---
Tags: users, uri
---


# Question
Title: Redirect on node form submit with custom module - hook_form_alter
I have Druapl 6 with orgranic groups installed. I need a thing - when a group user creates "group" content after node form submission he must be redirected back on group homepage instead of node view page.

```
function heihachi_form_alter(&$form, $form_state, $form_id) {
  switch($form_id) {
        case 'group_wall_node_form':
        unset($form['buttons']['preview']);

        $redirect = 'node/' . $form['og_initial_groups']['#value'][0];
        $form_state['redirect'][0] = $redirect;
        //dpm($form);
        break;
  }
}

```

but that code doesn't redirect at all. Using simple $form\['#redirect'\] works, but it affects Node delete button aswell, so i can't delete my node because it redirects on a custom path. Thanks for all advices in advance.

**My new code (not working also):**

```
function heihachi_form_alter(&$form, $form_state, $form_id) {
  switch($form_id) {
        case 'group_wall_node_form':
        unset($form['buttons']['preview']);
        $form['#submit'][] = 'custom_redirect';
        //dpm($form);
        break;
  }
}

function custom_redirect($form, &$form_state) {

  //unset($_REQUEST['destination']);
  //unset($form['#redirect']);

  $form_state['rebuild'] = TRUE;

  $redirect = 'node/' . $form['og_initial_groups']['#value'][0];
  $form_state['redirect'] = $redirect;
}

```

**This is what i see in $form variable:**

0 (String, 21 characters ) menu\_node\_form\_submit | (Callback) menu\_node\_form\_submit();

1 (String, 31 characters ) auto\_nodetitle\_node\_form\_submit | (Callback) auto\_nodetitle\_node\_form\_submit();

2 (String, 15 characters ) custom\_redirect | (Callback) custom\_redirect();

I guess something wrong is there?

**SOLVED!**

used hook\_nodeapi as one guy told me below:

```
function heihachi_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  if ($node->type == 'group_wall') {
    if ($op == 'insert') {
      $_REQUEST['destination'] = 'xxx';
    }
  }

```

# Answer
> 2 votes
use `hook_nodeapi` with op `insert` or add another submit function in `hook_form_alter`.

---
Tags: redirection, forms
---


# Question
Title: How do I add a subtitle for menu items in Nice menu?
I'm using the *Nice menu* module. I need to show a subtitle for each menu item.

How can this be done?

# Answer
Try OM Maximenu module

> "Maximize your main navigation by adding text, images, videos, slideshow, tabs, menu blocks, user info ..."
>
> That is now possible by using OM Maximenu which can create menus with all other module blocks you want as attachments, modules like views, slideshow, menu, user, nice menus, quicktabs, and custom blocks with tables, lists, images, videos, etc.

Here a great list of menu 7 Mega Menu modules for Drupal
> 0 votes

---
Tags: 7, navigation
---


title: Create a pager for views output

text:
# Question
Title: Create a pager for views output
How can I make a pager for views output to limit them at 10 entries?

```
$view = views_get_view('myview', 'default');
$view->override_path = $_GET['q'];
$view_output = $view->execute_display('page_1', array($tid));

```

# Answer
Drupal Views module provides this functionality. You don't need to write the code for that. See the image below Here you can set item to display as want. It has many more options
> 0 votes

---
Tags: views
---


title: Featured listing

text:
# Question
Title: Featured listing
How can we create featured contents in drupal 7 for a specific content type?

I have a content type called "Properties" with various fields to add real estate properties.I added a number of properties in this content type.

In the home page of the website, i have a region to show "Featured Properties". In this region i need to show 3 properties.\[ an image and the title of each node,which is set as featured\].

My question is :

1. How can i set some nodes in a specific content type as featured from admin side?
2. How can we show that featured contents at the user side as blocks or any other way?

# Answer
> 1 votes
You can achive this in different ways. I think the best way for you will be next:

Add additional field to your content type `Properties` -\> for example `featured` interger value. Next you will need to install Views module, this module is really strong and awesome, you can display any content you want in block or any aother way.

Then go to `Structure` -\> `Views` -\> `Add new view` , and create new view, chose `Create a block` instead of creating page, set title and description, `Display format` \- chose what you need or prefer( i suggest to use unformatted list) of `fields` \- \> *Save and continue*.

Next you will need to add `FIELDS` you want to display, click `add` and chose -\> `Content: Image` and `Content: Title` there are different settings for this fields(uncheck Create a label). Next click on `ADVANCED` and click add a `Contextual filter` and chose your field you have created for your node - `Content: featured` (or any other name you have chosen when created your field in node). Click on it and in `WHEN THE FILTER VALUE IS NOT AVAILABLE` \- and in `Provide default value` chose `fixed value` and set it `1,2,3` comma separated.

Save and your view is done, now go to `Structure` -\> `blocks` and add your view to your region you need.

In your nodes which you want to display in field `featured` add `1` to - display first `2` second, `3` to display third. Now you can manage what nodes to display as featured.

Oh i forgot, in your view `SORT CRITERIA` \- chose `Content: featured`.

Also you can do this with Flag module, but i don't have much time right now to explain.

Good luck.

---
Tags: 7, nodes
---


title: Hook_theme in module not working

text:
# Question
Title: Hook_theme in module not working
I have a ctools plugin in a module folder. I have a theme call in the .module file:

```
function vimn_article_theme($existing, $type, $theme, $path) {
  dpm($path);
  return array(
      'vimn_article_template' => array(
      'template' => 'vimn_article_template',
      'path' => $path . '/templates',
      'variables' => array('title' => NULL),
    ),
  );
}

```

and then in the template file vimn\_article\_template.tpl.php

```
<div class="test"><div class="test" <?php print $title; ?>></div></div>

```

What am I missing here to get this to work?

The module name is vimn\_article My ctools plugin in is plugins/content\_types/prevnext.inc my template file is located in vimn\_article/templates

# Answer
Your only defining the function, your not calling it.

```
   print theme('vimn_article_template', $vars);

```

Think you also have to implement hook\_theme\_registry\_alter() for Drupal to pick up your template.

Maybe you can use a process function to assign this to a variable for the template.

```
function YOURMODULE_preprocess_HOOK($variables) {
   $output = theme('vimn_article_template', $vars);
   // etc, etc...
}

```
> 2 votes

---
Tags: 7, theming
---


# Question
Title: How to know where to place a block in the body of my page
I am new to drupal7 and I am trying to create blocks and new content on the body in drupal7 using css and php. Can you help with directions please. Thank you

# Answer
> 1 votes
If you're new to Drupal 7, I also encourage you to look into placing your blocks using the Context module, rather then hard-coding their location through theming or something like that. It's also more flexible than what you can just do through the block admin interface.

Here's a simple example of using the Context module to place a block in a certain location on a single page or a specific content type:

1. Once you've downloaded and enabled the module, go to admin/structure/context
2. Click the "Add" link to add a new context
3. Fill in the first few fields as shown below (name, tag, conditions to be met to fire this context)

4. Before saving, in the "Reactions" section, select **which blocks** you want displayed and **WHERE** when the conditions above are met

# Answer
> 0 votes
Content you can create from your Content types in admin menu, basic content types are like `Article` or `Basic page`. Here you can read about how to add content. If you need block with just static view you can easy create it in admin menu `Structure -> Blocks -> add block`, also you can create custum blocks, you need to write module, or create blocks with Drupal Views Module. How to create blocks read here.

In admin menu `Structure -> Blocks` you can chose region where to place your block on your page, also you can add your own regions on the page. Here are example of how to create new region on the page.

---
Tags: theming, blocks
---


# Question
Title: How to programmatically render a node's teaser using the theme layer?
How do I programmatically render a node's teaser using the theme layer?

# Answer
`node_view()` is the standard function for rendering nodes, e.g.

```
$node = node_load(1);
$view = node_view($node, 'teaser');
$rendered = drupal_render($view);

```

There is a `node` theme defined by the node module (in `node_theme()`) but I've never actually seen it used.
> 20 votes

---
Tags: 7, theming, nodes
---


# Question
Title: What is a good module that allows maintainers of nodes?
Im on D7. I have nodes on my site that represent businesses. I want the business owners to be able to edit info about their business even if they didn't create it and I want multiple people to be do so. It would be nice if I could assign a user to a business giving them per node permissions. Any suggestions? thanks.

# Answer
> 2 votes
I have used Node Access Node Reference for this. You will need to install Entity Reference and create a multi-value entity reference field linking to users you want to be able to maintain your node.

---
Tags: nodes, users
---


# Question
Title: Display fields from a view in node template
I'm learning views in drupal 7 and I just created an unformatted list view that is displaying the titles of a few nodes. The preview looks great and so does the view page.

I have a div block in a custom node template that I want now to view this "view" in. **What code do I need to put into my node template to access the view function?**

I looked at the system view template (views-view.tpl.php) that is generating what I want and I see that there is a $rows variable:

```
<?php if ($rows): ?>
  <div class="view-content">
    <?php print $rows; ?>
  </div>

```

But when I place that into my node template it doesnt work (probably because I need a preproccess?).

Am I going about this the wrong way? Is there an easier way to get views into another template file? I considered using a block. But I thought that once I nail this, then I don't have to mess with blocks.

FYI: I saw this post but I am not sure where to put the code that he recommended.

Thanks! I really appreciate it.

# Answer
Drupal 6

```
  $view = views_get_view('view-name');
  print views_build_view('embed', $view);

```

Drupal 7

```
<?php echo views_embed_view('view-name', $display_id = 'display-name') ?>

```
> 2 votes

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


# Question
Title: Using Entity Field Queries with "does not contain"?
I have an EFQ that selects all nodes with titles not equal to 'panda'.

```
$query = new EntityFieldQuery;

$results = $query
 ->entityCondition('entity_type', 'node')
 -> propertyCondition('title', 'panda', '!=')
 ->execute();

```

How would I go about changing this query to give me only nodes whose titles don't contain the word 'panda' at all?

# Answer
The comments on the official documentation page for propertycondition() give an example using sql `like` on propertycondition().

From that example try the following change to your code:

```
   -> propertyCondition('title', '%panda%', 'NOT LIKE')

```

**EDIT:** I haven't actually tried this, just going offa docs and comments.
> 1 votes

---
Tags: database
---


# Question
Title: Im trying to pass an array as an argument in a page callback
I am attempting to pass an array as a page argument in a page callback in one of my modules. The scenario is this: The user selects some photo prints and I'm trying to add all the selected photo prints to the cart. So I'm trying to pass an array through a url to use it in a function. And the photo prints can be from different photo albums. There is code to do it if all the photos are from the same album so Im currently perusing that as well. This is code I "inherited" by the way.

The URL looks like /add\_selected\_prints\_to\_cart/Array. As you can see, instead of an array of values, it's just Array.

This is the page callback:

```
// Add the selected prints to the cart.
$items['add_selected_prints_to_cart/%'] = array(
  'page callback' => 'add_selected_prints_cart',
  'page arguments' => array(1),
  'access callback' => TRUE,
  'access arguments' => array('view own gallery'),
  'type' => MENU_CALLBACK
);

```

Like I said, I am just trying to figure out how to pass the array. Once I figure out that, the other part is easy.

Maybe there is an easier way to do this.

# Answer
> 1 votes
That happens because the code you are using is similar to the following one.

```
$url = url('add_selected_prints_to_cart/' . $array);

```

If each photo has an ID that can be used to univocally identify each photo, in the same way a node ID univocally identify a node, you could use code similar to the following to create the URL. I assume the structure of the `$photos` array is the following one.

```
array(
  'photo ID 1' => array( /* data for the photo with ID equal to 1 */),
  'photo ID 2' => array( /* data for the photo with ID equal to 2 */),
  'photo ID 3' => array( /* data for the photo with ID equal to 3 */),
  // ...
);

```

```
$url = url('add_selected_prints_to_cart/' . implode(',', array_keys($photos)));

```

In this case, `add_selected_prints_cart()` can get the photo IDs using code similar to the following one.

```
function add_selected_prints_cart($photos) {
  $photo_ids = explode(',', $photos);

  // Load the photos from the database.
}

```

If you need to pass the array to the menu callback, I would add the array to the session variables. In this way the code would for defining the menu callback would be similar to the following one.

```
function mymodule_menu() {
  $items['mymodule_add_selected_prints_to_cart'] = array(
    'page callback' => 'add_selected_prints_cart',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

  return $items;
}

function mymodule_add_selected_prints_to_cart() {
  $photos = $_SESSION['mymodule_selected_photos'];
  // ...
}

```

(If you use `'access callback' => TRUE`, the access arguments are not used.)

Otherwise, the code to convert an array to a string is similar to the following one.

```
$string = strtr(base64_encode(serialize($array)), array('+' => '-', '/' => '_', '=' => ''));

```

The code to obtain the array back from `$string` is the following one.

```
$array = unserialize(base64_decode(strtr($string, array('-' => '+', '_' => '/'))));

```

Bear in mind there is a limit for the URL length accepted from browsers.

---
Tags: uri, 7, views, routes
---


# Question
Title: Is there an alternative to the Node reference, and the Feeds modules?
I am using Drupal 7, Reference Module (references-7.x-2.x-dev), and Feeds Module (feeds-7.x-2.x-dev).

I created 2 Content Types: Address Book, and City. The Address Book content type has a node reference to nodes of the City content type; the CSV file is imported to "City" content type with success using Feeds Module.

I am unable to import to a node reference using the Feeds module. With it, I created an importer, and mapped 2 fields for AddressBook content type:

* Name: Target is Title
* City: Target is NodeID

The CSV file looks like the following:

> Name,City
> COK,1230

Executing this import gives me unfavorable results, where the City field does not get populated.

Is there an alternative module that may be used or another method that may be recommended?

Please advise where further clarification is needed.

# Answer
> 4 votes
There is a patch in the works that adds Feeds support for Entity reference fields.

References will most likely be deprecated in favour of Entity Reference in the near future, so this is a good option once it gets finalized.

# Answer
> 2 votes
I went out searching for something to support this functionality today. First I found the patch noted in the other answer, but I also found the feeds\_entityreference module, which I decided to try. I've got some building to do, but my first attempts at importing entity reference fields have been successful.

---
Tags: nodes, feeds, importing-exporting
---


# Question
Title: How to remove the Day field from a Date?
I want to remove the *day* field from a Date dropdown of a webform. How to do that? I tried with `hook_form_alter()` without success. Any suggestions? Thanks

# Answer
There seems to be no coding-free way to achieve this but to create a separate Number-type field for year and month.
> 2 votes

---
Tags: webforms, datetime
---


# Question
Title: How do I avoid the text on my site is selectable?
I am wondering how to avoid the text on a Drupal 6 site is selectable, ideally only for certain node types.

It should help to make life a bit harder for content thieves. Apparently there is a module in Wordpress that does exactly this, but I could not find such thing for Drupal.

# Answer
Try adding this code into your template.php file

```
/**
 * Implementation of hook_preprocess_page().
 */
function <THEMENAME>_preprocess_page(&$vars){

    drupal_add_js("(function($){
        $.fn.disableSelection = function() {
            return this
                     .attr('unselectable', 'on')
                     .css('user-select', 'none')
                     .on('selectstart', false);
        };
    })(jQuery);", 'inline');
}

```

You can try css methods also

```
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

```

A JavaScript solution for IE is

```
onselectstart="return false;"

```

See 826782
> 4 votes

---
Tags: 7
---


# Question
Title: How to make a block visible on a particular page and as well as on taxonomy term page?
here is my situation,

I have a Taxonomy menu block built using taxonomy\_menu and taxonomy\_menu\_trails module. And I have used block\_term module to display the menu on nodes with given term(s).

Now, how can I display the same taxonomy menu block on taxonomy term pages as well?

I tried adding the taxonomy term page link to display block only the listed pages. but it did not work. while doing this I had both the conditions (Display on nodes that are taged to terms and Show only on listed pages) checked.

# Answer
> 0 votes
Finally this issue is solved using the Context module with Omega theme. (Without need of editing template files)

Step 1: As i mentioned in the question use taxonomy\_menu and taxonomy\_menu\_trails module with block\_term module to display the menu on nodes with given term(s). \[Now the blocks are displayed only on the nodes tagged to particular term(s)\]

Step 2: Using Context add a new context

Step 3: Add a condition as: Taxonomy Term, and select the respective terms where you need the taxonomy block to be displayed.

Step 4: Add a Reaction \> Blocks

Step 5: On the right hand side list of blocks are displayed with check boxes. Select the block that you need to show

Step 6: in the middle column all the regions are listed with a \[+Add\] button. Click on \[+Add\] button and save the context.

Therefor, now the block(s) is displayed on nodes as well as on the taxonomy term pages too.

# Answer
> 1 votes
Well from what I understood from your question, you can use following lines of code in your template file where you want to display the block:

```
if(arg(0) == 'taxonomy' && arg(1) == 'term') {
  $tid = (int)arg(2);
  $term = taxonomy_term_load($tid);
  $taxo_term = $term->vocabulary_machine_name;

  if ($taxo_term == "your_vocabulary_name") {
    print render($page['your_block_region']);
  }
}

```

PS: I dont know if this is very standard(drupal) way to achieve this but it has worked for me.

---
Tags: taxonomy-terms, blocks
---