title: unable to delete a custom content type

text:
# Question
Title: unable to delete a custom content type
I just followed http://www.andypangus.com/drupal-7-adding-roles-to-users-dynamically to create a new content type. I am successfully able to create it, but when I uninstall the module, the content type is not getting deleted. I also cannot delete it from the admin interface; there is no delete option.

Why cannot I remove the content type? How should I remove it?

# Answer
Make sure you actually *uninstall* the module as opposed to just disabling it.

Uninstall is an additional tab on Admin \> Modules page.

If that doesn't work, you could try calling node\_type\_delete($type) from somewhere.
> 1 votes

# Answer
There is an "Uninstall" tab in the admin interface for modules. Locate it and look under it. After you've disabled the module, the module will show up in the table of disabled modules in this "Uninstall" admin interface. There will be a small tick-box to the left of the name of the module. To delete the custom content type, you need to tick this box, and then press the "Uninstall" button located below this table.

There is no "Delete" option in the admin panel. However, pressing the "Uninstall" button runs the uninstall hook, which is what deletes the custom content type created by the module.
> 0 votes

---
Tags: nodes
---


# Question
Title: How to display term images instead of term names in the term selection process?
I have a content type with a term reference field (check boxes widget, vocabulary: Category) from which every user has to choose one term to be attached to his node.

I have also added an image field to the Category vocabulary to attach a default image to each term.

How can i display the term images and the term names instead of only the term names in the term selection process when creating the node? Is there a module out there?

Or maybe using hook form alter. Any guidelines?

# Answer
Ok so after doing some research i found the Entity Reference View Widget being a very cool module to achieve this. Basically with this module you can use a view to select items (imagine that!).

For my purpose i had to patch the module in order to have fields (instead of only rendered entities) as the view's format to show. The fields i used in my view were the term image, the term name and the Entity Reference View Widget Checkbox field (coming from the patch). The patch has an extra feature which lets you choose radios instead of checkboxes if someone wants to restrict the selection to 1.

After building the view you can manage the display of your selection through the "Manage Display" process of the fields of your content type like any other field.

I think this module has great potential. Try it out.
> 1 votes

# Answer
Looks like the Taxonomy Term Reference Tree Widget module gives you the ability to add images to term references. Here is a quote about it (from the module's project page):

> ... provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.
> 1 votes

---
Tags: 7, taxonomy-terms, media, entities
---


# Question
Title: Theme select field with ul li in register form
I have a field in account settings named 'field\_country' which is a select list.

I have defined it as an ajax field in template.php

```
$form['field_country'] = array(
  '#type' => 'select',
  '#options' => $countries,
  '#ajax' => array(
    'callback' => 'change_country',
    'wrapper' => 'city',
  ),
);

```

Then when you change the value it calls correctly 'change\_country' with ajax and works perfectly.

My problem is that I want is to change this select/option input by an ul/li list, and call ajax method like its original version.

# Answer
> 0 votes
I think you have to try using a widget that looks and acts like a select list, but is made HTML list & Javascript.

---
Tags: entities, theming, users
---


# Question
Title: How can I e-mail the content of a view to myself with Rules?
I'm using Drupal 7, Views 3.5, and Rules 2.2. I have a view that provides a page accessible only to admin users on my site, and once a week I would like to e-mail the content of that page to myself.

I know how to use Rules Scheduler to set this action up to occur weekly. What I don't know is how to get the page provided by the view as a value that can be input into the body of the e-mail sent via Rules.

If it was a node, I could use `Fetch entity` to pull it in by ID, but since it's provided by a view, there is no such ID (that I know of) to speak of...

# Answer
You can use php code in the body of emails sent using Rules, so ultimately anything can be included. The easiest method, however, would be to use the Insert View module.
> 2 votes

---
Tags: views, rules
---


# Question
Title: Disable comments in nodes specific taxonomy terms are attached to
I know it is really easy to disable comments if your content is organized by content type, but what if it is organized by taxonomy, is it possible to disable comments on all nodes with, say, the term 'news' attached to them? If so, how?

# Answer
> 3 votes
For anyone not already a seasoned Rules user, here are detailed steps / a worked example for @Wheelz's approach.

This answer shows you how to enable comments when a specific taxonomy term is present and to disable them when that taxonomy term is absent. As per @Wheelz's answer it requires the Rules module. These steps have been tested against 7.x-2.2.

1. Create a new Rule called, e.g. 'Enable comments when tagged blog'
2. Add an event of the `Before saving content` type (use the 'React on event' dropdown and under the subdivision *Node*, select `Before saving content`). Save.
3. Add a condition to test for the presence of the taxonomy field that will control whether comments are allowed.

* Add a condition of the `Entity has field` type (use the 'Select the *condition* to add' dropdown and under the subdivision *Entities*, select `Entity has field`)
    * Select `node (saved content)` from the 'Data selector' dropdown. (Or type `node` into the 'Data selector' field.) (Don't be tempted by the `node:... (saved content)` option. It's not what is needed here.) *This specifies the type of entity for which you want to check for the presence of a field. In this case we want to check for nodes.*
    * Select the field to check for. The dropdown will give you a list of machine names (lower case and with underscores), e.g a field labelled 'Tags' might have the machine name `field_tags`. (If necessary look up the machine name for the relevant field in your the 'Manage Fields' tab of the relevant content type(s).)
    * Save
4. Add a condition to test for the taxonomy term that will **enable** comments.

* If your taxonomy field can only have one value, then select a condition of the `Data comparison` type. Otherwise select a condition of the `List contains item` type.
    * Select the field to test using the 'Data selector' drop down. This is a two step process. First select `node:... (saved content)`. When you do this, the dropdown items change. Select `node:<your field's machine name - but with dashes not underscores>`, e.g. `node:field-tags`. (Don't be tempted by `node:field-tags:... (Tags)` \- that's not what is needed here.)
    * Continue
    * If the next page isn't showing a 'Value' dropdown, click on the 'Switch to the direct input mode' button.
    * Use the 'Value' dropdown to select the taxonomy term for **enabling** comments, e.g. 'Blog'.
    * Save
5. Add an action that will enable comments

* Add an action of the 'Set a data value' type.
    * Use the 'Data selector' to select the comment mode, This is a two step process. First select `node:... (saved content)`. When you do this, the dropdown items change. Select `node:comment (Comments allowed)`. Alternatively, you can directly enter `node:comment` into the 'Data selector' field. *If you let you let your mouse hover over \`node:comment (Comments allowed)' entry in the dropdown you will see a helpful tip:* Whether comments are allowed on this node: 0 = no, 1 = closed (read only), 2 = open (read/write). *This helps with the next step.*
    * Continue
    * If the next page isn't showing a 'Value' field, click on the 'Switch to the direct input mode' button.
    * Enter `2` into the 'Value' field. This sets comments to 'Open (read/write)'.

The rule just created will switch on comments when the chosen taxonomy term is present. But if that taxonomy term is later removed the comments will still be open. To turn off comments when the taxonomy term is absent, first clone the rule just made and then make a couple of small tweaks.

1. From the main Rules configuration page, click the ‘clone’ link for the rule you have just created, e.g. 'Enable comments when tagged blog'
2. Change the name of the rule, e.g. to ‘Disable comments when not tagged blog’. Save changes.
3. Edit the ‘List contains item’ condition.

* Check the ‘Negate’ box. *If the original condition succeeded, i.e. evaluated as TRUE, when the Tags field included the term ‘Blog’, this modified condition will succeed only when the Tags field does not include that term.*
    * Save.
4. Edit the ‘Set a data value’ action. Replace the value `2` with `0`. Save.

This second rule switch off comments when the chosen taxonomy term is absent.

**Note:** if a 'List contains item' gives an `Error: The data type of the configured argument does not match the parameter's list requirement` error, then your term reference field is set to allow only one value. You will need to delete the `List contains item` condition and replace it with a `Data comparison` condition instead. In the complementary case where `Data comparison` condition is used when a `List contains item` condition is needed, errors will be generated when the rule is run and the rule will not work.

# Answer
> 2 votes
Use Rules to check if a piece of content has a term on 'before saving content' and if so disable comments?

You need to create an action set component to set the node:comment value to 0 then call that as the action in your rule.

# Answer
> 1 votes
I ended up copying comment-wrapper.tpl.php to the theme folder, wrapping everything in an if condition that checked for a `$skip_all` variable. Then, in `mytheme_preprocess_comment_wrapper`, I checked if $vars\['node'\] fit the conditions to hide the comments (`$node->type` was enough for me, but you can check `$node->taxonomy`). If it did, I set `$vars['skip_all'] = TRUE;`

---
Tags: taxonomy-terms, nodes, comments
---


# Question
Title: Using Views and Date module in Drupal 7 - Limiting Filter Options
I am creating an event calendar for a festival where user's can log into the site, click "Add new event" and create an event. I have 2 questions regarding dates.

1. When the user creates the event, rather than a standard date popup, I'd like for them to be able to choose a range of days (Thursday - Sunday) and a time, rather than the calendar popup or Day/month/year hour minute drop downs. Is there an easy way to limit this, of even prevent the user from selecting dates outside a certain range?
2. When showing the events list, I've created a table view. I'd like to allow the user to select which days to display using an exposed filter. If I choose "Event date" it only allows me to display a standard date field in the filter (Month Day Year). I want the user to be able to select "All, Thursday, Friday, Saturday or Sunday" instead. I was able to add "Day" as a field in the view, and group by the DAY, It just seems I'm not able to then filter by it.

I hope this makes some sort of logical sense. Thanks in advance for any help.

# Answer
> 0 votes
currently "date" module doesn't allow to satisfy this needs

I see two solutions for the first question:

1) Develop a custom module in order to create this type of interaction.

