# Question
Title: Custom field displayed based on author node
I have a website for ads. In addition the user will have opportunity to make his ad as a VIP ad.

When the user creates a new ad, down bellow will be displayed a field "Make your ad VIP" and after clicking on that button it will popup a description. This field is created as custom field with Display suite, but I want to make visible only on node author.

The idea is only user that is author of the node can see that field "Make your ad VIP".

The module "Field permissions" cannot control this custom field.

EDIT:

The field name is "adding\_make\_vip", the custom module is "custom\_alter" and this is the code that I've tried:

```
<?php

function custom_alter_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  if ($op == 'view' && !empty($entity) && $field['field_name'] == 'adding_make_vip') {

   // $entity will be the node,so check node author with current user.
   if($entity->uid == $user->uid) {
      return TRUE;
    }
   else {
    return FALSE;
    }
  }
}

```

Unfortunately it didn't hide the field for anonymous users and users that aren't authors of the node.

# Answer
> 0 votes
How about implementing hook\_field\_access() in your custom module.

This hook takes operation edit/view as parameters and returns access to the user for the operations.As a sample code

```
function MYMODULE_field_access($op, $field, $entity_type, $entity, $account) {
  global $user;
  if ($op == 'view' && !empty($entity) && $field['field_name'] == 'your_field_name') {

   // $entity will be the node,so check node author with current user.
   if($entity->uid == $user->uid) {
      return TRUE;
    }
   else {
    return FALSE;
    }
  }
}

```

---
Tags: entities, nodes
---


title: What is causing formatting to break?

text:
# Question
Title: What is causing formatting to break?
We are using WYSIWYG with CKEditor on Drupal 7.

When the edit button on a node is clicked, the edit page shows text in a jumbled mess, even if there was careful formatting. The text formats have the "Convert line breaks into HTML" filter enabled,  as well as having the \<p\> and \<br\> tags allowed.  As per a comment, I have taken these tags out of the allowed HTML on the filtered HTML format.

WYSIWYG Linebreaks is enabled as well, but doesn't seem to solve the issue.

If breaks are added in, they seem to stay, even when editing the text again.

My question is: What is causing this formatting to break, upon clicking the edit button?

Example of ruined formatting:

On the left is what you see when viewing the page before it has been edited (i.e. the page was written by someone else), and on the right is the jumbled mess that is the edit page. On the edit page, all the paragraph or line breaks have been removed.

# Answer
> 5 votes
You are using using **filtered html** (*Text Format*). \[As per your screenshot above\]

Filtered HTML only all the following HTML tags

* Web page addresses and e-mail addresses turn into links automatically.
* Allowed HTML tags: `<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>`
* Lines and paragraphs break automatically.

> **You need to change text format to FULL HTML if you wish to retain all HTML formatting**

As a best practice Full HTML use should be limited

---
Tags: wysiwyg
---


# Question
Title: Storing objects of custom type in $_SESSION - legal way?
I'm trying to figure out: can I load custom class (defined in module) to be loaded before session starts and its contents processed by PHP (unserialized) - is where any legal way to do this? (without hacking Drupal core)

without it I get \_PHP\_Incomplete\_Class if I store something of a custom type to $\_SESSION variable.

I did a research:

* hook\_boot is not called unless page is cached in NO DB mode otherwise it's called after session is loaded
* hook\_init is called too late (always after session load)

Any thoughts?

# Answer
> 2 votes
actually, I have found a workaround to do so without patching the core.

it is simple.

Drupal 7 core includes all module files which have `hook_boot()` registred, prior to open session, but `hook_boot()` is called only then session is started.

What you need to do - is to manually include class declaration outside of a `hook_boot()` (in a root context of a file containing `hook_boot()` of your module).

Such code is immediately executed as file being included by Drupal Core (prior to `session_start()` call), which gives us the desired behavior - we now can store objects of a *CustomClass* in `$_SESSION` variable and they wont become corrupted on next page load.

but be carefull if your *CustomClass* is extending from *AnotherCustomClass* located in different module and loaded by same mechanics (as described above) - you cannot be sure in order file loads. This can lead to fatal runtime error: Undefined class

---
Tags: sessions
---


# Question
Title: Automatic Node Expire / Unpublish with Renew Option
I have a classifieds site and would like to have a node expire after 45 days (unpublished), no matter how many times the user edits and saves the node. However after the node expires, the user has the ability to renew (publish) for another 45 days. I would like the time to be strictly 45 days with simple a renew button when it is expired.

Here is the workflow:

1. User creates node
2. Email is sent to node author indicating successful post.
3. Node is automatically expired 45 days later.
4. Email is sent to node author indicating expired post.
5. User has the ability to easily renew ad (expiry date is 45 days later yet again)
6. Email is sent to node author indicating renewed post (different from step 2)

I would also like to have a countdown for the days remaining until the expiry date.

I have successfully built steps 1-4 using rules only, however the rules are based on the event **'After saving new content'**, which means when a node is republished/renewed the rules do not follow because it is not new content.

I have also tried using the Scheduler module to set the unpublish date but cannot figure out how to enable renew only after it has expired.

I have also tried Auto Expire but I think it only gives the ability to renew before it expires, not after.

# Answer
I would have opted for a custom code solution with the above work-flow.As an alternate contrib module option classified Ads module can be potential option.

Module Features:

> Renewable expired ads during the 'grace period' Simple taxonomy-based browsing Ad expiration depending on category selection Per-user classified ads lists – custom lists totally sortable Length-limited body text with live counter of characters Advanced Help, CCK, Context, Panels, Token and Views support
> 0 votes

# Answer
This is an idea/suggested code but not solution. Use `node_save` to re-publish node.

```
$node = node_load($nid);
// set status property to 1
$node->status = 1;
// re-save the node
node_save($node);

```
> -1 votes

# Answer
1. Create a button and display it in menu local task tab (along with node `edit`).
2. Once the user clicked the "Renew" button it will trigger the custom function that contains something like monymirza's answer.

Make sure that the "Renew" button is only visible to node owner only.

```
function renewAd() {
  $node = node_load($nid);
  // set status property to 1
  $node->status = 1;
  // re-save the node
  node_save($node);
}

```

See this thread on how to get the nid from URL.

Get a node ID from the URL
> -1 votes

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


# Question
Title: Best approach to wrap rendered file field in a link?
I have a file field from the File Entity module (2.x-alpha2) attached to a content type. I'm trying to customize the output of this field so that it links to the main node (this is for a teaser display). I'm overriding the node template for the teaser display, so I have access to the renderable field array for the field as well as the node path.

I'm trying to find the best approach for wrapping the image in a link. I can easily create the link tag using the l() function. However, I can't just wrap that around the rendered file field because it renders with a lot of extra markup aside from just the image tag.

What is the best approach to handle this? Programmatically altering the theme functions that render the actual image tag? It's not clear to me if I can do that quite yet.

If it helps at all, I'm also using the Media module (2.x-alpha2).

# Answer
I would create a custom field formatter for rendering the cck field itself. Look for hook\_field\_formatter\_info, hook\_field\_formatter\_view and implement your own custom module

There is also this module https://drupal.org/project/custom\_formatters you might want to check out.
> 1 votes

# Answer
So, after exploring the option of creating my own field formatter, it seems that it wasn't necessary. I was able to:

1. Change view style to "Fields" instead of "Content"
2. Add relationship to File
3. Add the field "File: Rendered", and select the appropriate display style.

The output of this rendered field does NOT contain any of the extra markup for the field output itself, and I can modify the views row style to not output any of the outer divs that are normally added for fields.

It's important to note that when rendering a views row style as "Fields" instead of "Content", that Views will NOT render the complete file entity like it would for "Content". So, if your file entity has additional fields attached to it, they will not be rendered along with the field when using the method outlined above. See this issue I created regarding this behavior: https://drupal.org/node/2112329
> 1 votes

---
Tags: theming, files, media
---


# Question
Title: Which settings to use in hook_field_formatter_view?
Looking at the page of `hook_field_formatter_view`, the explanation for `$display` is:

> The display settings to use, **as found in the 'display' entry of instance definitions**. The array notably contains the following keys and values;

But I just found out that the `$display` variable does not hold accurate information.

This is what's inside my `$instance` (correct settings)

This is what's inside my `$display` (default values for settings)

I could overwrite `$display` from the `$instance` settings, but I can't figure out in which variable the current view mode is stored, so that I can grab the settings for the correct view mode.

As a little background info, this is a custom field with a custom formatter. Has anyone had similar issues with a custom field/formatter?

# Answer
This wasn't really a problem. This was because the page was a Panels page, and the field was added into the panel page with its own formatter settings.

Solved by setting the correct field formatter settings on the panel page.

It's one of d'ohs days.
> 1 votes

---
Tags: 7, entities
---


title: Updated by in content

text:
# Question
Title: Updated by in content
I have an article type where a **content admin role** can Create *an Article*. There are **10 Content Admins** in system. If one content admin creates the node, I can see eg: `Submitted by username`. If **user2** edits the same article, I want to store who edited it and when in database and display the *edited by: OR Updated by:*

Its same like in SE websites, you can see who edited the post at what time. How do I do this in Drupal 7 ?

P.S. I am still new in Drupal and haven't explored all the big ocean of Modules in Drupal, so, there might be easy solutions for these things somewhere which I couldn't come across using Google Search.

# Answer
> 0 votes
Node Revisions are stored in `node_revision` table.This table keep track of what user edited what nodes as separate revision.

Also the last uid who has revised/updated the node is available in $node entity.So try something as below in your theme template.php

```
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];

  // Gather last updated author info
  $revision_uid = !empty($node->revision_uid) ? $node->revision_uid : 0;
  if (!$revision_uid) {
    $revision_username = variable_get('anonymous', 'Anonymous');
  }
  else {
    $revision_user = user_load(array('uid' => $revision_uid));
    if ($variables['is_admin']) {
      $revision_username = l($revision_user->name, 'user/'. $revision_uid);
    }
    else{
      $revision_username = $revision_user->name;
    }
  }
  $variables['revision_username'] = $revision_username;

```

Then just `<?php print $revision_username; ?>` in your .tpl files.

Reference Link:

https://drupal.org/node/236523

Since above code will show only the last editor info,if you want to get all users you can query the node\_revisions table.

---
Tags: 7, nodes
---


# Question
Title: Drupal fboauth module - how to get the friendlist of a user
I have checked the friendlist field in configuration settings of the fboauth module. Now what do I do to get the friend list of the logged in user.