2) A quick and dirty alternative is to alter the dropdown content using JS, but a custom module would be miles better.

Sincerely I'll suggest the first one.

About the second question you could expose the day filter and populate it substituting the form filter with a custom one, for example hiding the original form filter with CSS (display:none) and adding some hand crafted links with the URL parameters on the views header area.

Good work!

---
Tags: views, datetime
---


# Question
Title: Fill in user reference from current user page while adding new content
I have a view with appointments displayed at the user profile page (using pages for this) that is specific to that user.

While adding a node (appointment type) I can select the user(user reference) that the appointment is made with.

Now, I would like to add a link at the bottom of that view so I can add a new appointment and at the same time pass in the user id/name of the current viewed user, so I don't have to manually select the user again.

Any suggestions?

# Answer
If you're using "Entity reference" module for the user reference field, you could use http://drupal.org/project/entityreference\_prepopulate module which allows to set the entity id with an URL parameter.

For example, if the field name is "field\_user\_reference", and the entity you're creating is "appointment", you'll have to generate a simple link like:

> node/add/article?field\_user\_reference=UID

Instead, if you're using "References" module, you can install and enable http://drupal.org/project/userreference\_url which does the same, although the syntax is a bit different:

> node/add/article?user\_reference=UID

I hope this will help.
> 1 votes

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


# Question
Title: How to override the user edit page using Panels?
I am trying to override the user edit page in Drupal7 using Panels. I checked the selection rule as user being edited are one of authenticated and administrator.

However, when I try to add a context to it and select the context User being edited, it asks me:

> Enter the name or UID of a node
>
> (A user edit form)

What do I write in here, any suggestions? Am I on the correct track or do I have to add any other context or relationship as well?

I also tried giving different path and ID but then I get some kind of ajax error.

Ps: Below is my screen shot, what do I enter in the first field?

# Answer
user\_edit panel default context is the current edited user. Why do you need to add an additional context with a user?

If you need to access to user values you can use the default context. For example you can use %user:uid in order to load the user ID which is being edited.
> 3 votes

---
Tags: 7, panels, users
---


# Question
Title: Searching for nodes from another site in a multisite installation
I am trying to have the search function of a www.site.com return also nodes from site.com/somethingelse. Is there any way I can achieve this?

I prefer not to use Solr.

# Answer
You could do that easy enough with Google Custom Search, e.g:

1. http://www.google.com/cse
2. http://drupal.org/project/google\_cse

Basically can search a range of selected sites from one interface, using the power of Google search.
> 2 votes

---
Tags: nodes, search, multi-sites
---


# Question
Title: How to make specific field disabled on node submit, but enabled on node edit?
In content type `testtype` I have 2 required field: `field_one` & `field_two`.

I need to make `field_one` only enabled on node submit, while `field_two` only enabled on node edit.

So, when submitting, we can only see `field_one`, and when editing, we can only see `field_two`

# Answer
you can solve this problem in different ways.

The first is quite easy: you can show/hide the fields from CSS.

When you create a node, the default body classes contain this CSS class: "page-node-add". Instead when you edit a node you'll have the class "page-node-edit".

So you can add this CSS code:

```
.page-node-add .field_two{ display:none }
.page-node-edit .field_one{ display:none }

```

This solution is not elegant and it could be a potential security hole.

A better solution is to implement hook\_form\_alter() from your theme or from a custom module.

The code could be something like:

```
function yourmodulename_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'testtype_node_form' && arg(1) == 'add' ) {
    $form['field_two']['#access'] = 0;
  }
  if ($form_id == 'testtype_node_form' && arg(2) == 'edit' ) {
    $form['field_one']['#access'] = 0;
  }
}

```

Good work!
> 2 votes

# Answer
I had almost the same situation today and field permission did the job perfectly.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Replacing field result with hook_views_pre_execute when replacing SQL query
I have a simple page view (unordered list) with just one field (content: path) and one contextual filter (nid). The view isn't displaying the right path if the language of the selected node is not the current site language.

For that reason i've decided to replace the query and try to get the aliased path of the selected node. I've used **hook\_views\_pre\_execute** and already replaced the query for this view. The query already shows up in the preview section in Views UI but the result is empty now. The query works in phpmyadmin.

I can't find much documentation about this hook. How to get my query to replace the views **Path** field and display the result instead?

This is my SQL Query:

```
SELECT ua.alias AS alias
FROM
{url_alias} ua
WHERE  (ua.source = 'node/247')
LIMIT 1 OFFSET 0

```

This is my function from my custom module:

```
function views_node_path_views_pre_execute(&$view) {
 if($view->name == "global" && $view->current_display == "node_path_page") {
  $myQuery = db_select('url_alias', 'ua')
  ->condition('ua.source', 'node/' . $view->argument['nid']->value[0], '=')
  ->fields('ua', array('alias'));
  $view->build_info['query'] = $myQuery;
 }
}

```

---

**EDIT:**

Just fixed it myself with **hook\_views\_post\_render** from views API. I know, it's just a dirty hack and i don't really like it but i need this part to be working.

```
function views_node_path_views_post_render(&$view, &$output, &$cache) {
 if($view->name == "global" && $view->current_display == "node_path_page") {
  $result = db_select('url_alias', 'ua')
   ->fields('ua', array('alias', 'language'))
   ->condition('ua.source', 'node/' . $view->argument['nid']->value[0], '=')
   ->execute()
   ->fetchAll(PDO::FETCH_NUM);
  if($result) $output = '/' . $result[0][1] . '/' . $result[0][0];
 }
}

```

# Answer
From your description, you are trying to display the aliased path of the current page using a view.If you are trying to encourage users to deep-link to your site, a PHP code snippet might be a better approach. (Drupal often encourages complex answers to simple requirements.)

Using aliased links means that the links may be broken if the alias changes (as with a change in the page title) unless the old aliases are retained. In that case, multiple aliases will exist for each page. Deep links should use the un-aliased url.
> 0 votes

---
Tags: views
---


# Question
Title: Using Adaptivetheme subtheme how to have fixed width left column?
How do I have a fixed width left column and fluid right? At the moment, in my panels config there is only the fluid layouts available e.g. AT Two column 33/66.

# Answer
From the AdaptiveTheme documentation:

Sidebar Units and Widths You can use any combination of units - meaning you can set a percentage width on the page and pixel widths on the sidebars. In some layouts you can only set the width on one sidebar because the second sidebar wraps below the main content and becomes a full width horizontal region - useful in smaller screen displays.

Example screenshot:

If you're using Panels, however, you're going to have to modify the CSS/theme code yourself. You can either make your own new layout (just look at the code-- AT is pretty well documented) or just override the part that is making the layout fluid. Note that doing this is almost certainly going to break the "responsiveness" of AT.
> 0 votes

---
Tags: theming
---


title: Turning on delay of superfish menu

text:
# Question
Title: Turning on delay of superfish menu
For some reason I cannot find the settings to turn on the delay for my superfish menu. I was able to get to it a couple of weeks, but not any more.

All I see when I go to /admin/config/user-interface/superfish is the ability to change the number of blocks and paths to superfish library.

How do I get to the settings where I can turn on delay?

# Answer
> 0 votes
The settings for the menu is on the same page as the menu block settings page. You'll find your menu block at `/admin/structure/block` where you click `configure` for your menu block, and you'll be able to change the settings.

---
Tags: navigation
---


# Question
Title: How add CVV's custom validation before order review in Ubercart
I'm developing a Gateway Payment module for Ubercart. It is necessary to validate that the User does not digit three ceros -000- (bank policy) before the order review form. I've seen that Ubercart does the CCV's validation in the uc\_credit.module

```
      if (variable_get('uc_credit_cvv_enabled', TRUE) && !_valid_cvv($cc_data['cc_cvv'])) {
        if (!$silent) {
          drupal_set_message(t('You have entered an invalid CVV number.'), 'error');
        }
      $return = FALSE;
      }

```

How could I add my validation without hacking Ubercart modules.

Thanks in advance.

# Answer
You can create a custom validation function in your module and name it whatever you like for example 'custom\_validation\_function'. and in the same module add this validation function to the form's validation list by using form\_alter.

```
function <module_name>_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == '<ubercart_form_id>') {
    $form['#validate'][] = 'custom_validation_function';
  }
}

```
> 0 votes

---
Tags: ubercart
---


# Question
Title: Breadcrumbs not showing properly translated
I am using a multilingual site with an Arabic and English versions. Before it was showing properly, but after the menu has been translated to Arabic, the breadcrumbs are showing only in Arabic.

How can I get the breadcrumbs in English too?

# Answer
> 1 votes
the first you must check the node type that is not translated then you write the code like this

```
function YOURTHEM_breadcrumb(&$variables) {
  $breadcrumb = $variables['breadcrumb'];
  $breadcrumb[] = drupal_get_title();
  if (!empty($breadcrumb)) {
    $node = node_load(arg(1));
    $type = $node->type;
    if ($type) {
      switch ($type) {
        case 'conventions_exhibitions_director':
          $breadcrumb['breadcrumb']= l(t('Conventions Exhibitions Directory'), 'conventions-exhibitions-directory');
          break;
         case 'event':
          $breadcrumb['breadcrumb']= l(t('Event'), 'event');
          break;
         case 'news':
          $breadcrumb['breadcrumb']= l(t('News'), 'news');
          break;

      }

    //var_dump($breadcrumb);
      if($type == 'webform'){
        array_pop($breadcrumb);
        if (arg(0)== 'node' && arg(1) == 263){
           $breadcrumb['breadcrumb'] = t('Attend an Event');
        }elseif (arg(0)== 'node' && arg(1) == 7) {
          $breadcrumb['breadcrumb'] = t('Contact Us');
        }elseif (arg(0)== 'node' && arg(1) == 263 && arg(2) == 'done') {
          $breadcrumb['breadcrumb'] = t('Attend an Event');
        }elseif (arg(0)== 'node' && arg(1) == 7 && arg(2) == 'done') {
          var_dump($breadcrumb);
          $breadcrumb['breadcrumb'] = t('Contact Us');
        }
        $output .= '' . implode(' > ', $breadcrumb) . '';
        return $output;

      }
  }
    $output .= '' . implode(' > ', $breadcrumb) . '';
    return $output;
  }
}

```