# Answer
> 1 votes
You need to know $access\_token.

```
$result = fboauth_graph_query('me/friends', $access_token);

```

See the Facebook API for a list of commands: http://developers.facebook.com/docs/reference/api/

---
Tags: social-network
---


title: File Upload, overwriting every time

text:
# Question
Title: File Upload, overwriting every time
I am using the Migrate module, and I need to upload a CSV file before every migration run. I've created a module that allows me to upload a file.

My first step was to make sure I had the logic correct for overwriting a file, so I have the following code:

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

if ($form_id == 'migrate_ui_dashboard_form') {
  $form['fldset'] = array(
   "#type"        => "fieldset",
   "#title"       => "CSV to Import",
   "#collapsible" => "TRUE",
   "#collapsed"   => "FALSE",
   "#weight"      => "-98",
 );
$form['fldset']['csv_file'] = array(
   "#type"   => 'managed_file',
   "#title"  => t('Choose a file'),
   "#upload_location" => 'private://user_migration',
   "#upload_validators" => array(
      "file_validate_extensions" => array('csv'),
   ),

 );

$form['fldset']['actions'] = array(
   "#type"    => 'submit',
   "#value"   => t('Uploady'),

 );

}

return $form;

}

```

That creates the file upload widget etc.

The following is what I do upon form submission:

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

  $file = file_load($form_state['values']['csv_file']);
  //TODO: rename file to user_migrate.csv
  $file->status = FILE_STATUS_PERMANENT;
  $file->replace = FILE_EXISTS_REPLACE;
  file_save($file);
}

```

The file uploads fine, and then when I refresh the form, and do another upload, that works but the file is not overwritten, but is incremented.

# Answer
What you're describing is the expected behaviour for a managed\_file widget. If you dig through the functions you eventually get to `file_managed_file_save_upload()`, which is responsible for actually saving the file.

That function calls `file_save_upload()` *without* the 4th parameter, which is `$replace`.

Since the default for that parameter is `FILE_EXISTS_RENAME`, `file_save_upload()` has no choice but to use in that context.

When you refresh the page, the original file that was uploaded has not been cleared up; in fact it won't be until the temp file cron job runs. So Drupal is "correctly" ensuring that the original file doesn't exist, because the managed file field is telling it to rename, not replace, files.
> 2 votes

---
Tags: 7, forms, files
---


title: Views calender missing menu tabs

text:
# Question
Title: Views calender missing menu tabs
I cannot get my Views calendar to have the tabs (e.g. Month,Week,Day,Year) in the upper left corner like the below image:

How do I get those tabs to appear?

# Answer
In case anyone is experiencing the same problem:

1) Go to each display's Page Settings. 2) Set the Path $path/week, $path/month, etc., where $path the respective path you have in the month display. 3) Set the Menu Type in Menu to Menu Tab.

Save view and clear caches.
> 1 votes

---
Tags: 7, views, datetime
---


# Question
Title: Adding js and css from a module but only to node view, not node edit
I'm adding js and css from a custom module and it works except for the fact that it also adds to the node edit page which I don't want.

I have this in my custom module:

```
function MYMODULE_preprocess_page(&$vars) {

// Global node.
$node = menu_get_object();
 if (!empty($node) && $node->type == 'my_node_type') {

// do stuff here like add_js, add_css

  }
}

```

... this works except that it also adds js and css files to the node edit page which I do not want. I've been playing around with this now for a while and any searches I've done have come up blank so I'm out of ideas for now. I suspect I need an extra argument to only add this to a node view and not node edit.

# Answer
> 4 votes
You could verify the 3 argument passed inside the menu item (`node/%node/edit`, `node/%node/delete`, `node/%node/translate`). If this third argument is `null`, you know that it is the node view page.

```
function MYMODULE_preprocess_page(&$vars)
{
    // Global node.
    $node = menu_get_object();

    if (!empty($node) && $node->type == 'my_node_type' && arg(2) === null) {
        // do stuff here like add_js, add_css
    }
}

```

# Answer
> 4 votes
A quick, dirty way would be to check the current path for 'edit':

```
$node = menu_get_object();
if (!empty($node) && $node->type == 'my_node_type' && arg(2) != 'edit') {
  // ...
}

```

---
Tags: 7, theming
---


title: How do I migrate CCK filefield?

text:
# Question
Title: How do I migrate CCK filefield?
I'm migrating a Drupal 6 site with CCK filefields to Drupal 7. I installed the Drupal 7 CCK module, and I'm ready to do the migration except for a filefield field.

Migrate fields states:

> Missing field module: 'filefield'. This field cannot be migrated.

The filefield module isn't available for Drupal 7. Is there an other module, or any other way of migrating a Drupal 6 CCK filefield to Drupal 7 fields?

### Update

I just realized it's an audiofield. Basically it's a filefield with an audio widget.

# Answer
Not sure whether I should call this a solution or a workaround. Anyway:

In D6 I removed audio representation of the filefield. This makes it an ordinary filefield. Then migrated to D7 using the CCK migration kit and then added the audio representation again. Done.
> 1 votes

# Answer
Please read Migrating D6 Content Construction Kit (CCK) to D7 Fields.

Basically you've to download CCK module for 7.x and it has the functionality to migrate these fields.
> -1 votes

---
Tags: 7, entities, files
---


# Question
Title: Uninstall or delete modules when upgrading 6 to 7?
Sorry to ask such a basic question, but I can't find an answer (and I'm an amateur).

I have a website that was written for me in Drupal 6. I want to upgrade it to Drupal 7.

There are quite a few contributed modules, and I realise I need to disable these before upgrading the core. Can I then simply delete the unused modules via FTP, or do I have to use uninstall within Drupal?

# Answer
Updated after re-reading your question. :)

The process for completely removing a module is generally:

1. **Backup your site**. The Backup and Migrate module is great here too.
2. **Disable the module**. Admin -\> Modules -\> Uncheck module -\> save.
3. **Uninstall the module** \- Goto yoursite.tld/admin/modules/uninstall -\> Check Modules to uninstall -\> Click Uninstall
4. **Delete the module** \- Delete module directory.

---

Additionally you can find details regarding upgrading from previous versions of Drupal at drupal.org.

Another useful module is the Upgrade Status module. Listed only for reference.
> 0 votes

# Answer
You can use the following command to disable all contrib modules and themes:

```
echo 'UPDATE system SET status = 0 WHERE filename NOT LIKE "themes%" AND filename NOT LIKE "modules%";' | `drush sql-connect`

```

Also don't forget to clear the caches:

```
echo "DELETE FROM cache`drush sql-connect`
echo "DELETE FROM cache_bootstrap" | `drush sql-connect`

```

And make sure that you don't have any additional module inclusion in settings file (like memcached, cacherouter, etc).

To uninstall, you have to follow the standard process, or find/write some module which removes the orphaned tables.
> 0 votes

---
Tags: 7, installation
---


# Question
Title: How to add css class to block using mytheme_preprocess_block() hook?
I need to add some css classes to each list item in a menu block that I created. I thought I could accomplish this by using the following code:

```
function mytheme_preprocess_block(&$vars) {

  if ($vars['block_html_id'] == 'block-menu-block-7') {
    $i = 1;
    foreach ($vars['elements']['#content'] as $key => &$item) {
      // get each list item and add some css
      if (strpos($key, '#') === FALSE) {
        $item['#attributes']['class'][] = 'col-' . $i++;
        if ($i > 3) {
          $i = 1;
        }
      }
    }
  }
}

```

However when I try this, I do not see the new class being added when I inspect the element although it does look like it is being added with this code. What am I doing wrong? I am using Drupal 7 by the way.

Thanks.

# Answer
```
function MYTHEME_preprocess_block(&$vars) {
  if ($vars['block_html_id'] == 'block-menu-block-7') {
    $vars['classes_array'][] = 'CSS_CLASS_NAME';
  }
}

```

If you want to add a class to each individual item (li or/and a)use something like this:

```
function MYTHEME_menu_link(array $variables) {
  // replace MENU-MACHINE-NAME appropriately
  if ($variables['element']['#original_link']['menu_name'] == 'MENU-MACHINE-NAME') {
    // Add menu-li class to each li
    $variables['element']['#attributes']['class'][] = 'menu-li';
    // Add menu-li-a class to each anchor link
    $variables['element']['#localized_options']['attributes']['class'][] = 'menu-li-a';
  }
  return theme_menu_link($variables);
}

```
> 2 votes