be careful to replace the 'YOURTHEM' to your current them name

---
Tags: 7, breadcrumbs
---


title: Titles on pages underneath the text

text:
# Question
Title: Titles on pages underneath the text
I must have checked or unchecked a button somewhere, sometime, because ever since I remember starting to work on my site the titles of the pages are showing underneath the articles / texts on the pages, instead of on top of them, like they should. (example: see link to screenshot) I tried the 'manage display' option but I the title isn't part of that with the basic pages.

Does anyone have an idea of how I could fix this? :) For I have no clue...

Screenshot: http://img89.imageshack.us/img89/2140/headerunder.png

(the tags I wanted to use were not available for me so I hope I tagged this right..)

# Answer
> 0 votes
well propably is a theme issue. if you encounter this on all pages check your page.tpl.php and make sure this

```
  <?php if ($title): ?>
    <h1 class="title" id="page-title">
      <?php print $title; ?>
    </h1>
  <?php endif; ?>
  <?php print render($title_suffix); ?>

```

is before

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

```

this is all i can say with the info provided.

# Answer
> 0 votes
The Display Suite Module offers you (among many many others) this functinality. With DS installed, you can rearrange your fields and more from every contenttype (and other entities) in your system. Very handy ...

---
Tags: 7
---


# Question
Title: add ajax form-like functionality inside node
I have an article on my Drupal site and need to add some calculations to it (to better illustrate a topic). It means, three textfield inputs and a button, after clicking the button a calculation should take place on server side (not in javascript, because I want this calculation to be in php on server side) and then comments should be displayed below the textfields.

The problem is, I would like to have all of it inside node, not below it - for better user experience.

Inserting input and submit button via wysiwyg works fine. Then, I need to use raw jquery ajax command and do everything manually - it should be possible.

So before doing this, I'd like to ask if there is a simpler way?

E.g. ajaxifying webform is documented. So, if the whole webform could be treated as one token, it could be inserted into wysiwyg using token filter inside node content. But webform as a token? - can't find such solution.

# Answer
> 1 votes
Build your webform, or Form api form, grab its ID and then follow my answer to insert this form into node's content through a custom module of yours

Cleaner way to do it.

---
Tags: 7, forms, ajax, tokens
---


# Question
Title: On View Rewrite Results I don't see additional options like Add Read More button when checked "Trim this field to a maximum length"
Can anyone help me? Because earlier this options were displayed when I checked "Trim this field to a maximum length". May be it depends on some settings?

I can't upload image to show you what I mean. But try to explain. I have a view block which displays some articles of the content type. I have some fields of content type to display. One of them is Body. I want to trim it because it can be very long and set "View more" link to the current article. I choose "Trim this field to a maximum length" in the "Rewrite Rules" of the field but nothing happens, additional options aren't shown to me, so I can't set number of characters to display, title of "View more" link, path and etc.

# Answer
My guess it is a Jquery incompatabilty. I had the same problem this morning while setting up a new site. After activating views there where no accordions and a faulty overlay.

So i set the Jquery-version in Jquery-Update Module from 1.8 to 1.5 and everything turned back to normal.

Edit: here's the issue queue on drupal.org: http://drupal.org/node/1869988
> 0 votes

---
Tags: views
---


title: bread crumb arg()

text:
# Question
Title: bread crumb arg()
I want to write code to translate the breadcrumb I use.

```
function MYTHEM_breadcrumb(&$variables) {
  $breadcrumb = $variables['breadcrumb'];
  $breadcrumb[] = drupal_get_title();
  if (!empty($breadcrumb)) {
    $node = node_load(arg(1));
    $type = $node->type;
    if ($type) {
      switch ($type) {
         case 'event':
          $breadcrumb['breadcrumb']= l(t('Event'), 'event');
          break;
         case 'news':
          $breadcrumb['breadcrumb']= l(t('News'), 'news');
          break;
/****This error from here*** */
         case 'webform':
         if (arg(0)== 'node' && arg(1) == 263 && arg(2) == 'done') {
             $breadcrumb['breadcrumb'] = t('Attend an Event');
            }
           $output .= '<div class="breadcrumb">' . implode(' > ', $breadcrumb) . '</div>';
           return $output;
         break;
      }
  }
    $output .= '<div class="breadcrumb">' . implode(' > ', $breadcrumb) . '</div>';
    return $output;
  }
}