# Answer
You can use the Menu attributes module. Here is a quote about it (from the module's project page):

> This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
>
> You should use this module when:
>
> * You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site
> * You want to give a menu item an ID so you can easily select it using jQuery
> * You want to add additional classes or styles to a menu item
> 0 votes

---
Tags: 7, theming
---


# Question
Title: Display different content on node pages depending on user role
I have a list of items visible for all anonymous user and authenticated user. Then when the user click through, if the user is anonymous, I want to tell them, "sorry must be authenticated". But if they are already authenticated I want to show them the node.

I am using:

```
if($logged_in) {
   //display node
}

```

In my `node--mycontenttype.tpl.php`. How do I make this work?

# Answer
> 6 votes
Showing different content on the same page to user depending on role could be accomplished with the Panels module like so:

1. Install the Panels module and its dependencies.
2. Go to admin » structure » panels.
3. Enable and edit the page "node\_view" template.
4. Click "add new variant".
5. Click "continue" on each screen until there is a button with "Add variant." Click "Add variant".
6. Under panel » content, click the gear in the upper left to add a panel of content for the logged in user to see. Save.
7. Click the gear in the upper right of the new content to get a menu. Select visibility rules » add new rule. Select role and set it how you want. Save.
8. If you want to show something different to anonymous users, repeat step 6 and 7 to add content and make it visible only to anonymous users.
9. Don't forget to save.

# Answer
> 0 votes
Or you can use the Context Module. Its better for developers, I think panels is better for users.

---
Tags: 7, nodes
---


title: Pinterest for Lightbox and/or Colorbox

text:
# Question
Title: Pinterest for Lightbox and/or Colorbox
Does anyone know if there is a project going on to add Pinterest to Lightbox or Colorbox?

I've been searching for some way of integrating quick share on Pinterest from my website and can't find any modules that work well. Pin It doesn't even work as far as I can tell and Service Links is difficult to figure out.

Plus the solution for Pinning isn't really the same user experience as tweeting a page or sharing on FB. An overlay on an image in lightbox or colorbox would be huge.

I'm just looking for some decent Pinterest solution for Drupal and am surprised I can't find anything.

# Answer
I used the hook THEME\_image\_formatter to accomplish this. It would be fairly easy to create a module to do this I just haven't had the time. Anyway here is what I did.

```
function THEME_image_formatter($variables) {
  $item = $variables['item'];
  $image = array(
    'path' => $item['uri'],
  );

  if (array_key_exists('alt', $item)) {
    $image['alt'] = $item['alt'];
  }

  if (isset($item['attributes'])) {
    $image['attributes'] = $item['attributes'];
  }

  if (isset($item['width']) && isset($item['height'])) {
    $image['width'] = $item['width'];
    $image['height'] = $item['height'];
  }

  // Do not output an empty 'title' attribute.
  if (isset($item['title']) && drupal_strlen($item['title']) > 0) {
    $image['title'] = $item['title'];
  }

  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = '';
    // I targeted the blog post image style to add to all blog photos.
    if($image['style_name'] == 'blog_post') {
      $output .= '<div class="blog_post">';

      $media = urlencode(file_create_url($item['uri']));
      $title = variable_get('site_name', '') .' - '. str_replace('+', '%2B', $variables['item']['title']);
      $path = $variables['item']['path'];

      $output .= '<div class="image_info"><div class="copy">';
      $output .= '<a href="//pinterest.com/pin/create/button/?url='. $path .'&media='. $media .'&description='. $title .'" data-pin-do="buttonPin" data-pin-config="none"><img src="//assets.pinterest.com/images/pidgets/pin_it_button.png" /></a>';
      $output .= variable_get('site_name', '') .'<br />'. $variables['item']['title'];
      $output .= '</div></div>';
    }
    $output .= theme('image_style', $image);
    if($image['style_name'] == 'blog_post') {
      $output .= '</div>';
    }
  }
  else {
    $output = theme('image', $image);
  }

  // The link path and link options are both optional, but for the options to be
  // processed, the link path must at least be an empty string.
  if (isset($variables['path']['path'])) {
    $path = $variables['path']['path'];
    $options = isset($variables['path']['options']) ? $variables['path']['options'] : array();
    // When displaying an image inside a link, the html option must be TRUE.
    $options['html'] = TRUE;
    $output = l($output, $path, $options);
  }

  return $output;
}

```

Just pay attention to the blog\_post check and output that I created. I have some javascript that shows and hides the button on hover but you can add that if you want.

Dont forget to add your pintrest JS to the head of your doc.

--Good Luck
> 1 votes

# Answer
There is nothing 'out of the box' that will add a 'pin it' button to Colorbox. Placing a pin it button on the overlay means that when the pin it button is used you are pinning the page you were on not the image in the overlay. This means that the Pin It button must be customized to pin the source of the image. This is possible with javasript but as this is different for each CMS I have not seen anyone create a module or plugin to do it.

If you just looking to add a Pin it button to your site in general then the dev version of the 'service links' module says it contain this network, but I have not checked.
> 0 votes

---
Tags: javascript
---


title: home block area

text:
# Question
Title: home block area
I have these 2 module in my home block area: left one is user module and 2nd is main menu block. I want to resize them to be same. I mean I want to make user menu bigger to equal main menu. where can I do this? this is picture:

# Answer
You will have to modify the .css file in your site's theme. This can be one file or many files depending on the theme that you are using. w3schools.com has good tutorials on using css. You would also want to use Firebug or Developer Tools to inspect the block elements to find the blocks id or class so that you can set css rules for the height of the box.

To make your blocks the same height, your css rule might look something like:

```
#my-block-id-1,
#my-block-id-2 {
  height: 300px;
}

```
> 1 votes

# Answer
If you don't want to use fixed heights, things get complicated: http://css-tricks.com/fluid-width-equal-height-columns/

THe easiest solution would be to use the property

```
 display: table-cell

```

Like this:

```
<div style="display:table;">
    <div style="display:table-cell">Block 1</div>
    <div style="display:table-cell">Block 2</div>
</div>

```
> 1 votes

# Answer
If you have a background or something, i would create the background as a repeating image and then add it to the container div.

```
<div class="background-image-class">
  <div class="left-box"></div>
  <div class="right-box"></div>
</div>

```

And then clear your content out with clearfix or w/e so the image will span all the way down.
> 0 votes

---
Tags: dashboard
---


# Question
Title: How to include cck field image in Forward module template (forward.tpl.php)
I'm using the Forward module and need help adding a custom field into the forward.tpl.php template. I've found a similar thread on d.o: https://drupal.org/node/2078479

However, this is for using user profile fields, not node fields. Here is the code that I came up with, but it's not fully working:

```
<?php
$path = drupal_get_normal_path($_GET["path"]);
$path = explode("/", $path);
$nid = $path[1];
$forwardthumb = node_load($nid);
$img_uri = $forwardthumb->field_thumb['und'][0]['uri'];
$fid = $forwardthumb->field_thumb['und'][0]['fid'];
$thumbfilename = file_load($fid)->filename;
$derivative_uri = image_style_path($style, $image_uri);
$success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
$new_image_url  = file_create_url($derivative_uri);
?>

```

In my testing, I've gotten the following text to output in my forwarded-email: http://mysite.com/sites/default/files/styles/blog\_thumb/public

(from the $new\_image\_url variable)

Which tells me that I've got it *partially* working, as it was able to indicate the correct folder / location... but I was never able to actually get it to spit out my image-file-name (e.g. thumbnail.png), just the path to the folder containing my image. Please let me know what I'm doing wrong?

Seems like part of this is a bit wonky, as it seems the $node variable in the template isn't the same $node variable used elsewhere in Drupal...?

\[Edit\] Wanted to also share the code that WORKS in a node.tpl file, but not in forward.tpl:

```
<img src="<?php print file_create_url($node->field_main_blog_image['und'][0]['uri']); ?>" />

```

But, when I set this code up in forward.tpl:

```
$path = drupal_get_normal_path($_GET["path"]);
$path = explode("/", $path);
$nid = $path[1];
$forwardthumb = node_load($nid);

```

And:

```
<img src="<?php print file_create_url($forwardthumb->field_main_blog_image['und'][0]['uri']); ?>" />

```

No luck...

# Answer
> 0 votes
Posted my solution on Drupal's site, the forward module issue queue:

https://drupal.org/node/2107769

---
Tags: 7, theming, entities
---


title: Hiding a block based on code

text:
# Question
Title: Hiding a block based on code
I'm looking for the best way to programmatically hide a block. In Drupal 6 I'd normally use preprocess\_block to do all my logic and then unset title and content/body from there. I've tried to do same thing in Drupal 7 but failed. What's the correct way of doing this? I'd like to avoid editing the settings through the UI as this change has to be deployed in code rather than database.

# Answer
The best (IMHO) way is to implement hook\_block\_list\_alter() in a custom module and unset specific blocks when you need to. Advantages are:

* No PHP code in your database, so your alterations can be managed in a version control system
* No hacking in the theme layer, so the alterations will remain when you switch themes
* Better performance because the block is removed from the list before it is rendered

Drupal core also uses this hook to hide blocks: block.module itself implements hook\_block\_list\_alter to apply the default block visibility settings.
> 13 votes

# Answer
Quickest way I could find was to use `template_preprocess_page()` and unset the block from there. Not entirely sure it's the correct way but it works.

```
/**
 * Implements template_preprocess_page().
 */
function MYTHEME_preprocess_page(&$variables) {

  // If sub-menu block is available.
  if (isset($variables['page']['sidebar_first']['menu_block_2'])) {

    // Unset its placeholder block.
    unset($variables['page']['sidebar_first']['block_3']);
  }
}

```
> 2 votes

# Answer
In case someone else stumbles on this more than 1.5 years later, there is a module called Logic Block that allows you to handle exceptions such as these.

> Logic block is a module designed to give site administrators extra control over how blocks are displayed - extending the default options for each block in some new ways.
>
> Some things logic block can do
>
> 1. Merge two blocks into one
> 2. Prevent a block displaying if it contains certain words
> 3. Show another block if one is empty
> 4. Show a different block depending on a user's language
>
> A default block is specified, and then its content is processed by this module in a one of four ways (although this module supports extending these).
> 1 votes

# Answer
Enable PHP filter module so that you can write PHP on block visibility settings page.

Like this
> -2 votes

---
Tags: 7, blocks
---


title: access the view but not the node

text:
# Question
Title: access the view but not the node
I have a view that displays a list of items. How to make anonymous user see this list of items but when accessing the node, it has to be logged? Any idea?

I use the latest version of drupal

# Answer
You can disable node\_access check for the view (Edit the View → *Advanced → Query settings → Disable SQL Rewriting*).
> 1 votes

# Answer
you can also create a page and embed your view inside it. in this way users can see your view. also create a node page and check this condition

```
if($logged_in)
{
    //your code
 }

```
> -1 votes

# Answer
in order to create a page for your view, I guess your view has a page display, set a path for it, say `/test` . now create a .php file and name it `page--test.tpl.php` and embed your view using this instruction :

```
views_embed_view('NAME_OF_YOUR_VIEW','page');

```

clear the cache and go to `/test` you will see your view.

and about your node page, there are couple of things you need to do, first in your template file add this function

```
function YourThemeName_preprocess_page(&$variables)
{

    if (isset($variables['node']))
    {
         if($variables['node']->type == "YourContentTypeName")
         {
                $suggest = "page__node__test";
                $variables['theme_hook_suggestions'][] = $suggest;
         }

    }
}

```

now create a .php file and rename it to `page--node--test.tpl.php`, this will be your node page and you can set authentication condition for it. you can even go further and check this authentication condition in your preprocess function, I mean create two different `$suggest`s in preprocess function :

```
function YourThemeName_preprocess_page(&$variables)
{

    if (isset($variables['node']))
    {
         if($variables['node']->type == "YourContentTypeName")
         {
                if($logged_in)
                {
                    $suggest = "page__node__test_authenticated";
                    $variables['theme_hook_suggestions'][] = $suggest;
                }
                else
                {
                        $suggest ="page__node__test_notAuthenticated";
                        $variables['theme_hook_suggestions'][] = $suggest;
                }

         }

    }
}

```

and now create two node pages in the same way I said, one for authenticated and one for non-Authenticated users. you can also get and set fields of your content type fields in preprocess function and display them in node page. don't forget to clear the chache
> -1 votes

---
Tags: views, nodes, entities
---


# Question
Title: Correct way to import an RSS feed and display it in a view?
I have an rss feed (facebook) (can also be output as a json). I want to import the RSS feed and have it display using a view.

I already have the Feeds module installed and the Feeds: Facebook Parser installed. I think I have everything I need but I can't figure out how put it together. Seems like this is a common need just not sure how to put the pieces together to make it happen.

# Answer
> 5 votes
The proper way to import an RSS feed and have its data displayed in a view is by creating nodes from the feed data. This is what the Feeds module accomplishes.

You will need to define two content types: one to be used by the feed importer (ex. "Facebook Feed Importer") and one for the feed items themselves (ex. "Facebook Feed Item"). In the feeds importer:

* Under Basic settings, attach the feed to the Facebook Feed Importer content type.
* Set the node processor bundle to Facebook Feed Item.
* Map the fields.

See this tutorial for more details in setting up the importer. If you have troubles using the Feeds: Facebook Parser, give the Feeds JSONPath Parser a try.

Once you have everything configured correctly, make a new Facebook Feed Importer node, enter in the feed URL, and save the node. View this node and click import. The RSS data should be imported as Facebook Feed Item nodes. If you get errors, or 0 nodes created, you probably have an issue with your mappings or importer configuration.

By importing the feed data into your website as nodes you have more flexibility in how you can display this information to the user. Instead of having one large string of data for a feed item, you have a node containing fields for each part of the feed item which can then be customized in your views or anywhere else on your site however is required.

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


# Question
Title: What are the replacement patterns or tokens for Profile2 URL of a particular user?
I just need to know how to key in token replacements for any given users different profiles. In my projects a user can have multiple profiles associated with the account. I am just having problems with tokens on how to locate or recreate those urls.

# Answer
> 0 votes
Try like this

1. First Install **Pathauto Module**.
2. Login in drupal as administrator, and goto **Configuration.** Under **'SEARCH AND METADATA'** select **'URL aliases'**.
3. Select **'Pattern'** tab and goto **'USER PATHS'** and click on **'REPLACEMENT PATTERNS'** a list will appear.
4. Select **'Users'** and again some more option will be displayed, select 'name' and the '**pattern for user account page paths** should be displayed as **'\[user:name\]'** and save it.
5. In the same window **'Bulk update'** tab and check mark the **User Paths** and click **Update**.

The following output will be http://example.com/username.

# Answer
> 0 votes
Old question, but since it's still unanswered...

This is still a lingering issue in the Profile2 issue queue. As yet, there's no official module that lets you use tokens with Profile2. mohit\_rocks answer really only applies to the core profile module AFAIK.

To get custom URLs without token, you can simple create a profile, export it, edit the URL in the export, and then import it.

Details here: https://drupal.org/node/1054740 (response #1) And here: https://drupal.org/node/1149636#comment-5320062

That second thread mentions a sandbox project that " is a quick-and-dirty integration between Pathauto and all the entity types that have an Entity URI." See https://drupal.org/sandbox/damz/1332096

And having written all that up, I just saw there's a similar answer here: Profile2, url rewrite

---
Tags: tokens, users
---


# Question
Title: Send a mail automatically with content/attachment using webform using rules
In Drupal 7 a want people to fill in a webform with their email/tel/etc..and finally can choose some options. When the submit the form, I want them to get automaticcaly more information about the chosen options, by sending automaticly a pdf by mail or permission to some content. Rather not with subscribing, also anonymous users. Is this possible with rules and webform (I also installed webform rules). When you need more information just let me know.

Thanks very much in advance!!!

Pieter-Jan Derks Holland

# Answer
Pieter - I think this answer can be helpful. You would use MIME mail to add attachments and send rich emails.
> 1 votes

---
Tags: rules, webforms, emails
---


# Question
Title: Theme mobile optimization and upgrade suggestions
I am running a medium trafficked Drupal 6 site with some custom modules, theme and a few thousand nodes. Our major woe is optimizing the site for different media displays or just responsify the current custom theme, and perhaps upgrade to Drupal 7 along the way.

What do you suggest about the following pathways?

1. Should I not worry about upgrading to Drupal 7, create a seperate jQuery mobile site and separate the mobile traffic to m.domain.com using domain module? It is very challenging to make themes responsive in Drupal 6.
2. Upgrade to Drupal 7, recode the theme to be responsive. But by the finish line, Drupal 8 would have matured enough. Should I even bother to upgrade to Drupal 7?
3. Wait for Drupal 8 release

Which one would you choose and why? Or any other optimal suggestions?

Cheers \[raises a pint of IPA\]

# Answer
> 0 votes
Mobile developing for D6 shouldn't be any harder than for D7. Actually, i remember that when i was building my last responsive website, there were a few useful modules only available for D6.

D8 much probably won't be out before 2014, and after the official release, it's going to take many months before all the themes and modules will get ported... many people may not be able to use D8 until 2015 or so. Probably.

It will be indeed much more mobile friendly, so it might be well worth the effort of porting.

But I don't really see the need to port to D7 at the moment.

Whether to make a separate site on a subdomain or a single responsive site is a very subjective question. Anyway, mobile\_tools will probably have everything you need for both scenarios: https://drupal.org/project/mobile\_tools

---
Tags: theming, javascript
---


title: Superfish - No output

text:
# Question
Title: Superfish - No output
Hi I can't get Superfish to output anything in Drupal 7 Zen Starterkit Sub Theme

I've done everything : Installed the Module For Superfish, Libraries, and jQuery Update, I've installed the Superfish Library, created a Menu, called the Menu in Superfish Module, but no output.

I've tried putting in snippets of code in the page.tpl to call the Superfish menu, but they only caused errors.

Please help.

View here http://www.cambrianvacation.co.uk/safeside

Ant:-)

# Answer
First off, super fish module doesn't require the jquery update module so uninstall it. It's a PIA module if you don't need it. Second, in the superfish settings, set it to render 1 block. Go to the blocks and find the super fish block. Edit that block and set it for whatever menu you would like to use it for and place it in a region.
> 0 votes

---
Tags: 7, navigation
---


title: Location proximity search using API

text:
# Question
Title: Location proximity search using API
I have a small number of location nodes with geofields, and need to programmatically get the distance between a location and a zip code. It would be ideal if I could get a query, or a sort, of my location nodes by proximity to the zip code. I couldn't easily tell how to do this in the geoPHP module.

# Answer
> 3 votes
In short : Use the Location Distance field in Views.

In detail : Check out the video http://www.youtube.com/watch?v=AxeskzN8BAc

---
Tags: 7, location
---


# Question
Title: Is there a module for tracking changes to a Drupal site's configuration?
I want to create a simple system for tracking changes to my Drupal configurations and knowing which modules are used by some configuration settings is crucial, but will be happy to use an existing one if it is good enough. Is there a module that implements this?

# Answer
I think you are looking for Configuration Management module.

> The module knows where configuration was changed and allows users to either "activate" a configuration that was changed in the datastore, or "write" to datastore if a configuration was changed in the activestore. If you enable the diff module, you can see the what is in the activestore vs. datastore.

and I'm not using this module before.
> 8 votes