```

It did not execute the `if (arg(0)== 'node' && arg(1) == 263 && arg(2) == 'done')` part. The URL I am accessing is MYURL/MYPROJECT/ar/node/7/done?sid=59.

Why doesn't it see the `arg(2)`?

# Answer
Although this code seems the wrong way to go, i would suggest checking for sid if this is the point anyway (meaning you only want the submitted url)...

```
if(isset($_GET['sid'])

```

or you could break down the $\_GET\['q'\] to explode your validator from the url

```
$url = $_GET['q'];
$fragment = explode('/', $url) and check for $fragment[3]=='done' or any fragment of the $url

```
> 1 votes

---
Tags: theming, webforms
---


# Question
Title: Drupal 7 skip node in hook after node save
In my custom module I am creating a node using node\_save. I have also implemented hook\_node\_update to catch a user updated node. But every time I call node\_save, it also calls my hook. Is there a way I can tell that this update was called using my node\_save. In Drupal 6, I used to add something like $node-\>skip\_it = TRUE in before node\_save, and this was available in the update hook. But not any more. Any pointers.

# Answer
> 1 votes
You can check using below condition while using node\_save

> If $node-\>nid is omitted (or $node-\>is\_new is TRUE), a new node will be added.

So, in your hook\_node\_update check for above condition before executing your code.

# Answer
> 0 votes
If all the user updates you need to catch happen via the node edit form, you could implement `hook_form_FORM_ID_alter()` and append your own submit handler which won't be called on `node_save()`. The downside is that you'll probably need to read any user modifications from `$form_state['values']`.

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

function mymodule_MY_CONTENT_submit($form, &$form_state) {
  // do stuff here
}

```

---
Tags: 7, nodes, hooks
---


# Question
Title: Rendering drupal login form in a modal window
I need to display the login form in a modal window when a user clicks a link on my website. I am doing that using jquery ui dialog currently.

However, once the user logs in, i don't want a page refresh instead i just want the modal window to get reloaded with some content.

how do i achieve this?

# Answer
> 2 votes
Modal forms module might help you.

> Modal forms make use of the modal feature in the ctools module to open some common forms in a modal window.
>
> **Supported forms:**
>
> * Log in (modal\_forms/nojs/login) Request new password
> * (modal\_forms/nojs/password) Create new account
> * (modal\_forms/nojs/register) Contact (modal\_forms/nojs/contact)
> * Comment (modal\_forms/%ctools\_js/comment/reply/%node) Webform
> (modal\_forms/%ctools\_js/webform/%node)

# Answer
> 0 votes
Use Lightbox module and mention rel in the url tag like below i mentioned

```
<a href="search.php" rel='lightframe'>Search</a>

```

you can see a live example in my site www.richtown.ae(click Mortage Calculator in bottom)

or you can use popup module to achieve this.

# Answer
> 0 votes
The Colorbox Module provides this functionallity.

---
Tags: users, javascript
---


# Question
Title: Views Summarize Won't Sum when field is output as link (D7)
I'm using Views Summarize module for one of my views. I need to output the field as link and sum them up, but the total is displayed as $0. When I uncheck the `output the field as link` option, the total is displayed correctly.

https://i.stack.imgur.com/SNK0h.png

Anyone has a solution for this?

# Answer
> 0 votes
I came up with my own solution to this problem. All you need to do is to modify the module file.

Within the `foreach ($data as $val)` add this right after

```
if (strpos($val, '</a>') !== false) {
  preg_match('/<a ?.*>(.*)<\/a>/', $val, $value);
  $val = $value[1];
}

```

# Answer
> 0 votes
Have you seen this issue on drupal.org: http://drupal.org/node/1880450?

It looks like this is actually a bug in the module - not anything you're doing wrong. However, there seems to be a user-submitted patch that fixes issues with decimals, currency, etc that you can try out...

---
Tags: views, entities
---


# Question
Title: When to use Views vs. a hardcoded query?
I recently took over maintainership of a little module called Suggested Terms and received a feature request to replace the build-in queries with views.

I'm trying to weigh the pros and cons of using Views vs. a built-in query, and I don't really know whether it's worth introducing a dependency on another module, what the performance impact will be, etc.

What guidelines determine when a situation is best suited to Views, vs. using custom queries?

# Answer
> 1 votes
As posted in the issue thread he's asking about caching, which Views can give you -- or as @Chapabu mentions one could cobble together yourself.

1 thing Views does give you is an ability to Alter query or presentation of results relatively easily with `hook_views_pre_execute` or `hook_views_query_alter` to tweak the standard module to make it more customizable.

I could see some merits going this route. You could also supply the default listing as a default View provided by the module. Allowing other modules to copy/override it later in code ...

# Answer
> 1 votes
I think that the best thing of integrating Views is that provides a *standard* and *easy* way to customize the query and look and feel of your query.

I'm not sure if this module is the right case for that (Will the users need to alter the view?), but you certainly can integrate Views in another optional submodule, called for example **Suggested Terms Views** (but with a better name). Depending on the usage of this new submodule, you could merge them in the future.

In my humble opinion, the Views dependency shouldn't be a problem nowadays, specially because I don't think there are many Drupal sites without Views, and at the same time with the need to use your module.

---
Tags: views, database
---


# Question
Title: How to provide ubercart discount coupons only for specific users
Anyone can say how to provide ubercart discount coupons only for applicable users and not for the other users ?. For example if a user from texas, then the admin can provide a coupon code only for that texas user and it should not applicable for other out of texas users . please reply ASAP if anyone knows . thanks.

# Answer
> 0 votes
What you are looking for is a custom hook\_uc\_validate\_coupon function. Ubercart coupon module allows for custom hooks here:

```
// Invoke validation hook.
  foreach (module_implements('uc_coupon_validate') as $module) {
    $callback = $module . '_uc_coupon_validate';
    $result = $callback($coupon, $order, $account);

```

So in your site module you would need to define a new hook function that validates whether the order (or possibly the user object?) is using a billing address from Texas. Roughly, clone the existing validation function and add logic to check the order for your conditions.

function YOURMODULE\_uc\_coupon\_validate($code, $order = NULL, $account = NULL) {

```
if ($order->billing_state != 'Texas') { // or however you want to handle this
   $coupon = new stdClass();
   $coupon->valid = FALSE;
   $coupon->message = t('This coupon code is only valid in Texas.');
   $coupon->title = t('Unknown');
   return $coupon;
}

.. rest of validation function

```

}

---
Tags: ubercart
---


# Question
Title: Views: displaying a field from a vocabulary based on the name
The following seems simple to me but i can't get it done in views:

A taxonomy vocabulary has two relevant fields: Name and Image. In the nodetype associated with this vocabulary i use Name as the linking field (i can not set the field up to directly use the image) but in the node view i want to show Image instead of Name. In my case Panels handles the display of my nodes. I turned to views and tried two alternatives with a taxonomyterm view and a content pane display:

1. Add both vocabulary fields and rewrite the output from the Name field to use the Image field. If i put the Image field first i can see a replacement pattern that seems to match the Image field, but the result is crap. I think a real link between the node and the tax-terms is missing;
2. I added a contextual filter with Taxonomy Term: Name but get stuck because the value is not in the URL. Everything i tried in options like "Provide default value" and "Specify Validation Criteria" fails. Also, using the Argument Input option in Pane Settings, picking Name from the node list under "from context" seems to do nothing. When i enter a valid Name value in Views Preview it returns the corresponding Image, exactly like i want. But someway that value isn't read when the view is run for real.

Any clues? Thanx in advance!

Kind regards, Cas

# Answer
If I understand question aright, you need to use a *Relationship* in your View.

* Under the Advanced section (just below contextual filters) click 'Add' to add a Relationship
* Select the field in your node for the relevant term reference, e.g. a field labelled 'Tags' and with a machine name 'field\_tags' would appear as `Content: Tags (field_tags)` in the list that is shown when you select 'Add'
* The default configuration should be fine for the use case at hand, so in the next dialog box it should be OK to simply select 'Apply'. (In some cases you do want to tick Require this relationship.)
* Go to Add fields and add a new field. Find the image field in your taxonomy. If the taxonomy is called Tags and the field labelled 'Image', it'll look like: `Taxonomy term: Image Appears in: taxonomy_term:tags.` Select this and click on 'Apply', Then click on 'Add and configure fields'
* When you are in the configure dialog you'll see an indication that a relationship is being used. It'll look something like this:

* Configure as required and apply. In your fields list it'll look something like this:

What these steps do is say that you want to use the field in the node that contains the taxonomy term to bridge to the fields in the particular taxonomy vocabulary item. Having added the relationship you can now add fields that call upon it. That, if I understand the question, is what is needed here. And, again, if I've understood aright, no need for contextual filters - at least not to get the image from the taxonomy into your view.

These steps apply to Views 7.x-3.5. (In pre 3.5 versions, or perhaps bit further back, the relationship set up was a bit more complex, but it's now more streamlined.)
> 0 votes

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


# Question
Title: I have a error in my batch api operations, and I don't find the solution
Hello I run this in a form\_submit function:

```
<?php
function generate_xls_form_submit($form, &$form_state) {

$data = array();
  $information = '';

  if($form_state['values']['SelectFormstackForm']){
    $data['FormstackForm'] = $form_state['values']['SelectFormstackForm'];
  }
  if($form_state['values']['FromDate']){
    $data['FromDate'] = $form_state['values']['FromDate'];
  }
  if($form_state['values']['ToDate']){
    $data['ToDate'] = $form_state['values']['ToDate'];
  }

  //if we don't have 3 options, que can not retrieve all we need.
  if(count($data) != 3){
    return NULL;
  }

  // we will retrieve all the nid to get them the lead field values.
  $IdList = submission_generate_xls_get_leads_id($data);

  //total de resultados encontrados.
  $cantidadIdList = count($IdList);

  // Get formstack form field labels from database.
  $labels = submission_generate_xls_get_fomrstack_field_labels($data['FormstackForm']);

  //cargamos la clase de PHPExcel.php
  require_once 'Classes/PHPExcel.php';

  date_default_timezone_set('Europe/London');
  // Create new PHPExcel object
  $objPHPExcel = new PHPExcel();

  // Set properties
  $objPHPExcel->getProperties()->setCreator("Captalis")
                 ->setLastModifiedBy("Captalis")
                 ->setTitle("Leads generados del formulario ." . $data['FormstackForm'])
                 ->setSubject("Leads")
                 ->setDescription("")
                 ->setKeywords("office 2007 openxml php")
                 ->setCategory("Customers");

  //montamos el encabezado
  $vocal = 'B';
  foreach ($labels as $key => $value) {
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($vocal . '3', $value);
    ++$vocal;
  }

  // Rename worksheet
  $objPHPExcel->getActiveSheet()->setTitle('Leads');

  //build batch operations.
  foreach ($IdList as $key => $value) {
    $operations[] = array('batch_generate_xls_row', array($value, $key, $cantidadIdList));
  }

  // configure a batch
  $batch = array(
      'title' => t('Build excell.'),
      'operations' => $operations,
      'init_message' => t('Batch is starting.'),
      'progress_message' => t('Batch is running...'),
      'error_message' => t('Batch has encountered an error.'),
      'finished' => 'submission_generate_xls_finished',
  );

  batch_set($batch);
}
?>

```

this is my batch functions:

```
/**
 *
 *
 */
function batch_generate_xls_row($value, $key, $cantidadIdList, &$context) {

  if (!isset($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_node'] = 0;
    $context['sandbox']['max'] = $cantidadIdList;
  }
  $values = submission_generate_xls_get_leads_values($value);

  $vocal = 'B';
  $integer = $key+4;
  foreach ($values as $key => $value) {
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($vocal . $integer, $value);
    ++$vocal;
  }

  $context['message'] = t('Loading node "@title"', array('@title' => $node->title)) . ' ' . $operation_details;

  $context['sandbox']['progress']++;
  $context['sandbox']['current_node'] = $value;
  $context['message'] = 'este es el procesamiento de ' . $value;
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {

    $context['finished'] =  $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

/**
 *
 *
 */

function submission_generate_xls_finished($success, $results, $operations) {
  if ($success) {
    // Here we could do something meaningful with the results.
    // We just display the number of nodes we processed...

    drupal_set_message(t('The excell is done'));
    drupal_set_message(t('The final result was "%final"', array('%final' => end($results))));

    // Set active sheet index to the first sheet, so Excel opens this as the first sheet
    $objPHPExcel->setActiveSheetIndex(0);

    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="01simple.xlsx"');
    header('Cache-Control: max-age=0');

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output');
    exit;

  }
  else {
    // An error occurred.
    // $operations contains the operations that remained unprocessed.
    $error_operation = reset($operations);
    drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array('@operation' => $error_operation[0], '@args' => print_r($error_operation[0], TRUE))));
  }
}

```

And this is the error watchdog give me:

```
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'batch_generate_xls_row' not found or invalid function name in _batch_process() (line 284 of /home/oscar/webapps/www/drupal/drupal7/includes/batch.inc).

```

Any help?

Thanks

Oskar

# Answer
I presume batch\_generate\_xls\_row is not defined in your .module file. In this case you need to specify the file in the batch definition:

```
<?php

$batch = array(
    ...
    'file' => drupal_get_path('module', 'mymodule') . '/pages.inc',
);
?>

```

See batch\_set() documentation for reference.
> 12 votes

---
Tags: 7, batch-operations
---


title: Move site from MySQL to MS SQL

text:
# Question
Title: Move site from MySQL to MS SQL
I've been trying to move an existing Drupal 7 site from a MySQL database to an MS SQL database. The tables and their contents has been successfully moved. I've seen some errors in datatypes and default values, but these has been manually altered.

The site is now working, well, almost working as it should. At the bottom of each page, I'm getting an error message stating:

```
PDOException: SQLSTATE[42000]: [Microsoft][SQL Server Native Client 10.0][SQL Server]The data types ntext and nvarchar are incompatible in the not equal to operator. in drupal_write_record()

```

I've been comparing some core tables from a fresh Drupal installation, and the datatypes ar the same.

Is this a database related error or a Drupal related error? Am I even posting this question at the right place? Any help appreciated.

# Answer
The DBTNG Migrator module is in fact a great choice. I've used it very successfully.
> 1 votes

# Answer
I have tried the DBTNG Migrator, and it failed miserably for several reasons. I even had to patch it with my own fixes because a table field in the privatemsg module where named "public" that is a reserved key word in SQL Server.

I ended up using the "Microsoft SQL Server Migration Assistant for MySQL" from Microsoft. It worked flawlessly and given the fact that they are the maker of SQL Server, why reinvent the wheel and waste your valuable time.

Do yourself a favour guys and use the tool provided from the DB Makers. Even MySQL Workbench can migration easily (few clicks) can migrate between MySQL and anything.

The good news is that all these tools are totally free.

Cheers
> 0 votes

---
Tags: database
---


# Question
Title: What is correct selector for radios to determine if ANY radio is selected?
Using #states to change form element visibility, I would like a 2nd element to be visible only if the 1st element is filled in. The first element is a pair of radio buttons, so I tried:

```
  '#states' => array('visible' => array(
  ':input[name="radio-id"]' => array('value' => '0', 'value' => '1'),
    ),),

```

However that doesn't work, the 2nd value condition clobbers the first, so the other element only appears if the 2nd radio ('1') is checked. So then I tried:

```
    :input[name="radio-id"]' => array('checked' => TRUE),

```

Nope, that doesn't work either.

What is the correct syntax to use for this, and which documentation page is it on? (drupal.org or other site?) I've looked and looked but can't find it.

# Answer
> 9 votes
Had same problem today. A slight modification of the *negated value expression* proposed on this comment: "Empty Radio Selection" on drupal\_process\_states() API page, did the trick for me!

```
'#states' => array(
   'visible' => array(
     ':input[name="radios-name"]' => array('!value' => false),
   ),
 ),

```

I just wanted the select list with the above #states entry to be invisible while no selection has still been made on my list of five radios (sharing name "radios-name").

Radios were also '#required' =\> true, in my case and all 5 individual radio-buttons have non-numeric string values. No #default\_value is specified in my case either.

**Disclaimer:** I have only tested this on Chrome!

# Answer
> 2 votes
You should take a look at the States example in the Form Example in the Examples project. This exact situation is demonstrated several different ways.

# Answer
> 2 votes
The documentation for the #states property is in the documentation for `drupal_process_states()`, which contains the following sentence and example code.

> When referencing select lists and radio buttons in remote conditions, a 'value' condition must be used:
>
> ```
>   '#states' => array(
>     // Show the settings if 'bar' has been selected for 'foo'.
>     'visible' => array(
>       ':input[name="foo"]' => array('value' => 'bar'),
>     ),
>   ),
>
> ```

The code you are using in your second snippet works for checkboxes, such as in the following example.

```
$form['toggle_me'] = array(
  '#type' => 'checkbox',
  '#title' => t('Tick this box to type'),
);

$form['settings'] = array(
  '#type' => 'textfield',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="toggle_me"]' => array('checked' => TRUE),
    ),
  ),
);

```

---
Tags: forms
---


# Question
Title: Views 3, link picture/title to users blog
I have a view of active blog users and I want to link the title of each blogger to their blog ie /blog/\[uid\].

By default, it seems views can link the blogger title to their profile ie (/user/uid) but I want to link the blogger title to their blog (/blog/uid)

Any idea of how I can go about this please?

Thanks,

# Answer
> 0 votes
Figured this out:

* Add field uid to views.
* Go to picture field in views, click rewrite results and output this as link, and then for link path: /blogs/\[uid\]

Make sure the field uid is visabally above al lthe other field in the view.

---
Tags: views, theming, nodes
---


# Question
Title: how to make previously entered values appear for multistep forms after validation errors
so evidently if I turn a form into a multistep form:

```
  if(!isset($form_state['storage']['step']))
    $form_state['storage']['step'] = 1;

```

and do form\_set\_error() in validate

when the validation error appears, the values that I previously put in would disappear.....

so If I enter a value into a textbox in a multistep form then hit continue then validation error appears, the textbox will now be empty instead of being filled with my previously entered values as it would happen normally

is there a way to prevent this from happening without manually reentering the default values for every form element?

fyi I'm using drupal 6

# Answer
I was bitten by a similar case in a multistep form scenario, though in my case it was use of the "Previous" button that didn't preserve user entered values.

Initially I was under the impression that D7's form\_builder() would automatically merge user data in $form\_state\['values'\] back into the '#value' property of the form elements on previous step's subform, but this never happened!

After reading carefully through examples module, **form\_example/form\_example\_wizard.inc**, I realized that I had to use:

```
'#default_value' => !empty($form_state['values']['my_elem']) ? $form_state['values']['my_elem'] : '',

```

on all form elements that I wanted to "remember" their user input!
> 1 votes

---
Tags: forms
---


# Question
Title: Views contextual filter using entity reference field
I have two content types. An image content type and a photographer content type. I have linked the photographer to the image content type by using entity reference, so that each image has a reference to a photographer.

I have created a view which shows all the images. I want to be able to use a contextual filter so that when I add the photographer title field into the URL it only shows images for that photographer. I have got this to work by adding a relationship in the view to the photographer and then using the photographer title field as the contextual filter. However, it doesn't work if any spaces in the title are replaced with dashes. Is it possible to make it work so that I can replace the spaces in the photographer title field with dashes?

So for instance the URL "photos/john smith" works, but the URL "photos/john-smith" does not, and I would like the last URL to be able to work.

# Answer
The usual approach for this would be to expose the images view as a block, and to show that block in the 'context' of the photographer page. In the Contextual Filter configuration for the entity reference, select 'Provide default value \> Content ID from URL' under 'When the filter value is NOT available'.

This will display each photographer's gallery as a part of his page. If the URL is important, give the photographer content type a default alias of "photos/\[node:title\]" under "/admin/config/search/path/patterns".
> 0 votes

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


# Question
Title: How to rewrite paths delivered by solr search (to view instead of node)
How can i rewrite the path of results delivered by solr search? Or is it possible to configure it the way i need?

The content of that particular website is organized in views. I do not want users to navigate to the node-view mode of the content, instead i want to redirect them to the specific views-page. Is there a way to show only views-pages as search-results? Or do i have to rewrite the links somehow?

# Answer
If you're using Apache Solr Views, or Search API Solr Search with Views, you can re-write the field in the usual Views way. Otherwise, you may need to fiddle with the search result template in your theme, which I realize is ugly.

A better choice would be to override the node display entirely, for example using Panels and creating a Page at node/% that overrides all node display for the appropriate content types. You can then customize the presentation of your nodes using Views that take the current node ID as an argument. This sort of thing is also possible using Display Suite, although that's a more complex solution. If you really always want people to see your node as presented by a View, you may as well solve this directly instead of by tweaking the search results.
> 2 votes

# Answer
I'm not sure I follow the question completely, but if you are using facets along with Solr you could try out Facet API Pretty Paths.
> 1 votes

---
Tags: 7, views, uri, search
---


title: Quicktabs Image in tab title

text:
# Question
Title: Quicktabs Image in tab title
I really need help with this.

I want to replace the link within the tab tile with an image. I can't find a solution for that. I saw some patches but I am not good at php and I did't got them right.

Can someone please tell me where I can find some tutorials about that?

Thanks.

---

I want to give some update regarding this. I tried different solutions and I need some advice.

Main goal is to add a different image to each tab. Empty tabs will be hidden.

**Version 1. Field-Group module**

I tried using that module and simple css with both class and id tab:

`#vertical-tabs-list1 {
background: url('images/harta3.png');
background-repeat: no-repeat;
height: 64px;
text-indent: -9999px;
padding-top: 15px;
}`

`.vertical-tab-button.vertical-tab-button2 {
background: url('images/evenimente.png');
background-repeat: no-repeat;
height: 64px;
text-indent: -9999px;
padding-top: 15px;
}`

This is working up to a point where is not working properly. If you hide empty tabs the following tab will take class and id of previous tab and that will mess up everything, because class and id are in li element and not in a href element like quicktabs.

**Version 2. Quicktabs - Plausible solution**

`

Contact
`

As you can see we have this id="quicktabs-tab-pagina\_local-0" in

what I tried is simple css for each tab

`#quicktabs-tab-pagina_local-0 {
background: url('images/media.png');
background-repeat: no-repeat;
width: 100px;
height: 100px;
font-size: 0px;
}`

This option seams to work, even if we have hidden empty tabs.

Now I want to ask:

1. Is version 2 reliable, or I will mess up things in other places?
2. Is it possible to add id same way to field group? How?

Thanks

# Answer
> 4 votes
Probably best to add your own Quicktabs style and use CSS background images.

In a custom module

```
function MYMODULE_quicktabs_tabstyles() {
  $tabstyles_directory = drupal_get_path('theme', 'MYTHEME') . '/quicktabs';
  $files = file_scan_directory($tabstyles_directory, '/\.css$/');
  $tabstyles = array();
  foreach ($files as $file) {
    // Skip RTL files.
    if (!strpos($file->name, '-rtl')) {
      $tabstyles[$file->uri] = drupal_ucfirst($file->name);
    }
  }
  return $tabstyles;
}

```

CSS files in THEMEDIR/quicktabs/\*.css will be read as a potential style

In your theme dir, add /quicktabs/image-tabs.css

Clear all caches

New style should be available, with accompanying CSS classes, add to your new CSS file.

Alternatively target the existing quicktabs classes with CSS.

Basic CSS background image tute here

# Answer
> 0 votes
I have used CSS rules: `background-image:` to pull an image in the background of the link (or the `li`) and `color: transparent;` to hide the text. According my test this works fine even on IE7.

---
Tags: media, blocks
---


# Question
Title: How to transfer multiple databases by sql-sync?
I've created proper aliases and successfully pulled files/database from live to dev server by:

```
drush sql-sync @live @dev

```

But I noticed my secondary database (defined also in `settings.php` and in alias file) has not been populated when syncing. I have `default` database and one additional database for some special operations which I use.

There was no any error message after sync, so I presume `drush` did not try to copy that database.

Is there any additional procedure I must follow when doing sync of 2 databases, or this was presumed to be automatic?

If there is no out-of-the-box answer, or I should show my config files?

# Answer
Drush sql-sync will only copy one database per run; if you have multiple databases to copy, you must run sql-sync multiple times. Use --source-database=other and --target-database=other to specify some other database. Use --source-target=mirror and --target-target=mirror if you want to copy a secondary mirror of your Drupal database (not your use-case).

Rename 'other' and 'mirror' to match the appropriate key of your database record. See figure below.

```
Array
(
    [default] => Array
        (
            [default] => Array
                (
                    [driver] => mysql
                    [username] => www-data
                    [host] => localhost
                    [database] => drupaldb
                )
            [mirror] => Array
                (
                    [driver] => mysql
                    [username] => www-data
                    [host] => localhost
                    [database] => mirrordrupaldb
                )

        )
    [other] => Array
        (
            [default] => Array
                (
                    [driver] => mysql
                    [username] => www-data
                    [host] => localhost
                    [database] => otherdb
                )

        )

)

```

**Update from NenadP:**

It seems that you need to add `--strict=0` when using Drush 5 to work around a bug in the sql-sync command definition. This has been fixed in Drush 8.6-6.x.
> 2 votes

---
Tags: drush
---


title: Custom validation for field form?

text:
# Question
Title: Custom validation for field form?
I'm using below codes in Bartik theme.

I need to make: Value cannot be `4` in integer `field_total`

But dont know why not working.

```
function bartik_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'bartik_form_validate';
}
function bartik_form_validate($form, &$form_state) {
  if ($form_state['values']['field_total'] == '4') {
    form_set_error('title', 'Total cannot be "4"');
  }
}

```

New added: clearing cache giving error:

```
Notice: Undefined index: field_total in bartik_form_validate() (line 161 of /var/www/dru7/themes/bartik/template.php).

```

# Answer
> 0 votes
The problem is that `$form_state['values']['field_total']` does not exist.

First make sure that you have a field value called field\_total.

Second try this code once you make sure you do `$form_state['field_total']['#value']` to get the value of the field.

---
Tags: 7, forms
---


# Question
Title: visibility of a view based on current node field
I am displaying a block of related articles in node page using views. I want to hide a view on node page if certain entity field on this node is empty. My view has contextual filter with default value node nid (relationship to entity ref. field) and relationship to entity reference field. How is it possible to do?
My aim is to show block in sidebar or mail content based on what is in the field (n/a or sidebar for example). Or is there any better way to show that block on various positions of page?
I use context module so I would create views - one for sidebar and second for main page. One would be set to show only if field is empty and the second one opposite. Thank you.

# Answer
> 0 votes
Just add another filter on the parent node relationship for that current field. Not sure on what field is what for you but it seems you have all the relationships added into the view based on the parent node page?

Just add another filter, select the field you want to check, add the parent node relationship and make sure its NOT EMPTY.

If you just have the contextual filter as a nid, add a relationship to that nid so you can get access to the parents fields.

---
Tags: 7, views
---


# Question
Title: after migrating to D7 all images are missing
After migrating to D 7.20 all my images are gone, actually they exist on the server but are not being displayed at all. I have a multi-site installation and I've successfully migrated all the content and re-enabled the modules. I have a page where all the users pictures should be displayed and none of them are being displayed. So, I've created a new account and uploaded a picture for it and this new picture appears. What should I be looking at? How can I migrate all the pictures to the new installation properly ?

Thanks.

# Answer
> 0 votes
The storage of user pictures changed from D6 to D7. I think the answer for your problem might be found at Picture Migration on drupal.org.

---
Tags: migrations, media
---


# Question
Title: Remove Side Menus on certain pages in Drupal 7
I realize that this question might be the result of a fundamental misunderstanding of how things work. So I apologize in advance if this is just me being a dope.

I am creating a webpage for a festival. On each page there is a left side menu bar with about 6 menus in it. I want that there most of the time, so that is good.

I've now created the ability for users to add events to the festival so others can see what's going on. I've created a content type called Event, added the fields I want to it and exposed it to registered users. I then create a table view and calendar view with all the events broken down by date/time with a few filters.

All that is working fine. The part I'm now struggling with is, I want all the menus on the left to go away, any time I am working with the events. Which means when I'm adding, editing, viewing the content, and when I'm viewing the Event views I want access to the entire width of the site, except for a small menu on the right with Add Event, View Events, View Calendar.

I thought a sub-theme would get me what I want, so I created a subtheme with the menus the way I want it and the page the way I want it. But I can't for the life of me figure out how to get the content to show in the sub-theme.

Any help would be appreciated. Please keep in mind I am very new to drupal so as much detail as you can go into would be appreciated.

Thanks,

PJ

# Answer
Check out the Context module - http://drupal.org/project/context.

That should help you show the menus/sidebar on pages you want (i.e. adding, editing, viewing the Event content type) and not on the others.
> 1 votes

# Answer
Did you added the menu on the left side menu bar using blocks or printing directly from the template?

On the first case you can hide the blocks on specific pages in many ways. The easiest is to configure the visibility from the blocks configuration (Administration \> structure \> blocks). On every block settings you can specify in which pages hide or show the block.

If you're printing the menus from the template you've to use some php in order to select when print them, like "if current page is x, then print" or something similar.

:-)
> 1 votes

# Answer
One solution would be to create another content type for your Events pages. Then once you have that content type, you can create a separate template for it in your theme, which will be named page--YOUR\_CONTENT\_TYPE\_MACHINE\_NAME.tpl.php. In this template you can rearrange your content as needed, ie omit the sidebar-first element, add a top menu, etc. For more info, you can refer to this tutorial.
> 0 votes

---
Tags: views, routes, entities, theming
---


# Question
Title: problems with contextual filter backtracking node references
Drupal 7.19

I have two content types defined: Package and Account. In the Package type, a Node Reference field is provided as field\_account.

I have two packages that each have a reference to one account.

In the Package display, a link is given for the Account. Clicking on that link shows the Account. --now my problem-- On that Account page, I wish to add a block that provides links back to the two Packages.

I have been trying and trying to use Contextual Filter and just can't get it... Appreciate all the help, --Scott

# Answer
Under the contextual filter, check 'Provide default value' under 'When the filter value is NOT available' and select 'Content ID from URL' as the type. Your view should work.

Conceptually, you wish to list 'Packages' in the Context of the Account you are displaying.
> 0 votes

---
Tags: blocks, views
---


# Question
Title: Making a block's content's all show in one row
I have a block that is made up of 3 subblocks: an image block, a menu block and a views block. I combine the three blocks programmatically like this:

```
function inflatable_icons_menu_combo_block_content() {
    $block = block_load('views', 'icon_views-block_5');
    $block2 = block_load('menu', 'menu-facebook-menu');
    $block3 = block_load('imageblock', '1');
    $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block3, $block, $block2))));
    return ($output);
}

```

Now this block shows up with all three blocks and looks like this:

But I need the image to show up on the same row as the other two blocks. What would be a good way to make it all show up on one line?

# Answer
This appears to be a stylesheet issue. Everything should 'float:left'. If this has already been done, then your first block is too wide and is forcing the other blocks to displace down.

Experiment with maxwidh on your first block to leave room for the other two.
> 2 votes

---
Tags: views, routes, blocks, media, theming
---


title: Magazine auto-publish by date & month

text:
# Question
Title: Magazine auto-publish by date & month
I am developing a complex website which will serve as an online magazine.

I am currently experimenting with the Book module and organizing my content in months but I am not sure it is a long term solution.

**I am trying to achieve a setup which at midnight of February 28th will automatically publish all content associated will the new month of March and un-publish content for the previous month.**

I would greatly appreciate any suggestions to achieve this.

# Answer
> 1 votes
I would recommend the Scheduler module.

From the module page: "This module allows nodes to be published and unpublished on specified dates."

I have used it with custom content types without an issue, so I imagine it should work with Book if you like how that module works.

Just note, it publishes/unpublishes on cron runs, so either set your cron to run exactly at midnight every day (preferred), or in your system settings (/admin/config/system/cron) have cron run every hour. If you have drupal execute cron be aware that it will not actually run every hour, but rather the next time you have a visitor.

# Answer
> 1 votes
You can use cron to achieve this,

* Use hook cron in your custom module and write the codes to publish and unpublish based on your conditions
* You can use Elysia Cron to schedule this cron job to run in every month or every first day of a month. Or you can configure cron in your server to set exact timings.

---
Tags: 7, nodes
---


# Question
Title: Node Access permission for anonymous users
The website is set Only login users can access. but There are times a node maybe allow an anonymous user to access by sending the user the URL for the node.

I try to use the Content\_Access module to make it but it failed to make it.

How can achieve it??

# Answer
Content Access controls access by content type. The module you want is the Nodeaccess module.
> 2 votes

---
Tags: 7, users
---


title: Classes in body of user profile page

text:
# Question
Title: Classes in body of user profile page
I have got a question. I have got drupal 7 running and in the user profile page, the body classes look like this:

```
<body class="html not-front logged-in one-sidebar sidebar-first page-user page-user- page-user-1">

```

If you notice, the second last class, 'page-user-' seems like it is missing something at the end, meaning, something is not working right. I have used theme devel and just did some mega digging around (including the user module) to see where this class is being added from, but I have had no luck.

I would basically like to change the styling of some tables in the user profile page via css and would like to identify these tables by a specific class in the body, so that it only applies in this user profile page. If that class was perhaps displaying correctly, I could identify the tables with that, and not have to modify the user-profile.tpl.php page to add a new class. So, I would appreciate it if anyone could tell me where these classes are being added, and what that missing variable could possibly be. Thanks.

# Answer
Drupal add arguments to page classes to make it possible to theme the page depending on the current page type (e.g. node, admin, user, etc.) as well as more specific data like node-12 or node-edit.
> 0 votes

# Answer
The solution/or answer to this question lies here:

theme\_get\_suggestions

Thanks def-gie for the answer.
> 0 votes

---
Tags: theming, users
---


# Question
Title: Is it possible to subscribe to a newsletter without first having to register?
I am using the Simplenews module, but from what I've been able to conclude, is not possible to subscribe to a newsletter without first having to register. Is that correct?

Is there a different newsletter module which will enable me to do this: offer a newsletter subscription to users without having to first become a registered user?

# Answer
It is supposed to be possible, but the anonymous user is still required to confirm their email address. Check this issue in the Simplenews issue queue.
> 1 votes

# Answer
Yes, it is possible. You do not need to register to subscribe to a simple news list. It is the default way to use the module.
> 0 votes

---
Tags: emails
---


title: Adding multiple nodes at once

text:
# Question
Title: Adding multiple nodes at once
I have created for a mobile site a form to collect daily readings using a content type and that is working like a charm. The question is:

Is there a method, way, module or hack where I can setup some sort of form where the same content type form will be display 7 times (one for each day) and the common fields be merge into one?

The reason for my question is that the regular form make sense to be fill using a mobile device, but if someone wants to use a desktop computer it will make more sense to enter the 7 days of data at once.

# Answer
Multi Node Add module could be very helpful for you. With this module you can add multiple nodes at once.

> This module provides a new interface for creating nodes where the users are able to select the fields what they want to use for creating the nodes.
> It is designed to create multiple nodes in one round, it's possible to add more node input rows on-the-fly.
> 2 votes

# Answer
It won't do exactly what you want, but there is a node copy module that allows a user to copy contents from one node to another, edit it, and submit it as a new one. It would certainly save time for your users in having to re-type existing data in a form.

http://drupal.org/project/node\_clone
> 1 votes

---
Tags: 7, nodes, forms
---


# Question
Title: Should I create fielded content types (with 1000+ tables) OR create custom entities with properties instead of fields (way less tables)?
I have a case where I have a lot of entities that can be stored with Drupal as node (content types) and fields. I had to end up creating 105 content types, 20 taxonomies and in-numerous fields. And the result is that I have right now 1600+ tables in my database. I'm assuming that is not healthy. Please advise.

The other option that I have now is to create entities. I can use entity api module to create a lot of the above content types as separate entities with all properties which would mean that one entity information is stored in one table as opposed to 2 fields for each field (i.e. data and revision). The data in these content types need to be imported but I do not need any CRUD interface for them. Will my database calls be better in terms of performance if I make separate entities instead of content types?

My main objective is to be able to present all the information through views. And I believe that if I have entities, I should be able to display the properties through views. Is that true? I have not tried ECK yet, so I am not sure if creating Entities through interface works clean, so some help in that regard will be very much appreciated.

# Answer
It depends on your requirement. For example, if you want nodes to be revisioned then go for content types. If you do not want them to revisioned and just using them for storing content then I think entity would be a better option.

**Update: 19th June 2016** Thanks to @jon-freed

> When it comes to performance-sensitive projects, nodes should really only be used for content, and we should separate as much as possible from nodes. Why? Nodes are revisioned, they fire a lot of hooks, and they have functionality that we likely won't need. Also if we know exactly what fields we should have in our entities, we can create our own custom entities to avoid all those joins of Field API tables.

As far as the choice between ECK and entity api module, it also depends on your requirement. Entity api module provides more control over an entity, for example if you want to create an entity controller for the entity then you should use entity api module. If you just want to create an entity and define some properties then go for ECK. ECK also allows you to created bundles for entities.

Also, you can easily create views for the entities, this site provides great example to work with entities.

Reference: Drupal 7 Entities: What are they, and what are they good for?

**Update: (19th June 2016)**

It is true that using fields will increase the number of tables, which means more JOINS during database queries. **If the purpose is to store data only then you should go for properties**. If you want to take advantage of Drupal fields (display the data in cool ways), then you should go for fields, but in this case you have to think about the performance.

We can add fields to nodes and custom entities. Therefore, using nodes will not affect performance. You can always alter properties of an entity using `hook_entity_property_info_alter(&$info)`
> 1 votes

---
Tags: 7, entities
---


# Question
Title: DRUPAL_ROOT undefined on module installation
I try to install the live\_agent module. When I go to enable the module, I get the following errors:

> Notice: Use of undefined constant DRUPAL\_ROOT - assumed 'DRUPAL\_ROOT' in /sites/all/modules/live\_agent/live\_agent.module on line 319
>
> Warning: require\_once(DRUPAL\_ROOT/includes/errors.inc) \[function.require-once\]: failed to open stream: No such file or directory in /sites/all/modules/live\_agent/live\_agent.module on line 319
>
> Fatal error: require\_once() \[function.require\]: Failed opening required 'DRUPAL\_ROOT/includes/errors.inc' (include\_path='.:/usr/share/pear:/usr/share/php') in /sites/all/modules/live\_agent/live\_agent.module on line 319

The code causing the error is the following one.

```
 /* 318 */ function live_agent_buttons_form(&$form_state) {
 /* 319 */   global $base_url;
 /* 320 */
 /* 321 */   $settings = new liveagent_Settings();
 /* 322 */   $la_buttons_grid = $settings->getButtonsGridRecordset();
 /* 323 */   $recordset = $la_buttons_grid->toArray();
 /* 324 */
             // ...
 /* 373 */ }

```

Any help on debugging this would be greatly appreciated.

# Answer
> 1 votes
The error about the undefined constant `DRUPAL_ROOT` could be caused from the index.php file that is corrupted, or that is returned corrupted from APC, or similar extension. `DRUPAL_ROOT` is always defined when Drupal bootstraps.

```
/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

```

As for why the error message is reported for that module when a function that doesn't contain any reference to the constant is executed, I think that is caused from the autoload function Drupal registers, drupal\_autoload\_class(), which is trying to load the file containing the class.

# Answer
> 0 votes
Check your settings.php file. You might have either.

You set the wrong base URL, or maybe you did not set one and this module requires it.

---
Tags: debugging
---


# Question
Title: How to access database table with drupal 7
I am quite new to Drupal. I am creating custom module which connects to the database table. I have gone through the API documentation and created a test function and tried db connect, but there seems to be an error. This is my code:

```
function first_db_insert() {
  db_insert('imports')
    ->fields(array(
      'name' => 'Groucho',
      'address' => '123 Casablanca Ave.',
      'phone' => '555-1212',
    )
    )
  ->execute();
  drupal_set_message('database updated');
}

```

# Answer
> 1 votes
If you have an autoincrement value for the primary key on the table you are inserting, then the `execute()` function will return you this increment value. So just check what it is returning. But do make sure the value is defined as an autoincrement (defined as serial in hook\_schema) because otherwise the returned value should not be used as it is *undefined*.

```
$nid = db_insert('node')
  ->fields(array(
    'title' => 'This is only a test.',
    'uid' => 1,
    'created' => time(),
  ))
  ->execute();
// This will ouput the $nid value to Drupal log.
 watchdog('yourmodule', "The value for nid is $nid .");

```

---
Tags: forms, database
---


# Question
Title: How Drupal identifies "Display on user registration form." in from array
How Drupal identifies "Display on user registration form." in from array

**I want to do something with the "Display on user registration form." by `form_alter`**

may be hide it or whatever.

```
[field_first_name] => Array
        (
            [#type] => container
            [#attributes] => Array
                (
                    [class] => Array
                        (
                            [0] => field-type-text
                            [1] => field-name-field-first-name
                            [2] => field-widget-text-textfield
                        )

                )

            [#weight] => 3
            [#tree] => 1
            [#language] => und
            [und] => Array
                (
                    [0] => Array
                        (
                            [#entity_type] => user
                            [#entity] => stdClass Object
                                (
                                    [uid] => 0
                                    [hostname] => 111.92.58.145
                                    [roles] => Array
                                        (
                                            [1] => anonymous user
                                        )

                                    [cache] => 0
                                )

                            [#bundle] => user
                            [#field_name] => field_first_name
                            [#language] => und
                            [#field_parents] => Array
                                (
                                )

                            [#columns] => Array
                                (
                                    [0] => value
                                    [1] => format
                                )

                            [#title] => Full Name
                            [#description] =>
                            [#required] => 1
                            [#delta] => 0
                            [#weight] => 0
                            [value] => Array
                                (
                                    [#entity_type] => user
                                    [#entity] => stdClass Object
                                        (
                                            [uid] => 0
                                            [hostname] => 111.92.58.145
                                            [roles] => Array
                                                (
                                                    [1] => anonymous user
                                                )

                                            [cache] => 0
                                        )

                                    [#bundle] => user
                                    [#field_name] => field_first_name
                                    [#language] => und
                                    [#field_parents] => Array
                                        (
                                        )

                                    [#columns] => Array
                                        (
                                            [0] => value
                                            [1] => format
                                        )

                                    [#title] => Full Name
                                    [#description] =>
                                    [#required] => 1
                                    [#delta] => 0
                                    [#weight] => 0
                                    [#type] => textfield
                                    [#default_value] =>
                                    [#size] => 60
                                    [#maxlength] => 255
                                    [#attributes] => Array
                                        (
                                            [class] => Array
                                                (
                                                    [0] => text-full
                                                )

                                        )

                                    [#input] => 1
                                    [#autocomplete_path] =>
                                    [#process] => Array
                                        (
                                            [0] => ajax_process_form
                                        )

                                    [#theme] => textfield
                                    [#theme_wrappers] => Array
                                        (
                                            [0] => form_element
                                        )

                                    [#pre_render] => Array
                                        (
                                            [0] => ctools_dependent_pre_render
                                        )

                                    [#defaults_loaded] => 1
                                    [#tree] => 1
                                    [#parents] => Array
                                        (
                                            [0] => field_first_name
                                            [1] => und
                                            [2] => 0
                                            [3] => value
                                        )

                                    [#array_parents] => Array
                                        (
                                            [0] => field_first_name
                                            [1] => und
                                            [2] => 0
                                            [3] => value
                                        )

                                    [#processed] => 1
                                    [#title_display] => before
                                    [#id] => edit-field-first-name-und-0-value
                                    [#name] => field_first_name[und][0][value]
                                    [#value] =>
                                    [#ajax_processed] =>
                                    [#sorted] => 1
                                )

                            [#tree] => 1
                            [#parents] => Array
                                (
                                    [0] => field_first_name
                                    [1] => und
                                    [2] => 0
                                )

                            [#array_parents] => Array
                                (
                                    [0] => field_first_name
                                    [1] => und
                                    [2] => 0
                                )

                            [#processed] =>
                            [#attributes] => Array
                                (
                                )

                            [#title_display] => before
                            [#id] => edit-field-first-name-und-0
                        )

                    [#theme] => field_multiple_value_form
                    [#field_name] => field_first_name
                    [#cardinality] => 1
                    [#title] => Full Name
                    [#required] => 1
                    [#description] =>
                    [#prefix] =>
<div id="field-first-name-add-more-wrapper">
                    [#suffix] =></div>
                    [#max_delta] => 0
                    [#after_build] => Array
                        (
                            [0] => field_form_element_after_build
                        )

                    [#language] => und
                    [#field_parents] => Array
                        (
                        )

                    [#tree] => 1
                    [#parents] => Array
                        (
                            [0] => field_first_name
                            [1] => und
                        )

                    [#array_parents] => Array
                        (
                            [0] => field_first_name
                            [1] => und
                        )

                    [#weight] => 0
                    [#processed] =>
                    [#attributes] => Array
                        (
                        )

                    [#title_display] => before
                    [#id] => edit-field-first-name-und
                    [#after_build_done] => 1
                )

            [#access] => 1
            [#theme_wrappers] => Array
                (
                    [0] => container
                )

            [#process] => Array
                (
                    [0] => form_process_container
                )

            [#defaults_loaded] => 1
            [#parents] => Array
                (
                    [0] => field_first_name
                )

            [#array_parents] => Array
                (
                    [0] => field_first_name
                )

            [#processed] => 1
            [#required] =>
            [#title_display] => before
            [#id] => edit-field-first-name
            [#sorted] => 1
        )

```

# Answer
The checkbox is added from user\_form\_field\_ui\_field\_edit\_form\_alter(), which checks the settings for the instance being edited.

```
  $instance = $form['#instance'];

  if ($instance['entity_type'] == 'user') {
    $form['instance']['settings']['user_register_form'] = array(
      '#type' => 'checkbox',
      '#title' => t('Display on user registration form.'),
      '#description' => t("This is compulsory for 'required' fields."),
      // Field instances created in D7 beta releases before the setting was
      // introduced might be set as 'required' and 'not shown on user_register
      // form'. We make sure the checkbox comes as 'checked' for those.
      '#default_value' => $instance['settings']['user_register_form'] || $instance['required'],
      // Display just below the 'required' checkbox.
      '#weight' => $form['instance']['required']['#weight'] + .1,
      // Disabled when the 'required' checkbox is checked.
      '#states' => array(
        'enabled' => array('input[name="instance[required]"]' => array('checked' => FALSE)),
      ),
      // Checked when the 'required' checkbox is checked. This is done through
      // a custom behavior, since the #states system would also synchronize on
      // uncheck.
      '#attached' => array(
        'js' => array(drupal_get_path('module', 'user') . '/user.js'),
      ),
    );
  array_unshift($form['#submit'], 'user_form_field_ui_field_edit_form_submit');
  }

```

It is user\_field\_info\_alter() that adds the setting property to the fields.
> 2 votes

---
Tags: forms, theming
---


# Question
Title: osx 10.7.5 built-in apache 403 forbidden for sites/default/files/styles
this really drives me crazy .. BTW here is a really nice tutorial i tried - everything. believe me ... from adding users to groups, running apache as different user, chALOT -R (even chmod a+rwx), copying the original httpd.conf back, enabled UserDir, added attributes like

```
sudo chmod -R +a "group:_www allow list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,file_inherit,directory_inherit" Sites

```

but .. i'm not an expirienced sys admin // ---

i try to use both - WebServer and User location as Document root

```
setup
/etc/apache2/http.conf

setup
/etc/apache2/users/me.conf

```

and actually all seems to work fine. so AllowOverride and FollowSymLinks set

**except:** sites/default/files/styles/

image styles do not work i get 403 for requests like

```
sites/default/files/styles/fancy/public/animage.jpg

```

original images show up ..

maybe related to the 7.20 issue ?!

how can i properly debug this ?

# Answer
> 3 votes
This is more likely to be the issue with the update of Drupal core from 7.19 to 7.20.
As per the release notes, the update was only targeted to address the Denial-of-Service attack on the sites powered by Drupal.

You can add:

```
$conf['image_allow_insecure_derivatives'] = TRUE;

```

in the `settings.php`, to negate the effect of the update. As per the side effects, this will remove this security fix. I wouldn't recommend you do this on production.

**existing patch:**

```
--- a/modules/image/image.module
+++ b/modules/image/image.module
@@ -993,7 +993,7 @@ function image_style_url($style_name, $path) {
// The token query is added even if the 'image_allow_insecure_derivatives'
// variable is TRUE, so that the emitted links remain valid if it is changed
// back to the default FALSE.
-  $token_query = array(IMAGE_DERIVATIVE_TOKEN =>  image_style_path_token($style_name, $path));
+  $token_query = array(IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, file_stream_wrapper_uri_normalize($path)));

```

works, and $conf can be removed !

I've answered a similar question here.

**Note:** I'm making this as community wiki, so that someone working on Drupal security (hopefully from the security team) or anyone who is interested could add more to it.

---
Tags: 7, files
---


title: how do I create submenus in my module?

text:
# Question
Title: how do I create submenus in my module?
I am pretty new to drupal php etc.

I have a module that just add links to main menu and load a .html and a .js when a link is called.

For now my menu looks like this:

* Demo

Now I would like something like:

* Demo
* More demos
    + extra demo1
    + extra demo 2

Ideally "More demos" should be collapsed and should expand on click

Here is the code I have so far:

```
<?php

/**
 * Implements hook_menu()
 */
function kl_menu(){
  $items = array();

  $items['demo'] = array(
   'title'            => t('Demo'),
   'page callback'    => 'build_demo_page',
   'access arguments' => array('access content'),
   'menu_name' => 'main-menu',
   'type' => MENU_NORMAL_ITEM,
  );

  return $items;
  }

/*
 * build_demo_page
 */
function build_standard_demo_page() {
drupal_add_js(drupal_get_path('module', 'kl') . '/demo.js', 'file');
 return  ( file_get_contents( drupal_get_path('module', 'kl').'/demo.html') );
}

```

I am not sure to go from there.

Thanks

# Answer
You can add as many menu items as you need in hook\_menu. Then, to have them showing in a tree, as long as the items are of type `MENU_NORMAL_ITEM` you can view them in the menu admin UI, and drag & drop them in the correct order and hierarchy.
> 0 votes

# Answer
I've pasted a sample code below. Hope that helps.

```
 function hook_menu() {
      $items = array();

      $items['demo'] = array(
      //other code here
      );

      $items['more-demos'] = array(
      //other code here
      );

      $items['more-demos/extra-demo-1'] = array(
      //other code here
      );

      $items['more-demos/extra-demo-2'] = array(
      //other code here
      );

      return $items;
    }

```
> 1 votes

---
Tags: routes
---


# Question
Title: Restricting Menu Item visibility for certain nodes
Is there a way of customising what pages a Menu item will be displayed on? For example, I would only like one particular menu item in the sidebar menu to be displayed for one node, but the rest of the menu item links I would like to be the same throughout the site. Is this possible?

# Answer
> 0 votes
I don't know about any module that does what you need. But you could clone you menu (with Menu Clone), remove the particular items and set the visibility to the seperate menus.

---
Tags: routes
---


title: How to call watchdog() outside Drupal

text:
# Question
Title: How to call watchdog() outside Drupal
I'm getting used to use the Drupal watchdog() function. It provides me a very simple and accessible way to log events in my code.

However, I would like to use the same (or very similar) function in some other PHP projects outside Drupal. Accessing the results via the Drupal reports interface would be nice.

Does anyone know any proper way to include the relevant files of a Drupal instance to provide this functionality in custom PHP code? I know that there are already other PHP logging solutions which may be better, but I'm looking for something similar to watchdog().

# Answer
> 7 votes
Requiring the existence of a Drupal installation for all of your other non-Drupal PHP projects isn't something I've come across before...but you can bootstrap Drupal to make the `watchdog()` function available like so:

```
define('DRUPAL_ROOT', '/path/to/drupal/installation');
include_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

watchdog('my_module', 'A message');

```

# Answer
> 5 votes
What you are requesting will considerably slow your external script. Perhaps there are better alternatives to using drupal's watchdog function.

To use watchdog function you will need to bootstrap drupal.

```
$drupal_path = '/drupal/home';

// Create a constant DRUPAL_ROOT that
// defines our path to the drupal install
define('DRUPAL_ROOT', $drupal_path);

// We need to load the bootstrap.inc file so we can
// have access to the drupal_bootsrap() function
require_once DRUPAL_ROOT . ‘/includes/bootstrap.inc’;

// Bootstrap Drupal at the phase that you need
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

Drupal bootraps in the index.php file in the drupal root. Checkout the includes/bootstrap.inc file to see the bootstrap phases and what loads at each phase. You can experiment with different phases, perhaps you do not need to perform a full drupal bootstrap.

---
Tags: log-messages
---