# Answer
I would be surprised if such a module exists in Drupal 7 - "Features" and "Configuration manager" (see Bala's answer) can warn you (diff) if a particular variable, node structure, view etc. changed. They cannot really tell you who changed it and when following a course of action (they dont store user and timestamp info) - which I would consider true tracking and very valuable piece of information.

I say I would be surprised because I recently looked into hooking into variable\_set and realized there is no module\_invoke\_all - thus you cannot hook into it - thus your module cannot interact with variable\_set.
> 1 votes

---
Tags: 7, configuration
---


# Question
Title: Redirecting the home page to index.php, not index.html
I have an index.html file in the server root directory.

When users browse the domain, the index.html page should come first. In that index.html, I have created a link like **enter website** that links to index.php present in the server root directory to enter the Drupal site. When I click on the **Home menu** link, it automatically redirects to index.html; I need it to redirect to index.php.

# Answer
> 2 votes
Why use separate index files when you can use a *splash screen*:

> We define a splash page as being content that shows up at a specified interval, at a specified location, one time. If someone goes to a certain page for the first time, we want to make sure the splash content shows up. But if the person is coming from an internal link on the site, we don't want the splash content to show up over and over again (otherwise, the splash page would become a nuisance).

These modules implement the flash features in a Drupal site:

1. For D6 : https://drupal.org/project/splash
2. For D7 : https://drupal.org/project/splashify

---
Tags: uri
---


# Question
Title: Create a node Programmatically having Composed Field
I have a content type having composed filed (used Composed Field module for this).

How can I create a node programmatically with composed field values?

# Answer
Consider with this example you created a field as contact with two subfields as mobile(textfield) and home(textfield).

so while creating the node pro grammatically you just have to assign the array of your input to the field,something like below

```
$contact = array("mobile"=>"1234565","home"=>"789");
$node->field_contact[$node->language][0]['composed'] = $contact;

```

I have not shared the node\_save() as you have mentioned you are able to make it.
> 2 votes

# Answer
In theory the same principle should be applied. Can you try using "Devel" module, to see the structure of the "composed" node and then try to copy (structure) in the new node.

For example, Drupal Commons has "organic group" reference field. "og\_ref". you can try..

```
$node = new stdClass();
$node->composed_field (copy structure from Devel).

```

Regards

Regards.
> 0 votes

---
Tags: 7, entities, nodes
---


# Question
Title: Managed to delete Event_Calendar_Status and cannot reinstate
When trying to get rid of notification emails every time I create a calendar event, I have managed to delete the ?built-in? event calendar status term. I have tried to reinstate it but machine will not allow the same name as original. It's causing an undefined index Notice which will not now let me save any new events.

Have not got much stuff on the site yet, so may have to disable, uninstall and reinstall the calendar module?

This appears when creating new calendar event: Notice: Undefined index: event\_calendar\_status in event\_calendar\_form\_alter() (line 293 of web1/user47631/website/sites/all/modules/ event\_calendar/event\_calendar.module)

Grateful for any help or suggestions...

Cynthia

# Answer
I have not checked the module, but here are few things I can suggest take a database backup before you take any step.Uninstalling calendar module should be not helpful, as it seems settings to be changed in event\_calendar module.

How you deleted the status term,did you make any direct changes to database?can you revert back those changes? You can setup event\_calendar module on fresh drupal installation to track what changes can be done to make it work.

Not sure, but keep uninstalling and reinstalling event\_calendar module as last option.

I guess event\_calendar provides UI for mailing notifications settings, as the project page says

> This module also gives an Admin UI to change status (approval/denied) of events and a mailing system.
> 0 votes

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


# Question
Title: $GLOBALS['user']->uid returns same uid for different logged in users?
I'm implementing hook\_menu in my custom module. Implementation works fine except, it turns out that $GLOBALS\['user'\]-\>uid returns **always same value no matter which user is currently logged in**. Sounds absurd! What could be the problem?

Below is a full hook\_menu:

```
function my_tab_menu(){

    $current_user_id = $GLOBALS['user']->uid;  // $current_user_id=202 for each

    $query = new EntityFieldQuery();
        $result = $query
                ->entityCondition('entity_type', 'node')
                ->entityCondition('bundle', 'profile')
                ->propertyCondition('status', 1)
                ->propertyCondition('uid', $current_user_id)
                ->propertyOrderBy('created', 'DESC')
                ->range(0,1)
                ->execute();

    if (isset($result['node'])) {
        return array(
        'user/%/alumni-spotlight' => array(
                'title' => 'Alumni spotlight',
                'page callback' => 'user_tab_page',
                'page arguments' => array(1,$result['node'],$current_user_id),
                'access callback' => 'user_tab_access',
                'access arguments' => array(1),
                'type' => MENU_LOCAL_TASK,
            ),
           );
    }
}

```

# Answer
> 7 votes
Hook menu is not for non-menu functionality.

Using %user in the menu item will call user\_load() with whatever is in that part of the url (in this case the uid) and then when that part of the url is used in callback or access arguments it will pass in the loaded user object instead of the user id.

See wildcard loader arguments for more info on that.

To control who sees the tab, do your database check in the access control callback and deny access if there is no result. This way the tab will only show if there is a node.

Callbacks like the access control call back and the title callback run every time, not just when the cache is refreshed, so it is ok to use them in this way.

Try

```
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items = array();

  $items['user/%user/alumni-spotlight'] = array(
    'title' => t('Alumni spotlight'),
    'page callback' => 'MYMODULE_user_tab_page',
    'page arguments' => array(1),
    'access callback' => 'MYMODULE_user_tab_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
 * Access callback for user alumni spotlight page.
 */
function MYMODULE_user_tab_access($user) {
  // Do something here to check access & return TRUE or FALSE to grant access or not.
  $query = new EntityFieldQuery();
  $result = $query
    ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'profile')
    ->propertyCondition('status', 1)
    ->propertyCondition('uid', $user->id)
    ->propertyOrderBy('created', 'DESC')
    ->range(0, 1)
    ->execute();

  // If there is a node, allow the user to access the page.
  if (isset($result['node'])) {
    return TRUE;
  }

  // If there is no node, deny access.
  return FALSE;
}

/**
 * Page callback for user alumni spotlight page.
 */
function MYMODULE_user_tab_page($user) {
  // Return the content of the page.
}

```

# Answer
> 3 votes
As I can see from your hook\_menu implementation, you're trying to add a tab on the user page if the user published at least one content of type 'profile'. And inside this tab you want to show the latest 'profile' the user has published.

Your implementation is wrong. First, for the reason that the other answers also mention, hook\_menu will be cached. Second, you shouldn't do the logic in hook\_menu, but in the page or access callback functions.

However, there is also another way to get what you want to achieve, using Views.

### Using hook\_menu:

```
function my_tab_menu() {
  return array(
    'user/%/alumni-spotlight' => array(
      'title' => 'Alumni spotlight',
      'page callback' => 'user_tab_page',
      'page arguments' => array(1),
      'access callback' => 'user_tab_access',
      'access arguments' => array(1),
      'type' => MENU_LOCAL_TASK,
    ),
  );
}

```

This way you register a menu item, that can be cached. In the page callback you can do the query and show the content. Note that, even if you don't want to show the menu item if there is no result, you should register it with hook\_menu. With 'access callback' function you can decide where to show or not.

### Using Views

1. Create a View page and give it a path `user/%/alumni-spotlight`, show fields
2. Items to display: 1, no pager.
3. Set Menu: Menu Tab
4. Add relationship: 'Content: Author'
5. Add filter: 'User: Current', select relationship 'author', is the logged in user: 'yes'

# Answer
> 0 votes
Can you try using

```
global $user;
$uid = $user->uid;

```

Regards\`

# Answer
> 0 votes
Try using cache\_clear\_all() above the global $user. This will clear the cache and the present uid can be obtained.

Note : I have not tried this hook before.

---
Tags: users
---


# Question
Title: How to pass node queue id in views contextual filters
I a list of node queues and nodes associated with them. Now I have created a block using views. This block should list the nodes in a specific node queue based on the node queue id.

I have used node id in contextual filters, but not sure how to use node queue's id in contextual filter.

Any help would be widely appreciated.

# Answer
> 2 votes
You can give a try to nodequeue\_extras module

> Provides 2 pieces of helper functionality specific to Nodequeue and Views:
>
> 1. Contextual nodequeue edit links for views that include a nodequeue relationship.
> 2. A special Views nodequeue relationship and subqueue argument that let you build views based on a subqueue without requiring that all result nodes in the view exist in the subqueue.

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


title: Custom PHP code before a site is loaded

text:
# Question
Title: Custom PHP code before a site is loaded
I need to **execute a few lines of PHP code before a page is rendered**. Basically what I need to do is to store in a database the user's original http\_referer together with an anonymous visitID, and save this visitID in a session. So the code i need to execute is something like this:

```
if(!isset($_SESSION['lock'])) { // we only want this to run when the user enters the site, not on subsequent pages
   $_SESSION['lock'] = true;
   save_http_referer_in_database();
   $_SESSION['visitID'] = mysql_insert_id(); // gets the id of the last inserted row
}

```

I've found a few solutions but not very convincing. **UPDATE 16th Oct: I'm making a short summary here as I've edited this post many many times.**

* First, I tried putting the required code at the top of **html.tpl.php**... it works, but *stops running if i enable caching*. Not good. I don't want to disable caching.
* I tried putting the code in the **settings.php and index.php**, but drupal's session aren't initialized yet in there.
* As suggested here, I've tried creating a custom module implementing **hook\_boot**, but this solution has weird problems when caching is enabled. What happens is that the **save\_http\_referer\_in\_database()** function correctly runs the first time, but when the user loads another page, it runs again! All the subsequent page loads don't trigger it again though. This post has some more informations about it. This bug report on Drupal.org shows some other bad things that happen with sessions and caching and hook\_boot()
* **SOLUTION:** Use cookies instead of sessions.

Regarding @znerol's answer:

* I wouldn't have DB problems anyway because i save visitID and referer in another database, so i manually db\_connect() to my database and manually run mysql\_query(). Hopefully it's not a bad thing.
* How could exposing the visitID to the user create problems? The visitID is a completely anonymous ID, generated by MySql as the Auto Increment column of the table containing the http\_referers. I can't imagine how someone could use this ID to do something 'bad'.
* The reason why I want to do it inside my application, is that I need the visitID to "connect" certain actions on my site to the http\_referer (through the visit\_id foreign key). So basically i have a structure like this:

VISITS (visitID, http\_referer) EVENTS (eventID, event\_description, fk\_visitID)

When an event is triggered, I add it to the database by fetching the fk\_visitID from the cookie (or session)

I couldn't find a way to accomplish that through AWSTATS (which is installed) or Google Analytics or other similar software.

I didn't know Piwik but thanks to the API it might be fine for what I need, right?

# Answer
There are a couple of answers for this question because there are multiple problems involved.

## 1. $\_SESSION and page cache cannot coexist

You probably noted the call to drupal\_bootstrap(DRUPAL\_BOOTSTRAP\_FULL); in `index.php`. This function essentially calls the following functions in exactly that order:

```
// 1. Run settings.php
_drupal_bootstrap_configuration();
// 2. Call `hook_boot` and attempt to deliver page from cache. Exit if successful.
_drupal_bootstrap_page_cache();
// 3. Connect to the database
_drupal_bootstrap_database();
// 4. Load the variables table (think initialize `variable_get`)
_drupal_bootstrap_variables();
// 5. Load the session and populate `$_SESSION`
drupal_session_initialize();
// 6. Invoke `hook_boot` (For pages not served by the cache)
_drupal_bootstrap_page_header();
// 7. Prepare for multilingual sites
drupal_language_initialize();
// 8. Load all modules and build the page
_drupal_bootstrap_full();

```

Note that `_drupal_bootstrap_page_cache` is called before the session is initialized. Therefore when delivering a page from the cache, `$_SESSION` is simply not yet defined when `hook_boot` is called.

Even more important is that `_drupal_bootstrap_page_cache` does not attempt to deliver a page from the cache when it detects a session-cookie on the request.

Page caching is mutually exclusive to having a session open in drupal core.

## 2. Use your own cookie for the visit-ID

As suggested by others, you may set your own cookie to track visits and http\_referer. You can use `hook_boot` in this case and implement something like this:

```
if (!isset($_COOKIE['visitid'])) {
    $params = session_get_cookie_params();
    $visitid = save_http_referer_in_database_and_return_visit_id();
    $expire = 0; /* remove when browser window closes */
    setcookie('visitid', $visitid, $expire, $params['path'], $params['domain']);
}

```

Recalling the bootstrapping order, one might argue that the database may not be ready when `hook_boot` is called and therefore `save_http_referer_in_database_and_return_visit_id` would fail. However unless the setting `page_cache_without_database` is set to true in `settings.php`, `_drupal_bootstrap_page_cache` will make sure that the database connection exists before `hook_boot` is called.

The solution presented has the problem that the visit-id will be exposed to the client. That said, it should better be something which is not predictable (i.e. no serial number but some randomly generated unique id for example).

## 3. (Offtopic): Use third party web analytic software

Even the good old AWStats is capable of presenting metrics about HTTP referrers with the additional benefit, that no database inserts are necessary for delivering cached pages. Another good option is Piwik which also exposes an API where you could fetch exactly the metrics you need.
> 2 votes

# Answer
hook\_boot runs on every page, even on cached pages. Implement it in a custom module.

Generally it's better to not require code to run on cached pages, but that's the best option you have, as opposed to hacking index.php. The primary problem I see with depending on hook\_boot, is that you open your self up to a very simple denial of service attack. Anyone with curl and a shell can potentially bring your site down with much less resources when caching isn't used well.

One option to consider it relying on javascript to make a call the site via ajax. That way you can save yourself quite a bit of load on the server.
> 5 votes

# Answer
I guess you can implement hook\_boot() in your custom module.

> Perform setup tasks for all page requests.
>
> This hook is run at the beginning of the page request. It is typically used to set up global parameters that are needed later in the request. Perform setup tasks for all page requests.
>
> This hook is run at the beginning of the page request. It is typically used to set up global parameters that are needed later in the request.
> 1 votes

# Answer
I'd use `hook_init` in a custom module.

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_init/7
> 0 votes

# Answer
You can use drupal Rules module.

Create a new rule:

1. add a title
2. React on event "Drupal is initializing"
3. add your condition
4. add your action in php format.

Here is an export of that rule.

```

{ "rules_run_session_query" : {
    "LABEL" : "Run session query",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "php", "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "php_eval" : { "code" : "if ( isset($some_value) ) {\r\nreturn TURE;\r\n} \r\nelse {\r\nreturn FALSE;\r\n}" } }
    ],
    "DO" : [ { "php_eval" : { "code" : "\/\/ Do your query here." } } ]
  }
}

```
> 0 votes

---
Tags: hooks
---


# Question
Title: Display Taxonomy Terms Based on user login in a select list in a view
I have created a view with taxonomy term as filter criteria.

I want to display values of taxonomy terms based on the user logged in(i.e. I want to display only the terms which are created by that user alone) in that select list.

Any help will be really appreciated.

# Answer
> 2 votes
There is no way you can get the author uid of taxonomy term. But here is a solution you can try:

* Add a user reference field to the vocabulary, the field will contain author uid.
* Add term exposed filter to the view.
* Using hook\_form\_alter() alter the exposed filter so that it shows only those taxonomy terms which are created by the currently logged in user.

# Answer
> 0 votes
As mentioned by subhojit777, its not possible to get the author uid of the taxonomy term. But you can customize that options by getting all the nodes of that particular user and all the terms used in that particular node.

There are more than one proper way to do it. But the following way is simple and will not have more db call.

So you can try the following in your hook\_form\_alter,

```
$options = array();
// Get term defined by current user
$nids_result = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('n.uid', $uid, '=')
    ->execute()
    ->fetchAll();

foreach ($nids_result as $nid_obj) {

    $terms_result = db_select('taxonomy_index', 'ti')
        ->fields('ti')
        ->condition('ti.nid', $nid_obj->nid, '=')
        ->execute()
        ->fetchAll();

    foreach ($terms_result as $term_obj) {
            // Check if the term value is not from any other vocabulary that node is using
        if (isset($form['taxonomy_category_tid']['#options'][$term_obj->tid])) {

            $options[$term_obj->tid] = $form['taxonomy_category_tid']['#options'][$term_obj->tid];
        }
    }
}
$options = array_unique($options);

$form['taxonomy_category_tid']['#options'] = $options;

```

\*taxonomy\_category\_tid\* is the taxonomy field id as in form element.

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


# Question
Title: Tracking number of attempts via Form API
I'd like to track the number of times a user has failed a form validation.

It doesn't necessarily matter if the end user has access to the variable, or even the ability to manipulate it client side, as the purpose is to provide additional help to the user by detecting when they might not be in trouble.

At this point I think I'm leaning towards adding a hidden field and incrementing that value, but I'm interested to know if there's a cleaner method that does prevent access and manipulation in my quest for knowledge :)

Thanks for any advice.

**UPDATE**

As per tunic's advice below, I'm trying the `$form_state` route but this doesn't appear to be persisting. In my form validation function I have:

```
// Track the number of attempts.
if (!isset($form_state['mymodule']['attempts'])) {
  drupal_set_message('attempts not set');
  $form_state['mymodule']['attempts'] = 0;
}
$form_state['mymodule']['attempts']++;
drupal_set_message($form_state['mymodule']['attempts'] . ' attempts');

```

However repeatedly submitting a form with errors results in the following output each time:

```
attempts not set
1 attempts

```

**SOLUTION**

Having difficulty arguing with `$form_state` I instead went for the core flood module as suggested below, with the following code, in my validator:

```
function mymodule_booking_register_online_form_validate($form, &$form_state) {
  if (form_get_errors()) {
    form_set_error('', 'There was a problem registering your online account, please try again.');
    flood_register_event('mymodule_booking_register');
  }
}

```

And then to handle the result of this event, back in my form definition:

```
function mymodule_booking_register_online_form($form, &$form_state) {
  if (flood_is_allowed('mymodule_booking_register', 5, 3600)) {
    ...
  else {
    drupal_set_message('You have incorrectly entered your personal details too many times. Please call us on 12345678 to ask for your user code and then enter it in the form below.');
    ...
  }
}

```

# Answer
> 3 votes
How about using drupal 'floding mechanism' for login attempts ,so using flood\_register\_event() to have entry for custom event in flood table,but might be too overkill !

A better picture can be seen inside `user_login_authenticate_validate()` in user.module

# Answer
> 5 votes
Just use a variable insider $form\_state.

In validate function

```
if ($validation_failed) {
  $form_state['error_count']++
  $form_state['cache'] = TRUE;
}

```

Then, in your form function just check $form\_state\['error\_count'\].

$form\_state will be persistent between page petitions while validation fails thanks to $form\_state\['cache'\].

You can also check for errors using form\_get\_errors().

---
Tags: 7, forms
---


# Question
Title: How to change path of public files Drupal
Public files in Drupal have a relative path that is similar to /sites/default/files/file.txt; private files have a relative path similar to /sites/default/files/privates and system files have a relative path similar to /system/files/file.txt.

How can I make the relative path for public files be /public/files/file.txt?

# Answer
> 1 votes
You can change the path using below step.

* Go to Administration -\> Configuration -\> Media
* Click on 'File system' link
* Change the directory in text-field 'Public file system path' and save the configuration.

# Answer
> 1 votes
I think that what you are looking for is similar to How to hide /sites/default/files from URLs? In that case, try the File Aliases module.

> The File Aliases module allows you to use token customizable aliases for your uploaded files, giving you the ability to keep your file system organized as per usual while providing clean looking paths (i.e., no more '/sites/default/files/').
>
> ### Features:
>
> * Customizable File Alias field using Node tokens. Support for:
>     + Drupal core Upload module.
>     + FileField module.
>     + ImageField module.
>     + Image module.
>     + Comment Upload module.
> * Support for Private and Public file systems.
> * Support for Views output (Fields and Nodes).
> * Support for FileField Paths Retroactive and Active Updating.

---
Tags: files
---


# Question
Title: Views: How to display the title and breadcrumb from taxonomy terms in URL?
I have a Page display in a View. The page url is `taxonomy/term/xx` and I am trying to display the term as the page title and the breadcrumb.

I have tried to set the term as an argument `Content: Has taxonomy term ID` with the following settings, I checked `Set the breadcrumb for the term parents` but it did not work. Can someone help?

# Answer
> 2 votes
By default, taxonomy terms default view is disabled so you can enable it and see how it is working with the contextual filter.

You need to Configure contextual filter: Content: Has taxonomy term ID (with depth)

# Answer
> 0 votes
Check "Override title" and "Override breadcrumb" checkboxes on your screenshot and use "%1" for the first argument, "%2" for the second, etc.

For example you can specify "Article %1" and "%1" will be replaced by the name of taxonomy term.

---
Tags: views
---


# Question
Title: Use a database specific function in dbtng (e.g. uuid in db_insert)
I have a table that contains a char(36) field for a uuid. It seems like I can insert data into that field with a mysql query like: `INSERT INTO mytable (uid, event_guid) VALUES (1, uuid());`. I'd like to make a query like that in *DBTNG* syntax, but I believe I will just insert the string "uuid()" into the column.

```
db_insert('mytable')
  ->fields(array('uid' => $uid, 'event_guid' => 'uuid()'))
  ->execute();

```

So...do I just use db\_query? Is there some magic in dbtng to handle this?

# Answer
Here's what I ultimately did:

```
db_query("INSERT INTO {mytable} (uid, event_guid) VALUES (:uid, uuid())",
array(':uid' => $uid));

```

And that works to use the mysql uuid() function in an insert.

I've created an issue to add this to Drupal 8 http://drupal.org/node/1858188
> 2 votes

# Answer
```
            $uuid = db_query("SELECT uuid() AS uuid ")->fetchField();

            db_insert('mytable')
            ->fields(array('uid' => $uid, 'event_guid' => $uuid))
            ->execute();

```

A workaround to the problem.
> 1 votes

# Answer
You can use function calls in the fields array. The following code should just work:

```
db_insert('mytable')
  ->fields(array('uid' => $uid, 'event_guid' => uuid()))
  ->execute();

```

If you wanted to insert multiple entries in a loop something like this would work:

```
$event_guid = uuid();
foreach($entries as $entry) {
  $entry['event_guid'] = $event_guid;
  db_insert('mytable')
    ->fields($entry)
    ->execute();
}

```
> -1 votes

---
Tags: 7, database
---


title: Integrate Switchtheme with Context?

text:
# Question
Title: Integrate Switchtheme with Context?
Im using Switchtheme to allow users to switch the theme of my site. Im also using Context and id like to create a new context depending on what theme has been chosen, but I cant see any options for this in the UI.

# Answer
Actually, bit of searching and here you go: Context Condition Theme

> This module will add a conditional check within context for themes. Ever had the need to load a context based on which theme is being rendered?
> 1 votes

---
Tags: 7
---


title: entityform submit handler with preview

text:
# Question
Title: entityform submit handler with preview
I have a simple Entity Form and have added a custom submit handler:

```
$form['actions']['submit']['#submit'] = array('custom_submit','entityform_edit_form_submit');

```

That works very well. The problem is when I enable form preview before submission. My `custom_submit` function runs before preview is generated and not after it was confirmed.

How do I get it to run after form has been confirmed in preview?

```
$form['#submit']  = array(
    'custom_submit',
    'entityform_edit_form_submit'
);

```

does not work at all.

# Answer
> 1 votes
So this is what I found entityform module does. If preview is enabled it set `$form['review']`. All of my forms will have that preview set so what I did is simply:

```
//check if form is in preview mode and if it is then it adds my custom handler.
if(isset($form['review'])) {
    $form['actions']['submit']['#submit'][] ='custom_submit'
}

```

# Answer
> 0 votes
You should add your submit handler to the end of the array like so:

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

```

---
Tags: 7, forms, entities
---


# Question
Title: Installed base them NineSixty - where is it?
I've installed the base theme NineSixty using the URL method without any errors. When I then look for the files I can't find them anywhere. I've looked in the themes directory as well as the sites/all/themes directories. In fact i've looked everywhere.

Where do the base theme's files end up?

# Answer
> 1 votes
If you have access to the database, check the "system" table of your drupal database and look for a record with the "name" ninesixty. That row will also tell you the path to the theme.

If you have phpmyadmin via cpanel or something similar you can just browse the system table.

Otherwise you could use this SQL (if your database is using a prefix it will be slightly different a the prefix will be appended to the table name "system"):

```
SELECT * FROM system WHERE name = 'ninesixty';

```

and that will give you all the info about your ninesixty theme.

Another way is to search your file system for the word ninesixty, which I imagine won't be anywhere except for the theme and maybe your base theme.

---
Tags: theming, installation
---


# Question
Title: How can I override a link in the language menu?
I'm using the i18n module and Views. I have a separate view for each language and the language menu obviously doesn't line up for each of those views. I want to be able to adjust the links for the language menu when I'm on each of those view pages so they map to the corresponding view in the other language?

Where/how would I adjust those links? Would it be something in the template.php file for the theme or should I do it in a custom module?

# Answer
I'm certain there is a better way to do it than this...it's a little brute-force, but it gets the job done for me:

```
function THEME_preprocess_page(&$variables) {
  $markup = $variables['page']['my_region']['locale_language']['#markup'];

  // Do some string replaces on $markup to adjust the URLs

  $variables['page']['my_region']['locale_language']['#markup'] = $markup;
}

```

I know this isn't the Drupal way to do this. Part of the problem is that I only need to adjust the language links on a few Views pages, so figuring out how to do this in hook\_menu\_alter or in a module was too complicated...I needed a quick solution.

I'm hoping someone can pos the Drupal way of achieving this.
> 0 votes

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


# Question
Title: Add block with taxonomy terms in intergrated View Taxonomy term
I'm using one content type that has taxonomy terms. With default view "taxonomy term" that comes with Views 3, I've managed to display the content with taxonomy terms in different menu pages based on taxonomy terms.

Now I want to add a block that will use the same terms, with one more field that will be different and will appear over the taxonomy term content.

EDIT

When I add the block into the default taxonomy term view and activating it into structure -\> blocks in content region, it's not rendering in the pages.

Do I have to change something in the views block?

I'm using Drupal 7.

# Answer
> 0 votes
After lots of searching and tweaking the views, finally I've found the solution and I'll post it here, so might be useful for someone.

Since a blocks are little "dumb" and it doesn't possess a path it is necessary to do a bit more configuration to achieve the result. So, here the solution:

Click on the contextual filter on the block view form in views. Under "When the filter value is NOT available" select "Provide default value"

IF the page in the path is a taxonomy term Choose "Taxonomy term ID from URL" from the Type drop-down box and check "Load default filter from term page". That's all. :)

# Answer
> 0 votes
Seems your problem in argument. If you want display content by term id, you should use term id as argument in your views display. You can use "contextual filters" and "Argument input" from context.

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


title: Add a variable to custom views template

text:
# Question
Title: Add a variable to custom views template
I have created a view that is grouped by taxonomy term and it displays exactly how I want it. But what I need to do is add the term ID that the view is grouped by as a class, I have the following custom views template created but the term ID is not available as a variable to use.

The template is `views-view-unformatted--products.tpl.php` where I have printed the title as the class of the wrapper I need to add the term ID instead (the title is actually the term name as this is what the view is grouped by.)

```
<div class=<?php print '$title)'; ?>>
  <?php if (!empty($title)): ?>
    <h3 class="quick-view-closed"><?php print $title; ?></h3>
  <?php endif; ?>
  <div class="product-list" hidden>
    <?php foreach ($rows as $id => $row): ?>
      <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
        <?php print $row; ?>
      </div>
    <?php endforeach; ?>
  </div>
</div>

```

# Answer
What I had to do is use the term ID to group the results of the view and then in the views template use the function `taxonomy_term_load()` and then render the template as below.

```
<?php $binder_title = taxonomy_term_load($title); ?>
<div class=<?php print '"binder binder-' . $title . '"'; ?>>
  <?php if (!empty($title)): ?>
    <h3 class="quick-view-closed"><?php print $binder_title->name; ?></h3>
  <?php endif; ?>
  <div class="product-list" hidden>
    <?php foreach ($rows as $id => $row): ?>
      <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
        <?php print $row; ?>
      </div>
    <?php endforeach; ?>
  </div>
</div>

```
> 2 votes

# Answer
I haven't time to actually investigate the details of this right now, but if you enable the devel module, put

```
<?php dpm(get_defined_vars()); ?>

```

somewhere in your template file somewhere, and then refresh the page twice you will get a list of available variables which you can then click on to expand and drill down into the arrays and objects.

If you still cannot find the tid anywhere to use, try adding the tid as a hidden field to your view, then it will definitely be in there somewhere for you to use.
> 2 votes

---
Tags: views, theming
---


# Question
Title: Why is the 'time ago' not displayed in my view?
I'm not sure whether this is a bug or not, so I'm just going to ask this. I created a view (and block) with a 'Comment: Post date' field with 'Time ago (with "ago" appended)' as Date format. I didn't fill in a custom date format.

Everything is previewed perfectly, but when I go to my dashboard, I only see the "ago": the actual numbers (hours, minutes, seconds...) aren't displayed.

I cleared caches, but nothing happened. I'm still using the default Seven 7.23 administration theme for my dashboard and I didn't set a custom template file or anything else. I just created the view.

How can I solve this?

**Edit**: I exported my view, so you can read the code here.

# Answer
I don't know what causes the problem, but I solved it temporally. I changed the Date format to 'Time ago' an added the 'ago' manually via the 'Rewrite results' function.
> 0 votes

---
Tags: 7, views, blocks, dashboard
---


# Question
Title: D7: Get terms from node and display other nodes with same term in block?
I have a node that has terms:

Artist1

And need a block to show all the other nodes that has Artist1 as a term

I tried this solution Display the title of related nodes from taxonomy in block

I set it to "Provide a default argument", and configured that to use the nid of the node being viewed... and nothing

this seems simple but been working at it for hours now.

# Answer
> 1 votes
Try this module - https://drupal.org/project/views\_arguments\_extras This allows you to select a field from the current node as a contextual filter. Enable this module. Create a new view, block display, and the chose the relevant field as the contextual filter. Configure the view as per your requirement and show the block on your node page. It should work.

# Answer
> 0 votes
You need a block view that accepts a term (from your node) as argument. I'm not sure how you'd best pass the term as argument to the view block but here's a possible solution: Passing Arguments to block in 7.x Views

# Answer
> 0 votes
This answer works in Views version 2 or higher. First you need to install Views attach ( http://drupal.org/project/views\_attach ). Please read about Views attach before proceeding further. Views attach is best explained by this video http://mustardseedmedia.com/podcast/episode37

Now we get to Views attach. Please enable the views attach module before proceeding. Essentially `Views attach` attaches a view at the end of the node. In our case our view will be a listing of other articles with the same term.

We will essentially need to "pass" the taxonomy term of the node to the view. Let the name of your Vocabulary be called `MyVocab`.

Steps to make the view.

1. Lets call the view `display_other_articles_with_same_taxonomy`.
2. Add a display of type `Node Content` (available after enabling Views attach). This is a display just like block and page displays but with special ability of attaching itself to the node.

Make the following settings in the `Node Content Display`

```
Node content settings
Node types: [select the content types you are interested in seeing the list of nodes with same taxonomy term]
Build modes: Teaser, Full node
Arguments: token
Show title: No

```

You should select `Use tokens from the node the view is attached to` under Arguments. Let the token be `[term-id]` This is the **"ID of top taxonomy term"**. This is very important!! Essentially you are going to be passing the taxonomy term of the node from the `MyVocab` (See http://groups.drupal.org/node/11788#comment-38332). If it has the lowest weight, the taxonomy vocabulary will be the first vocabulary in the taxonomy section of your node edit form. Add an argument `Taxonomy: Term Id`.

Add the fields you are interested in e.g. `Node: Title`. Make sure the `Node: Title` is made into a hyperlink by ticking `Link this field to its Node`

So what this view is going to do is:

1. Take the taxonomy term from the `MyVocab` vocabulary in the Node that is currently being viewed
2. Pass that as argument to the view `display_other_articles_with_same_taxonomy`
3. List all the nodes that have the same taxonomy term as the node being displayed.

Thats it!

If you're using Views 3 (currently at alpha3 at the time of writing) *and* you want a block (right now the articles have same taxonomy term come at the end of node body) you can do it in the following fashion:

1. Forget about views attach... its not required
2. Add a block view. It should contain the same argument, fields and filters as the instructions above for the `Node Content` display.
3. You need to modify the settings for the argument `Taxononomy: Term Id` just slightly: Under `Action to take if argument is not present:` choose `[x] Provide Default Argument`. Choose `[x] Taxonomy Term ID from URL`. Now make sure `[] Load default argument from term page` is unselected and `[x] Load default argument from node page, thats good for related taxonomy blocks.` Also `[x]Limit terms by vocabulary` and choose the `Series` vocabulary.
4. Make sure you name the block and put it in the appropriate region.

**Note:** This answer is subset of the answer I provided at https://stackoverflow.com/questions/3895213/how-to-just-show-nodequeue-block-on-included-nodes/3909670#3909670 In that scenario the requirement was that the related articles are explicitly selected and listed in a particular order. Its a little more complex and uses Nodequeues which we don't need here at all.

# Answer
> 0 votes
Not advisable, but as an option you can use php codes inside the views contextual filters, code something like below.

Assuming this view block has to be placed with a node, so taking arg(1) as nid.

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

```

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


# Question
Title: Can I just have a color coded HTML editor in Drupal 6 that keeps line indentations?
I'm trying to get out some minimally designed pages. The WYSIWYG (CKEditor) has a habit of collapsing the code between saves. WHile this is fine and all, I'm finding myself copying copy and pasting it into sublime text in order to reformat. The copy-pasting -- while not difficult -- is thumbing me up a bit. I've copied/pasted the wrong code and had to redo a lot of my work.

So can I have stop CKEditor from minimizing the HTML code? This is a legacy site in Drupal 6.28.

# Answer
> 1 votes
Well I got myself halfway there and without the need to download an additional module, library, or plugin. By checking *Apply source formatting* and *Preformatted*, the Disabled Rich Text rendition shows code indented with some of the white spacing preserved.

You can find these settings in D6 via `admin/settings/wysiwyg`

---
Tags: 6, wysiwyg
---


title: Combine subdomains into one domain

text:
# Question
Title: Combine subdomains into one domain
I have main website ABC.com with 5 subdomains on Drupal 6.2

The problems I'm facing are bellow:
1 - It is difficult for user content to migrate across the subdomains. Detail: There are tabs on the top of USER PROFILE page for "My Content" and "My Images". I was hoping that title links for all pages written by that user from all of the subdomains could be listed in that area And also that all images from all subdomains uploaded by that user could go under "my images".

2 - Every time a change is made to the structure of the (site, taxonomy, blocks, configurations etc) the change has to be made on all 5 subdomains.currently we are doning indevidually. Detail: Ideally, most of the administrative tasks should be implemented in a single change. Things like content types, meta tag and post settings, taxonomy. The structure of pages under site building, site configuration, user permissions. All the things that make a site consistent in its look and function.

MAIN WEBSITE - ABC.com
SUB DOMAIN 1 - one.ABC.com
SUB DOMAIN 2 - two.ABC.com
SUB DOMAIN 3 - three.ABC.com
SUB DOMAIN 4 - four.ABC.com
SUB DOMAIN 5 - five.ABC.com

Database Structure:
There is only 1 database for MAIN site plus all 5 Subdomain with total 700+ tables.
MIAN website ie(ABC.com) tables doesnt' have any db\_prefix.
ABC.com tables as follow:
\- access
\- accesslog
\- actions
\- users
.
.
\- vocabulary
\- watchdog

All sub domains have a db\_prefix of subdomain with their table names like:
\- one\_access
\- one\_accesslog
\- one\_actions
\- one\_users
.
.
\- one\_vocabulary
\- one\_watchdog

---

\- two\_access
\- two\_accesslog
\- two\_actions
\- two\_users
.
.
\- two\_vocabulary
\- two\_watchdog
Any help would be appreciated.

Cheers
zafar

# Answer
The Domain Access module was created for exactly the sort of use-case you're describing.

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites such as:
>
> * example.com
> * one.example.com
> * two.example.com
> * my.example.com
> * thisexample.com \<-- can use any domain string
> * example.com:3000 \<-- treats non-standard ports as unique

It'll take a fair amount of work to convert 6 individual sites into a single Domain Access site, but if that's the workflow you're looking for, I don't think you'll find an easier or more complete existing solution.
> 2 votes

---
Tags: multi-sites, subsites
---


# Question
Title: Paginate options in checkbox of a form field
I have a custom form with a field of type checkboxes,options for which I am getting from another function which takes an array as input, do some theming on options value and return options back to form,

Here is how my another function looks like

```
function mymodule_twitter_accounts_as_options($twitter_accounts) {
  $options = array();
  if (is_array($twitter_accounts)) {
    foreach ($twitter_accounts as $twitter_account) {
      $key = $twitter_account->twitter_id;
      $options[$key] = theme('image', array('path' => $twitter_account->profile_image_url)) . mymodule_twitter_account_basic_info_block1($twitter_account) . mymodule_twitter_account_basic_info_block2($twitter_account);
    }
  } return $options;
}

```

The array `$twitter_accounts` is coming from a database query, which is extending drupal pagination but I do not think the extended pagination will be helpful here as I need to show a global pagination for all the options rendered in the form later.

**Edit:**

The reason I am using a form is only because of the reason that once user checks checkboxes and submit the form, I am doing some operations using checkboxes key values, If there is an alternate to use of custom form that will be good too.

# Answer
Might be no one will land up here,still adding the answer and foolish doubts I had

The pagination done for query to get options works! .

The reason I was in doubt before was because of using the query results as option of checkbox field, the time I added themed the pager while rendering the form, I got the pager which worked out of the box!

How I figured out if pagination working with the query was by adding `?page=1` in the url manually which changed the checkboxes , it ensured me I just have to theme the global pager :) .
> 0 votes

---
Tags: paging
---


# Question
Title: How to set Form API's password_confirm in/visible depending on prior select list input?
Neither `visible` nor `invisible` seems to work on `password_confirm`. Am I doing something wrong? What else can I try? This is my current code for a subadministrator form, where I'ld like to display the `password_confirm` only after a user is chosen:

```
$form['user_select'] = array(
  '#type' => 'select',
  '#options' => array('' => '- ' . t('None') . ' -') + _get_users_by_role('Subadministration'),
  '#required' => TRUE,
  '#description' => t('Chose account'),
);

$form['confirm_password'] = array(
  '#type' => 'password_confirm',
  '#required' => TRUE,
  '#description' => t('Type same password in both fields'),
  '#states' => array(
    'invisible' => array(
      ':input[name="user_select"]' => array('value' => ''),
    ),
  ),
);

```

# Answer
A container around the password\_confirm did the trick! Fieldset works too.

```
$form['user_select'] = array(
  '#type' => 'select',
  '#options' => array('' => '- ' . t('None') . ' -') + _get_users_by_role('Subadministration'),
  '#required' => TRUE,
  '#description' => t('Chose account'),
);

$form['pass_wrapper'] = array(
    '#type' => 'container',
    '#states' => array(
      'invisible' => array(
        ':input[name="user_select"]' => array('value' => ''),
      ),
    ),
  );

$form['pass_wrapper']['confirm_password'] = array(
  '#type' => 'password_confirm',
  '#required' => TRUE,
  '#description' => t('Type same password in both fields'),
);

```
> 3 votes

# Answer
is the value ever getting `""`,try the following

```
 'invisible' => array(
   ':input[name="user_select"]' => array('value' => t('None')),
 ),

```
> 0 votes

---
Tags: 7, forms, users
---


title: Rewrite title to download file?

text:
# Question
Title: Rewrite title to download file?
I have a content type with a file field. In a view I am trying to make the title link to the document. So that when someone clicks the title it downloads the file.

In Views for the title field I selected 'output this field as a link' and in 'link-path' I entered \[field\_file\] which is valid.

When I click the title I get a page not found error. `The requested page "/%20the%20file%20name.xlsx" could not be found.`

So it seems it is treating the link as a url link. How can I change this so that it downloads the file?

# Answer
When you added `field_file` in views as a field you should set the **Formatter** to `URL to file` instead of `Generic file`.
> 5 votes

---
Tags: views, files, navigation
---


title: Customize order of a list in Drupal 6

text:
# Question
Title: Customize order of a list in Drupal 6
I have a list of links that are all displayed as one list. They are currently sorted by 'Title' asc.

I would like to customize the order of this list.

How can I do that in Drupal 6.

Example:

* A1
* B1
* C1

But I want instead to have (not sorted or organized in any specific order):

* A1
* C1
* B1

This is my backend interface in Drupal 6:

Thank you for your help! Izumi.

# Answer
> 0 votes
I think draggable views module should be pretty much what you need.

> The DraggableViews module can be used to organize simple lists and complex structures via drag n' drop. The configuration is quite easy as you just have to access the style-plugin settings.

Here's a tutorial. Look specifically at the part that's headed as **Create a sorting interface for views**:

> With DraggableViews you can create a "sorting interface" that will allow users to sort the result of the view using Drupal's built in drag and drop functionality. The simple overview for this is:
>
> * Create a view
> * Create one display that will be the actual list displayed to visitors
> * Create another display that will act as a "sorting interface" and be used to sort the result of the view

Don't forget to set the access parameters for the sorting interface, maybe limit it to specific roles, otherwise anyone can come in and change the order of your lists :P

# Answer
> 0 votes
In your own custom module implement hook\_views\_pre\_render and alter the view's result in the following manner:

```
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'my_view') {
    // for example reverse the result
    $view->result = array_reverse($view->result);
  }
}

```

Use devel module and namely the dpm function to test your code before and after. It is very handy.
Hope this helps.

---
Tags: views
---


# Question
Title: Migrate module: how to handle adding Redirects and rolling back?
I'm writing some migrations using the Migrate module. I need to set up redirects after I migrate in an item, but I'm not sure where to perform that action.

I can do it in the complete() function for the migration, which is called after each object has successfully been inserted. At that point, I'd have enough information to programmatically add a redirect.

However, if I needed to roll back the migration, I don't see where I can put in any clean up code to remove those redirects. There are pre and post rollback functions, but those are called before the entire migration is rolled back.

I suppose one alternative would be to, in a pre rollback, query the map table for all the objects and then lookup and destroy the redirects like that. Seems ugly.

I think the best solution here is to have a pre/post rollback function available on a per-object basis.

Anyone run into this previously or have suggestions?

# Answer
> 1 votes
The redirects associated with the migrated (node) content should be automatically removed during the rollback.

---
Tags: redirection, migrations
---


# Question
Title: Does Drupal have a system for noticing and logging changes to records?
Does Drupal have a system for noticing and logging changes to existing content into a database or a file log? I am interested in something equivalent to database triggers.

I am also interested in Feeds in particular as a lot of the data will be loaded from external sources. Do Feed imports have such a facility?

# Answer
> 1 votes
There is the Track Field Changes module which appears to have little support. And also a -dev version of Node Changes module with many more contributors and more recent updates.

Both modules allow you to track field level changes on Nodes essentially. From Node Changes:

> This module stores the changes of a node into a field attached to comments allowing to display a kind-of activity stream on the node much like on drupal.org issues just with a lot less custom code.

I don't believe either makes use of database triggers.

---
Tags: 7, feeds, rules
---


# Question
Title: replace css on certain pages by another css
I use drupal 6. How do I remove global.css from certain path like cart\* and replace it with another css? I can add for example stylesheets\[all\]\[\] = custom.css inside my theme info file but how to load it only on path cart\* and how to disable global.css on the same path? Thank you

# Answer
> 3 votes
You would need to use your theme to watch for it. You'll need to hook into `preprocess_page` and look for the `global.css` file in the css array and unset it. Below is an example of how to remove the `modules/system/system.css` you'll need to see where in the array `global.css` is and do the same thing. You'll want to wrap that inside of an if for your paths. In this example I use `arg()` to get the first path value (ie cart) and turn it on for that case. You can do what ever you want.

```
function phptemplate_preprocess_page(&$vars)
{
    if(arg(0) == 'cart') {
        $css = $vars['css'];
        unset($css['all']['module']['modules/system/system.css']);
        $vars['styles'] = drupal_get_css($css);
    }
}

```

---
Tags: 6, theming
---