title: Export nodes from Drupal 4?

text:
# Question
Title: Export nodes from Drupal 4?
I am looking into updating a Drupal 4 site. The Node Export module does not seem to have a release suitable for Drupal 4. Can anyone recommend an alternative module or procedure?

The site is running Drupal 4.6.3.

# Answer
> 4 votes
I'm assuming you're on a shared server. Here are some options.

Option 1 - Downgrade PHP. Although it might not be the safest choice, as both the PHP and Drupal is probably no longer supported, you can do the following.

* Some hosts allow to specify a different PHP version in php.ini.
* Rent a cheap VPS, which will allow you to set the PHP version.
* Some shared hosts specialize with older PHP versions, make a switch.

Option 2 - Use backup and migrate modules. There are a number of backup and migrate drupal modules which will make the migrating process easier. This would be a safer choice, but the downside, is that you'll loose your theme and you might have to upgrade to -\>5, -\>6 and only then to -\>7. Here are a few modules to look at

Option 3 - Start from scratch, import in bulk. It's both safe and probably the best choice. Set up a new site and a theme. Export the data from the old site, using feeds, or other Drupal modules and import it into the new site using modules like Migrate.

I would advise to upgrade to D7, since the support for D6, not alone D5, will be dropped soon.

# Answer
> 2 votes
I don't go back as far as 4, but if it's just content you're after, I think you can disable all the modules, then do an upgrade to 5. Once that's working, do an upgrade to 6, then to 7. I think if you're not worried about modules, the upgrades work just fine, or at least this was my experience going from 5 to 6. Unfortunately, I'm a bit ignorant of going 4 to 5.

# Answer
> 0 votes
Even i faced same problem. After trying few export modules, decided to write my own php code to move content from Drupal 4 to Drupal 7. Here i am sharing the link, someone may get some help out of this: http://goo.gl/GPmG9F

> Drupal having a huge support with version 6 \> but no support with 4.X and limited support to 5.x.
> Initially I install few module to import node/content with CSV/XML, but they are not working as expected. I need to import content first which include mainly title, description images (more than one) and attachments (more than 1) for each content. I checked feed, taxanomy csv import, migrate and couple of more but they are able to upload content but not images and attachments. So I thought of writing our own script which will read each node from Drupal 4.x and insert directly into Drupal 7.x database.

---
Tags: upgrading
---


# Question
Title: No results behavior not working when using contextual filter with content id from url
I have a problem displaying the no result behavior. a view gives me an image depending on what page i am on. So i have setup a contextual filter of "content:nid". When the filter is not validated, i add a default value:"content ID from url". When i go to the nodes, the image is shown. Nodes who do not have an image should show my default image that i put in the "no result behavior" section.

The problem now is, that the filter does not validate when there is no image and just shows nothing. How do i get my view to show the "no result" ?

Kind regards

# Answer
Assuming you are working with the default `Article` content type of Drupal 7.x

# **Your Content Type**

You should add something similar to this in your **NO RESULT BEHAVIOUR** of your **IMAGE** field in your **VIEWS**

I'm attaching the exported **VIEWS** code, you can check that, create 2 dummy **ARTICLES** one **with** IMAGE and another **without** an IMAGE but remember to store a **no-result.png** image in your `sites/default/files/styles/thumbnail/public`

# **Views Code**

```
$view = new view();
$view->name = 'preview';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Preview';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Image View';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Field: Content: Image */
$handler->display->display_options['fields']['field_image']['id'] = 'field_image';
$handler->display->display_options['fields']['field_image']['table'] = 'field_data_field_image';
$handler->display->display_options['fields']['field_image']['field'] = 'field_image';
$handler->display->display_options['fields']['field_image']['label'] = '';
$handler->display->display_options['fields']['field_image']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['field_image']['empty'] = '<img src ="../sites/default/files/styles/thumbnail/public/no-result.png" />';
$handler->display->display_options['fields']['field_image']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_image']['settings'] = array(
  'image_style' => '',
  'image_link' => '',
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'preview';

```

Using the above **VIEWS** code you can access the output at `http://<your-host>/preview/<nid>`

Let me know if you face any issues.

Cheers!
> 2 votes

---
Tags: views
---


# Question
Title: Merge content (e.g. a forum, with nodes, terms and users) from one Drupal site into another
How would I merge content (e.g. a forum, with nodes, terms and users) from one Drupal site into another?

Here's my specific use case:

* I have a local site which just contains nodes, terms and users for a forum (these were imported with http://drupal.org/project/phpbb2drupal \- and before you suggest just using it on my live site, I can't get it to work there, running into the issues described at http://drupal.org/node/1033316 )
* I have a live site which has no forum, but has its own nodes, terms and users.
* I'd like to merge the local site forum into the live site, adding the forum to the live site.

# Answer
> 2 votes
If it was just for nodes i would say use this:

http://drupal.org/project/node\_export

As you need to migrate users and taxonomy terms as well I would use this:

http://drupal.org/project/migrate

Although there will be some php OOP coding to do.

# Answer
> 0 votes
You can use below script to dump into your new drupal 7:http://goo.gl/GPmG9F

---
Tags: 7, migrations, importing-exporting
---


# Question
Title: unsetting field via view hooks no effect on aggregation results
I have created a view, with some aggregation parameters.

I expected that unsetting (removing) the aggregation field via some view hook (views\_pre\_render?) would do the trick to disable the aggregation caused by this field.

But it just removes the field from the table, the results are the same (aggregated by the unsetted field, even if it is removed).

some ideas? thanks

# Answer
> 0 votes
with pre\_build worked fine and the aggregation disappears.

function views\_test\_views\_pre\_build(&$view) { unset($view-\>field\['my\_field'\]); }

---
Tags: views, hooks
---


# Question
Title: Where are the Page Manager "Caching options"?
In D7 I'm using Ctools, Panels (3), Views, Page Manager etc., but in Page Manager when gear-icon-clicking the content panes I don't find any "Caching options" as I have seen described. What reasons can there be for this. It's probably something really simple, I just can't find it...

# Answer
> 0 votes
Although the language is german in this screenshot, location of the menu/options should be the same.

---
Tags: caching, panels
---


# Question
Title: Publish content on user unblock event Drupal 7
I know that this is most probably and easy question but I simply can't get it to work. I have a custom module which generates a form to create a content (unpublished) of a certain type and also register the anonymous user creating that content with a username and password.

I am using the User verification module to send a validation mail, and when the client clicks the link the account is unblocked.

I want a rule (I tried using the Rules module) to publish the content when the account is *unblocked* or *validated* (i need it to work on one of these to events) , but I can't find either of these events, nor can I manage to set the data selector to publish that specific content when setting the action to **publish content**.

If anyone can explain to me what I am missing or doing wrong it would help me a lot.

# Answer
> 0 votes
In your custom module you could use a hook\_user\_update and if the $account-\>original-\>status == 0 & $account-\>status == 1 (meaning that the user just got active \[untested\]), publish the content.

something like:

```
<?php
/**
 * Implementation of hook_user_update()
 */
function MODULE_user_update(&$edit, $account, $category) {
  if($account->status && $account->status != $account->original->status) {
    // with the user id you can find (i suppose) the content this user has just
    // created and publish it, using something like the link below
  }
}

```

publish-unpublish

---
Tags: 7, rules, users
---


# Question
Title: Output both form and generated image (imagejpeg) onto same page
This is my first newbie module (drupal 7). It's 'simple' but needs help x2.

**Intention:** To create an online image-name generator i.e, user types their name into a formfield and the browser outputs the text as a jpg image so they can right-click and save.

**What I've done:** 1. created one hook menu with two callback functions, one for the form and one for the image output. 2. A working form where user types in their name. 3. Able to output Image by setting name input manually through code, not by submitting the form!

**What doesn't work:** I created a $name variable within the form function, but using that same $name variable within the image-output function won't work. So I can't output a text-image when users submit the form. Also I don't know how to render both form and image output onto the same page.

**I need help with:** 1. How to render both form and image onto the same page?. 2: How to associate $name variable so inputted text will render upon submit button.

Frameyourname.module:

```
<?php

//Create simple image-generator.

//Implements hook_menu().

function frameyourname_menu() {
$items['frameyourname'] = array(
'title' => 'Frame Your Name form',
'page callback' => 'drupal_get_form',
'page arguments' => array('frameyourname_nameform'),
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM ,
);

//not entirely sure what to put here.

$items['image'] = array(
'title' => 'image',
'page callback' => 'drupal_get_form',
'page arguments' => array('create_textimage'),
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM ,
  );

return $items;

}

// Define a form.

function frameyourname_nameform() {
$form['user_name'] = array(
'#title' => t('Your Name'),
'#type' => 'textfield',
'#description' => t('Please enter your name.'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;
}

// Validate the form.
function frameyourname_nameform_validate($form, &$form_state) {
}

// Handle post-validation form submission.
function frameyourname_nameform_submit($form, &$form_state) {

//set name variable associated with user input and test if works.
$name = $form_state['values']['user_name'];
drupal_set_message(t('Thanks for adding your name,'.  $name));
}

// create image
function create_textimage() {

// Create a blank image and add text as per form input
$im = imagecreatetruecolor(400, 400);
$text_color = imagecolorallocate($im, 233, 14, 91);

//trying to reference $name variable not sure how.
imagestring($im, 1, 5, 5,  $name, $text_color);

// Set the content type header
drupal_add_http_header('Content-Type', 'image;jpeg');

// Output the image
imagejpeg($im);

// free from memory
imagejpeg($im);

}

```

# Answer
If you put `$form_state['rebuild'] = TRUE` in your submit handler then the form's redisplayed and you have access to `$form_state['values']` in the form constructor. This is typically how multi-step forms are done. So in this case something like:

```
if (empty($form_state['values']['user_name'])) {
  $form['user_name'] = array(
    '#title' => t('Your Name'),
    '#type' => 'textfield',
    '#description' => t('Please enter your name.'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );
}
else {
  $form['image'] = array(
    '#theme' => 'image__nameform',
    '#path' => $path,
    '#width' => $width,
    '#height' => $height,
    '#alt' => $form_state['values']['user_name'],
  );
}

```

To pass the name to your image generation function you want to change its entry in `hook_menu()`: the path should be `image/%` (which says there's an argument), page callback `create_textimage` (because that's what generates the content) and page arguments `array(1)` (because the text is the second argument, and you start numbering at 0). There are more details in the documentation for `hook_menu()`.

A few other points not directly related to the Q:

1. Currently the image generation function is a bit of a DOS vector (because it's a bit CPU intensive, isn't cached, doesn't require auth, and doesn't require a form submission).
2. You should use `drupal_set_message(t('Thanks for adding your name, %name.', array('%name' => $name));`. This is secure and translatable - see `t()` and `format_string()`.
3. The function names are a bit all over the place. If your module's called `frameyourname` then all your functions should start with that (with a few exceptions). Also I'd suggest avoiding a path like `image/%` in favour of something more specific like `frameyourname/%`.
> 1 votes

---
Tags: media
---


title: Suppress Incorrect error message

text:
# Question
Title: Suppress Incorrect error message
My website is using Drupal 7, secure login, and r4032login. I get this message when I log into a page that was redirected to the login page when access was denied:

> You are accessing using an unencrypted connection. For your security, only supports account logins using a secure protocol such as HTTPS. You can switch to HTTPS by trying to view this page again after changing the URL in your browser's location bar to begin with "https" instead of "http". Please contact for help if this error continues.

This is untrue, as every time this message appears the sites url is https://www.mysite.com What can I do about his message? What is the underlying cause? How can I suppress this if it can't be solved?

Update: This is not being caused by r4032login or secure login. I disabled and unistalled these module, and after logging in, the message is still displayed.

# Answer
Turns out this error message was being created when clicking on a link that had http selected as its protocol.
> 0 votes

---
Tags: 7, status-messages
---


title: How to create multi sites

text:
# Question
Title: How to create multi sites
I have just started to learn Drupal. So, I apologize to ask such a silly question here.

I wanted to create multi sites in Drupal. I have unlimited access to create Subdomains, Parked Domains, Addon Domains, Email Accounts and All SQl Databases with my hosting provider.

I wanted to create total 4 websites.

* One that I have already created just to play and learn drupal with just **Basic Structure** and layout.

Rest of the three websites should have same layout and theme but different layout and theme then what I have already created called **Basic Structure**.

So, theses three purposes should have **Same Theme** and **Same layout** with ***Different* Databses** with **Same User Names** and **Password**.

* One for **Development** purposes,
* One for **Staging** purpose and
* One for **Clients Editing** purpose (where client can play with our mock-up website for their content editing purpose).

I have read lots of reviews and steps to create multi sites in Drupal. Everyone explained it nicely in different ways. And I tried all the different ways to make it work. So, by trying and doing all those, I have messed up everything.

So, now I wanted to create again from beginning. Can anyone help me with that? Can any one provide steps to how to create multi site in Drupal? I am just beginner for Drupal. So, can anyone please explain the steps in detail?

Also, What is the best practice to create multi sites? With Parked Domain or with Sub Domain?

Thanks for your help!

# Answer
If the only purpose is to have a a dev/test/live environment, you should just go with a service like Pantheon which provides all of those for you with an ease of maintenance.

If you want to host it yourself, here's the gist of what you do...

1. Make sure you only have one Drupal root. Can't stress this enough. If possible, also be on version control (git) as this will help immensely.
2. Create 4 separate MySQL databases. Would go with a naming convention of like CODE\_dev, CODE\_test, etc.
3. Inside of your **sites** directory, create 4 directories, each with their own settings.php and files directory. You can name them whatever, just keep it consistent for ease of use. ie, dev.example, test.example, etc. Add their database credentials to their settings file.
4. In your **sites** directory, you will create a file called **sites.php**. In there, you will assign a directory name to a URL. So if you used **dev.example** as the name of your development site directory, and your subdirectory URL looks like **dev.example.com**, the format will look like this:

**$sites\['dev.example.com'\] = 'dev.example';**

Do that for each directory/site.
5. In your registrar for your DNS settings, point all of the subdirectories to the same IP or path as the top level domain (example.com), which should be the Drupal root directory. From there, Drupal will take care of the rest.

I think that's it, but anyone feel free to correct me. As far as the themes go, put it in **sites/all/themes** so all sites will have access to them. If you want a site to only have access to a specific theme/module, put it in THAT site folder.

For example: **sites/dev.example/themes/THEMENAME**
> 0 votes

---
Tags: theming, database, multi-sites, subsites
---


# Question
Title: Creating Primary Sub menu's programmatically
I want to display the latest 10 nodes of node type 'ABC' as a sub menu link under my primary menu. Are there any modules for Drupal 6 to help me achieve it.

I have created a view which gives me a latest 10 nodes sorted by creation date. However, I am unable to figure out how to integrate as an submenu links under the primary menu link.

So is there any other way I can achieve this?

# Answer
> 0 votes
You could use the menu views module:

> **What Menu Views Does**
>
> Menu Views is a utility module. It provides back end support for replacing a standard menu item link with a menu item view. Menu items (in any menu) now have the option of toggling between two different menu item types: link or view. Depending on which option is selected, the appropriate configuration form is displayed on the admin side and the appropriate type of item is rendered on the front-end.

Once you create a submenu, you can attach a view to it. Your title suggests you're asking to do this programmatically. From what i know, i'm not totally sure if that's possible without a lot of headache.

# Answer
> 0 votes
I think what you are expecting is described here. For following the tut you also need to enable Views build menu module. I haven't tried it but by reading it I'm sure its worth a try.

---
Tags: views, 6, routes
---


# Question
Title: Removing user points using rules module?
I've made a rule to add userpoints by

Add user points rule

**Events** 1.A node has been flagged, under "MyFlag"

**Actions**

1.flagged-node:author 2.Value 1 3.Point Category General

How do you remove user points using rules?

# Answer
> 1 votes
Just make the value of the "Points" field a negative number.

Let's say you want to remove 100 points when the flag event occurs.

Make the value for Points equal to -100.

Hope that helps.

---
Tags: rules, userpoints
---


title: Custom menu items with hook menu

text:
# Question
Title: Custom menu items with hook menu
I'm using hook menu here for the first time as token menu doesn't seem to be doing what I need.

*In the end, I need a menu that will use a wildcard and load a view based on that wildcard. I have the views working, now working on the menu.*

I have a "directory" structure like so:

* committee/committee-name/charter
* committee/committee-name/roster
* etc...

So I am using hook menu like so:

```
$items['committee'] = array(
        'title' => 'Committee Page',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

    $items['committee/%/roster'] = array(
        'title' => 'Roster',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

    $items['committee/%/charter'] = array(
        'title' => 'Charter',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

```

Committee shows on my menu, but Roster and Charter don't. I am not sure why not? If I give a wildcard, committee/%, to committee for example, I get no menu item. So is this a wildcard issue? should I be able to use a wildcard here? I am going to pull in a view based on wildcard and charter/roster content types.

# Answer
> 1 votes
See hook\_menu for reference under using Wildcards but you need to tell your menu which page arguments are going to be passed into your function:

```
$items['committee'] = array(
        'title' => 'Committee Page',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

    $items['committee/%/roster'] = array(
        'title' => 'Roster',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

    $items['committee/%/charter'] = array(
        'title' => 'Charter',
        'page callback' => 'committeemenu_mymenu_page_callback',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
    );

```

In this case array(1) would be the second positiong (as array(0) would be the first) if your wildcard resided in committee/charter/% it would be array(2).

I do not believe your items will be showing in the menu because there are wild cards, you would have to do that in your local tasks instead as the menu would not have any idea.

# Answer
> 0 votes
From what I understand, the only way to do this dynamic menu idea based on URL string / Node info is by using something like Menu Token. However, it didn't work well for my needs. Drupal Caches your menus, and since I am requiring something dynamic a menu wasn't going to work (unless someone else can give me some ideas).

The solution I am using is to create a new block and use PHP and/or JavaScript to create the menu. I did a quick mock up in JS and retrieved the URL and then inserted which committee I was on into the url and made the menu items.

```
<ul><li><a href="committees/' + getSecondPart(u) + '/charter">Charter</a></li><li><a href="committees/' + getSecondPart(u) + '/roster">Roster</a></li></ul>

```

getSecondPart(str) just returns the name of the committee in my case (committees/name/charter). You can break up a string however you'd like as long as it is consistent, which is possible with Views use.

Anyhow... I'll be moving this into php and a hook\_block custom module which will hopefully solve all my woes... hope this helps someone.

---
Tags: 7, routes
---


title: Adding jQuery Tabs via template.php

text:
# Question
Title: Adding jQuery Tabs via template.php
How do you add jQuery tabs in a "template.php" file?
I'm trying to add it with `drupal_add_library('system', 'jQuery.tabs')` or `drupal_add_js('/misc/ui/jquery.ui.tabs.min.js')`, but I'm not having any luck.

Here's my full snippet:

```
function custom_theme(&$existing, $type, $theme, $path) {
  $hooks = array();
  drupal_add_library('system', 'ui.tabs');
  // custom.js will call jQuery.tabs!
  drupal_add_js( path_to_theme() .'/js/custom.js', array('weight' => 9));

  return $hooks;
}

```

# Answer
hook\_theme() is a hook that must returns the list of theme functions implemented by a module, or a theme.

Calling `drupal_add_library()` or `drupal_add_js()` inside `hook_theme()` is not the way to add a JavaScript file to a page.

As reported in Structure of the .info file, a theme can use the `scripts` directive to declare the JavaScript files that it uses.

```
scripts[] = js/custom.js

```

Alternatively, a theme can use `drupal_add_js()` inside a theme function, or use the following snipped inside page.tpl.php, or any alternative page template Drupal would use.

```
drupal_add_js($path_to_script);
$scripts = drupal_get_js();

```
> 2 votes

# Answer
I think the specific question is regarding adding jQuery UI Tabs. Another answer speaks to adding custom javascript files.

When I have a lot of tabs on many pages, I've been accomplishing this is in a custom module with hook\_init()

```
function mymodule_init(){
    drupal_add_library('system','ui.tabs');
}

```

In the comments, this questions asks how to accomplish this for a specific page (or node).

You can do this in your theme in template.php with template\_preprocess\_page():

```
function mytheme_preprocess_page(&$variables) {
    echo "<pre>"; print_r($variables['node']); echo "</pre>";   // great for debugging
    if ($variables['node']->nid == 3) drupal_add_library('system', 'ui.tabs');
}

```

The above code assumes that node 3 is the target page that has the jQuery UI Tabs.

Don't forget to flush caches after adding these.

So now we've loaded the library. The next step is to add a javascript file to your module/theme. This is done in the mytheme/mymodule **.info** file. Add

```
scripts[] = js/script.js

```

Make the 'js' folder, create the script.js, and follow Drupal practices by following this pattern:

```
(function($, Drupal, window, document, undefined) {
    Drupal.behaviors.my_custom_behavior = {
        attach : function(context, settings) {
            // assuming your div is "tabs"
            jQuery("#tabs").tabs();
        }
    };
})(jQuery, Drupal, this, this.document);

```

So, for sake of simplicity, you can have your node 3 content set to Full HTML (or PHP in this example), and the body like this, which will show two Views on different tabs:

```
<div id="tabs">
<ul>
  <li><a href="#tabs-1">Stack Overflow</a></li>
  <li><a href="#tabs-2">Drupal StackExchange</a></li>
</ul>
  <div id="tabs-1">
    Let's show our View for Stack Overflow
    <?php echo views_embed_view('stackoverflow', 'machine_name_foo'); ?>
  </div>
  <div id="tabs-2">
    And for Drupal
    <?php echo views_embed_view('drupal_se', 'machine_name_bar'); ?>
  </div>
</div>

```
> 1 votes

---
Tags: 7, javascript
---


title: Adding a header to a views glossary

text:
# Question
Title: Adding a header to a views glossary
I currently have a glossary view set up using attachments in views using Drupal 7. I would like to have a header on top of the list of results displaying an element of the currently selected letter with a divider (top image). So far I've tried setting up a footer on the attachment but can't seem to figure a way to extract the current letter into the footer (bottom image).

.

I would like the view to look the same way the top image does. I've hardcoded the letter 'A' into the footer but am looking for a way to make it change with the letter selection.

# Answer
You need to be able to perform business logic (php) in your Views header (or footer) to perform this task.

The Views header or footer should be able to accept PHP, just change the input filter to PHP. If that input filter is not available, you'll need to enable the PHP Filter module (core, optional) first.

Once you can use PHP in the Views attachment header or footer you can include logic to look at the selected glossary item such as:

```
$term = check_plain($_GET['glossary_term');
echo "<div id='selected-glossary-term'>" . $term . "</div>";

```

Then use whatever CSS you need in your theme or module to make this Letter appear however you wish.
> 1 votes

---
Tags: views
---


# Question
Title: Loop over first three items of a list in Rules
I have a list and need to loop only over the first 3 elements of that list in Rules, but I cannot find the option to do this. It seems to be more complicated than I had thought.

# Answer
Install Conditional Rules so that you can add "conditions" between " rule actions". After that you can create a variable which iterates and use that to stop after the third elements.
> 1 votes

---
Tags: 7, rules
---


# Question
Title: Drupal confusion when including multiple instances of same webform on a page
I have nearly the same problem than this : Multiple forms on single page?

But the answer is for an inclusion on a **page** template and I want to do the same on a **node** template where I can't use any incremental ID loop. I'm using Drupal 7.

# Answer
> 1 votes
In either Display Suite or a `node template` just call the forms using `drupal_get_form` each form will given a unique `build_id` and there should be no problem displaying any number of forms on the page.

`hook_forms` in this answer https://drupal.stackexchange.com/a/6230/3279 has nothing to do with your question. You don't need to worry about incremental form IDs or anything.

Here is an example of how to use a preprocess function for a Node (type): http://purencool.com/drupal-7-preprocess-tutorial-adding-variable-to-template this uses this Drupal API function https://api.drupal.org/api/drupal/modules!node!node.module/function/template\_preprocess\_node/7

Your code would look something like (this is example code not guarenteed to work):

```
function MYMODULE_preprocess_node(&$vars) {
  if ($vars['node']->type == 'MY_NODE_TYPE') {
    // link to webform paths.
    $vars['custom_form_links'] = implode(' ', array(l('Please Fillout Form 1', 'some/path/to/webform'), l('Please Fillout Form 2', 'some/path/to/webform2')));
    // Or just embed the forms.
    $form1 = drupal_render(drupal_get_form('myform1'));
    $form2 = drupal_render(drupal_get_form('myform2'));
    $vars['custom_forms_embed'] = $form1 . $form2; // You may want additional HTML wrappers, figure it out.
  }
}

```

Then in your themes template files for like `node--YOURCONTENTTYPE.tpl.php` you echo these new variables.

Display Suite makes all this a ton easier with `Code Fields`, or custom fields, and dynamic `view_modes` so you don't need to touch template files either ...

None of this code is guarenteed to run -- it's just a rough example.

# Answer
> 0 votes
I think you can get your form on template if you know their ids.

```
$form1 = drupal_get_form('form1_id');
$form2 = drupal_get_form('form2_id');

```

And then render by drupal\_render()

```
drupal_render($form1);
drupal_render($form2);

```

# Answer
> 0 votes
Use Panels module. You can embed any number of webforms in a single page using panels module. Create a custom page and add existing nodes as content

---
Tags: 7, forms, theming, webforms
---


# Question
Title: What would cause this error when upgrading Panels module?
```
$ drush up panels
Code updates will be made to the following projects: Panels [panels-7.x-3.4]

Note: A backup of your project will be stored to backups directory if it is not managed by a supported version control system.
Note: If you have made any modifications to any file that belongs to one of these projects, you will have to migrate those modifications after updating.
Do you really want to continue with the update process? (y/n): y
Project panels was updated successfully. Installed version is now 7.x-3.4.
Backups were saved into the directory /home/bzisad0/drush-backups/newco/20140724235906/modules/panels.       [ok]
WD php: PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'newco.cache_panels' doesn't [error]
exist: TRUNCATE {cache_panels} ; Array
(
)
 in cache_clear_all() (line 165 of
/var/www/vhosts/www.companyname.com/releases/20131007153705/includes/cache.inc).
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'newco.cache_panels' doesn't exist: TRUNCATE {cache_panels} ; Array
(
)
 in cache_clear_all() (line 165 of /var/www/vhosts/www.companyname.com/releases/20131007153705/includes/cache.inc).
Drush command terminated abnormally due to an unrecoverable error.                                           [error]
Backups were restored successfully.                                                                          [ok]

```

The only clue I have is that the company I'm doing work for underwent a merger, and we had to set up the new web site before the name of the new company was public, so everything went by "newco". I could not find anywhere that this is configured in Drupal, but I see that showing up in the error message "Base table or view not found: 'newco.cache\_panels' doesn't exist".

I'm not sure if that's relevant or not, but I'm mentioning it just in case, and hoping it's not a red herring.

# Answer
> 1 votes
For some reason, the "cache\_panels" table of panel used for cache is missing.

It's reported as an issue for this module.

To solve this error, first, I **strongly recommend to do a backup of the database** before make any change (even before do a drush updb or update a specific module as you are trying in this case).

You cloud try one of the following solutions:

I recommend you to use the first alternative as I see that you use drush.

---
Tags: 7, panels, upgrading
---


title: Different product attributes same SKU

text:
# Question
Title: Different product attributes same SKU
I need the user to choose a serial number from a drop down when viewing the product display. For example there is a product SKU of unxm\_12 for Uncanny Xmen #12, there are 3 in stock and each one has a serial number, all are the same price.

We want the user to be able to choose a serial number from a drop down and then we can view that serial number on the order later to determine which comic book they actually want.

This needs to be custom for each product, each SKU can have multiple serial numbers. There are many products. What is the best way to do this?

# Answer
Have you tried Commerce Product Attributes?
> 0 votes

---
Tags: commerce
---


# Question
Title: hook_form_alter checking $user->uid == $node->uid
I need to check if the node uid and the logged-in user's uid are identical when the user is in the node edit form, and then add a class to the form if that condition is true.\* The relevant code in my custom module currently looks like this:

```
function custom_form_alter(&$form, $form_state, $form_id) {
    global $user;
    $node = node_load(arg(1));
    switch($form_id) {
        case "custom_type_node_form" && "$user->uid == $node->uid":
            $form['#attributes'] = array('class' => 'test-class');
    break;
    }
}

```

The class is getting added even if the user isn't the author.

\*Use case is that all site members with role X can edit nodes of type Y, but if the member editing the node is the author, I'd like to add some CSS.

I'm using Drupal 6.31.

# Answer
hey You can simply do this :-

```
function custom_form_alter(&$form, $form_state, $form_id)
 {
    global $user;
    $node = node_load(arg(1));
    if($form_id=='custom_type_node_form')
     {
       if($user->uid == $node->uid)
        {
          $form['#attributes'] = array('class' => 'test-class');
        }
      }
}

```

I hope this will work for you.
> 0 votes

---
Tags: forms
---


title: Drupal view to display node activity

text:
# Question
Title: Drupal view to display node activity
I need to provide a view which gives a simple list of user activity with regards to node 'events' - e.g. any updates to fields, new nodes created, nodes deleted etc..

For example,

> ```
> Last Updated:         Activity
> -----------           --------
> ..
> 5 mins ago -          username has updated Title for node:nid
> 6 mins ago -          username has updated Price for node:nid
> 7 mins ago -          node:nid has been deleted
> 13 mins ago -         new node:nid has been created..
> ..etc
>
> ```

Has anyone achieved something similar? If so - how did you go about this? Did you use a module?

# Answer
> 1 votes
As per your requirement it seems Activity module will suite you. But again this module is in Dev version for Drupal 7. So if you are ready to use Rules module then go ahead. Since you are only tracking the node create & edits then in Rules module you will get all the conditions and events.

But if you are also okay with developing custom module then I'd suggest to write a custom module and with all the HOOKs provided for nodes you can create the desired records and store those in a table. See the HOOKs for nodes here.

Let me know if I can assist you with creating a custom module.

---
Tags: views, nodes
---


title: Pre-filled subject Form

text:
# Question
Title: Pre-filled subject Form
I wanted to attach a form to my node, in wich the subject would be already filled with the nodes title. I was trying something with webforms and views but didnt get any results. Any Ideas?

# Answer
If subject is a simple textfield on webform and token module is enabled then you can set this textfield's default value using token.
> 1 votes

---
Tags: webforms
---


# Question
Title: How to export custom module form content as PDF file in drupal 7?
I have a custom module with some form fields. I want to submit this form and generate pdf file of user filled values in new tab. I am trying with TCPDF but it doesn't display any fieldset ( as border ).

In submit funciton , I am taking $form array and using drupal\_render($form) that render form values as html ( if I print ). If I pass this html to WriteHTML($html, true) , it gives pdf but there is no styling left on that form.

# Answer
> 0 votes
Have you tried Webform2PDF?

> The Webform2PDF Drupal module is an extension of the Webform module. It can be used to generate PDF document from the results of a form. The generated PDF document can be attached to the form summary e-mail sent by Webform module, or it can be downloaded from the /Results/ page. Different PDF templates can be set for each form. The templates can be formatted with HTML tags, and they can be edited with WYSIWYG Drupal module, making the template creation easy and the templates highly customizable. The output documents will be created by using these templates.

# Answer
> 0 votes
The Views Pdf module will do everything that you need.

> With this module you can output a view as a PDF document. Each field of the view can be placed on the PDF page directly in the administration interface. Therefore a new display called "PDF" is added.

# Answer
> 0 votes
TCPDF doesn't support all styling attributes.It only supports some of the features that are given below.it has a very limited CSS support.

```
font-family
font-size
font-weight
font-style
color
background-color
text-decoration
width
height
text-align

```

Basically, You can use tables to style your pdf data And styling pdf throught table attributes.like

```
colspan
rowspan
align
cellpadding
cellspacing
width
border

```

etc.

And Note That PDF and HTML and different formats that hardly have anything in common. If TCPDF allows you to provide input data using HTML and CSS it's because it implements a simple parser for these two languages and tries to figure out how to translate that into PDF. So it's logical that TCPDF only supports a little subset of the HTML and CSS specification and, even in supported stuff, it's probably not as perfect as in first class web browsers.

---
Tags: forms, files
---


title: Form results not displaying - D7

text:
# Question
Title: Form results not displaying - D7
Below is my code. Form results are not displaying below the form. What am I missing ?

When I use `print_r($form_state['storage']['results']);` I'm getting the results.

But it is not displaying in the form.

Any ideas/suggestions will be helful.

```
function file_search_form($form,&$form_state) {
  $otpions = _get_country_titles();
  $form['countries'] = array(
    '#type' => 'select',
    '#title' => t('Country'),
    '#options' => $otpions,
    '#required' => TRUE,

  );
  $form['entities'] = array(
    '#title' => t('Entity'),
    '#type' => 'textfield',
  );

  if(isset($form_state['storage']['results'])) {
    $form['result'] = array
    (
      '#value' => t('The results of the form are: !results', array('results' => $form_state['storage']['results'])),
    );
  }

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

  $form['#submit'][] = 'webform_options_submit';
  return $form;

}

function webform_options_submit($form, &$form_state) {

  $args = array(':entities' => '%'.$_REQUEST['entities'].'%', ':countries'=>$_REQUEST['countries']);
  $result = db_query("SELECT field_entity_value,field_country_value, filename
                   FROM field_data_field_entity,field_data_field_country , field_revision_field_file_upload, file_managed
                   WHERE ( field_data_field_entity.field_entity_value LIKE :entities
                   AND field_data_field_country.field_country_value= :countries )
                   AND field_data_field_entity.entity_id = field_revision_field_file_upload.entity_id
                   AND field_data_field_country.entity_id= field_data_field_entity.entity_id
                   AND field_revision_field_file_upload.field_file_upload_fid=file_managed.fid",$args );
  foreach( $result as $item) {
    $form_state['storage']['results'] = $item->filename;
  }
  $form_state['rebuild'] = TRUE;

}

```

# Answer
> 0 votes
Added type markup below the submit code in $form\_state\['storage'\]\['results'\] and that does the trick...

```
  $form['submit'] = array(
    '#value' => 'Search',
    '#type' => 'submit',
  );

if(isset($form_state['storage']['results'])) {
        $form['result'] = array
        (
          '#type' => 'markup',
          '#markup' => t('The results of the form are: !results', array('results' => $form_state['storage']['results'])),
        );
      }

```

---
Tags: 7, forms, search
---


title: Boost is not working properly

text:
# Question
Title: Boost is not working properly
I am using Drupal 7.

I have installed Boost module and configured properly as per the guidelines from Drupal.org site and other sources.

As per my knowledge to test whether boost is working or not we have to check html source code of any page because Boost module adds Boost tags in the html output generated by drupal.

When i check page source i don't find any boost tags.

I also have one doubt regarding the configuration, in .htaccess generation page there are three options

> %{HTTP\_HOST}
>
> %{SERVER\_NAME}
>
> localhost

which one should i enable when i am configuring on the site like http://xyz.com/mydrupal where mydrupal contains drupal setup and all the files

# Answer
%{HTTP\_HOST} is the default and it usually works. The other 2 options are there in case http\_host doesn't work. Every hosting environment is different; that's why there are options.
> 1 votes

# Answer
There are two possible reasons:

1. Some browsers may not display the Boost tags. Check, if HTML files are saved to the cache directory. If so, it caches, but the tags are not displayed
2. Check, if you put the Boost htaccess snippet really at the right place in your .htaccess file. It should be added right after

```
    # If your site is running in a VirtualDocumentRoot at http://example.com/,
      # uncomment the following line:
      # RewriteBase /

```
> 1 votes

# Answer
One more possible reason is the directory permission of cache. Set `<drupal-root>/cache` permission to 777, then visit any page on the site. If everything is ok then you can see cached page copy on below path

```
<drupal-root>/cache/normal/domain-name/

```

This way you can verify which page is cached and which is not.
> 0 votes

---
Tags: caching
---


# Question
Title: What hook is most appropriate for code that should run as early as possible in bootstrapping but only on certain paths?
I am writing a module that should run code as early as possible because it's a conditional redirect to another page, so the first page doesn't need to finish loading.

I only want to run it on `/foo/*`.

Is there a hook that can be bound to a particular path, like `hook_form_alter()` can be with form IDs? Or should I just use `hook_init()`?

# Answer
> 4 votes
Similar to the forms, there's `hook_page_alter()`, but that happens near the end, making it a bad place for redirects.

`hook_init()` should be fine, but is not invoked on cached pages.

`hook_boot()` sounds self-explaining; it's run so early that you can't call any module's function, not even drupal's.

however, since you need a conditional redirect and you already have your own module, just add it atop the page callback of 'foo/\*'.

if that callback it's not defined in your module, use `hook_menu_alter()` to have that path pointing to a custom function that will execute your conditional redirect.

---
Tags: redirection, hooks
---


# Question
Title: How to set default values for "modify entity values" form
I have a view with nodes and a views bulk operations field. With this vbo field I like to "modify entitity values" of the selected node.

Is it possible:

* to automatically check the checkbox for a selected field, so that the field to modify the value is shown by default?
* to automatically set a default value in the textfield (which should be shown by default of course)?

# Answer
You have to hook the form, which is shown after clicking "Modify entity values".

Here is my code to handle this:

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

  global $user;
  $account = user_load($user->uid);

  //to get the form id, you have to print it out first
  dpm($form_id);

  switch ($form_id) {
    case 'views_form_your_view_display_name':

      $nid_page = menu_get_object();

      // the next line activates the checkbox to show the input field
      $form['bundle_item']['show_value']['field_name']['#default_value'] = TRUE;

      // the next line sets the default value for the field shown
      // notice: the 'value' array field depends on the field type and may also
      // be 'target_id' (for entity references) or 'tid' for taxonomy references
      $form['bundle_item']['field_name'][LANGUAGE_NONE][0]['value']['#default_value'] = $your_desired_value;
  }
}

```
> 0 votes

---
Tags: views
---


# Question
Title: Boolean single on/off field - how to make it NOT render the off option?
I'm having some issues with boolean field. I want to have few fields that can be turned on/off, which will be used to show if something is available in the content.

So I thought single on/off checkbox is the way to go. Well, apparently not because even if I don't select the checkboxes, they're still rendered in the code. And I need them to NOT render.

Checkboxes/radio buttons works in this way, but it creates 3 selectable options (on, off, not available) whether I would like to have only one checkbox.

I also tried using List (text) for my needs, but here I'm limited by the fact I can't add individual CSS id/classes to every item in the list.

My target is using these lists/checkboxes, hidding them in CSS and replacing with icons. I did something like this few months ago but now I can't remember how exactly I achieved what I needed.

# Answer
Turns out field of the List (text) type was enough, just needed to create my own field template for that field. With this I was able to render additional classes/id and change the way the field is build, making it possible to style as needed using CSS.
> 0 votes

# Answer
You can hide them either through CSS or you can unset them using the form\_alter if you are using forms. Look at the code below In this code, I am unsetting the author on the comment form.

```
function Mymodulename_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    if($form_id == 'comment_form) {
      unset($form['author']);
    }
  }
}

```

If you've added the field to some node then you can unset them using this code.

```
unset($node->field);

```
> 0 votes

---
Tags: entities
---


# Question
Title: Alternative ways to clear the Drupal cache
We have a busy database server and when we try to clear the cache on Drupal, Drupal tries to `TRUNCATE` cache tables and that causes a backlog until the MySQL hits to maximum number of user connections (which is 800). This is causing problems for us.

As far as we can tell, the problem is being caused by the locks during the table truncation.

Are there any alternative methods to clear cache that can help avoid this situation?

# Answer
While your cache bins are in MySQL, truncating tables is by far and away the quickest method to clear the cache. It's not a particularly expensive operation, so if it's backing up your db connections I would get your sysadmin to investigate what config issues might be causing that (or whether it's simply a lack of sufficient resources).

As MPD notes in the comments above, your real problem might actually be the cache rebuild *after* the flush has happened, though. You should be able to confirm that after a bit of testing.

You can take the pressure off the database by using redis/memcache/etc as a cache backend instead of the database. Doing that will also make considerable speed improvements to your site in general.

Your mileage will vary, of course, but it's very likely that flushing cache from memory will be a quicker operation than flushing it from the disk. As Mołot notes below, writing the new cache items to memory rather than disk will also give you a performance boost (there will still be reads and writes to MySQL, but far fewer writes in theory).

As with anything, it needs testing on the bare metal to see how any of this would affect your specific configuration.
> 4 votes

# Answer
If you are using `drush cc all` or clearing cache from the Performance page (admin/config/development/performance), then you end up calling `drupal_flush_all_caches()`. This will

* Rebuilt the registry
* Clear CSS and JS caches
* Rebuild theme info
* Rebuild entity and field info
* Rebuilt the menu router table
* Rebuild the action list
* Clear all of the cache tables

The actual clearing of the cache tables is rather quick, but the other operations are pretty expensive. In addition, on the next page load (which can be when you get redirected back to the Performance page), you will rebuild all of the cache tables.

When I have seen cache clear problems, the root cause has normally been a misconfigured LAMP stack. Calculating out the max number of Apache processes to prevent system overload can help, as can having MySQL provisioned properly for buffers, max connections, etc.

In addition, in a live environment, you don't really need to rebuild everything from a `drupal_flush_all_caches()`; you usually just want to clear the cache tables themselves. In this case, I use a variant of this:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  $form['clear_cache']['clear_forward'] = array(
    '#type' => 'submit',
    '#value' => t('Clear all forward facing caches'),
    '#submit' => array('MYMODULE_clear_forward_submit'),
  );
}

function MYMODULE_clear_forward_submit($form, &$form_state) {
  MYMODULE_clear_forward_caches();
}

function MYMODULE_clear_forward_caches() {
  $cache_tables = array(
    'cache',
    'cache_block',
    'cache_filter',
    'cache_page',
    'cache_views',
  );

  foreach ($cache_tables as $table) {
    cache_clear_all('*', $table, TRUE);
  }

  drupal_set_message(t('Cleared forward facing caches.'));
}

```

This will add a new submit button to the Performance page which will just clear the caches that affect the forward facing portion of your website (ie, main pages). I wouldn't use this as is; you need to adjust the table list to match your environment. Once of these days I will make this more generic and release it as a public module.
> 4 votes

# Answer
You can try to use `drush` like `drush -y cc all` command, or TRUNCATE/DELETE the tables manually by the following one-liner:

```
drush sqlq --extra=--skip-column-names "SHOW TABLES LIKE 'cache%'" | xargs -L1 -I% echo "DELETE FROM %;" | drush sqlc --extra=-v

```
> 0 votes

---
Tags: caching, database
---


# Question
Title: How to model players and rosters in a team sport site
I'm very new to Drupal and I would like to know, from a general design standpoint, how you would enter players of a team into drupal. I don't want to add them as users because they should not be able to log in etc.

Each player could have fields like Name, Picture, etc.

Is this really a content type? Because the players are not published alone. Or is it necessary to create a custom module for this?

These players are then used to show the current roster. This could be done with a View and custom template I guess, but I'm not sure. They are also used in game reports (who played in that particular game and maybe the stats)

If I have a database of players somewhere, I would like to have a field that allows me to select a particular player. So basicly I must reference a content type inside another content type. I have not seen that option though.

No technical details are required, just general hints to modules or advice how to accomplish this task.

# Answer
I would say yes, player is a content type in this case. Every player node would represent something (the player) that still has a meaning when you would take it out of its context (the team). Setting it up as a distinct content type will allow for more flexibility in the future, for instance showing player biographies, or transferring a player from one team to another.

If you want to hide the player nodes from regular visitors, you can use the Rabbit Hole module.

To make references between nodes, there are several options. Entity Reference is good and pretty straight forward. It allows you to add a field on the 'team' node type in which you can reference nodes of the 'player' type.

The Relation module is more complex but it can do a lot more. Relation doesn't store the references in the node itself, but it creates a new relation entity for each relation. Those relations can be 1-to-1 or 1-to-many and they can be bi-directional or one-directional. Since relations are entities, you can even add fields to them. For instance, if you define a relation that stores which players play for team X, a field on that relation could store the year/season when that happened. As you can see this offers a lot of possibilities, but it might introduce more complexity than you need.

How you can create the roster depends on the way you build your team-player relations. If you use Entity Reference to create a players field on the tem node, then the roster could simply be a display of the team node. When Drupal displays the team node, Entity Reference can fetch all related player nodes and render them in a view mode of your choice (eg. it can use the teaser view mode of the player node). If you use Relation, you should use the Views module. The Relation module has pretty good Views support (though I haven't used that feature a lot myself) as you can see in this video tutorial.
> 2 votes

---
Tags: nodes
---


# Question
Title: Update remaining points in different site once purchase through points method
I am using userpoints module. What I need to do is once the purchase is done through points methos, update the remaining points in different drupal site.

I have tried for webservices. I have created web services which will update the remaining points in other site.

I have gone through the code and found function uc\_userpoints\_payment\_uc\_order() 'all\modules\userpoints\_ubercart\uc\_userpoints\_payment\uc\_userpoints\_payment.module' where it updates (uc\_userpoints\_payment\_payment) or refund the points (uc\_userpoints\_payment\_refund). So here (in these two functions), I want to call webservice.

Could anyone please throw some light and point me in right direction?

# Answer
You can call web service using `hook_uc_checkout_complete`. it takes action when checkout process is completed.

Please refer uc\_cart api
> 0 votes

---
Tags: updating, userpoints
---


# Question
Title: How to preserve form values for user who navigates out of form and back?
I have a form that works, essentially, as a search / filter:

```
 foreach($search_properties as $property) {
    $form['properties'][$property->idProperty] = array(
      '#title' => $property->Label,
      '#ajax' => array(
        'callback' => 'mymodule_filter_ajax',
        'wrapper' => 'category-filter-result',
        'method' => 'replace',
        'effect' => 'fade',
      )
    );
    switch ($property->PropertyType) {

```

Options are generated by taking only actually used values from possible ones:

```
  '#options' => array_intersect_key($possible_choices, $used_values),
  '#default_value' => array_keys($used_values),

```

Nothing interesting here, really, just set of fields that, on change, reloads a list of links using AJAX. Never submitted, never saved.

Problem is - when user clicks on a link, and then clicks browser's "back", all fields have their defaults selected again.

I'm under impression that it was not the case with Views exposed filters. I think I remember these filters was able to keep values when user went back to them. So it is possible.

What is **the Drupal way to keep user-selected values** in the simple scenario of a link click, and then browser's "back" button?

# Answer
> 1 votes
I'm not aware of a specifically *Drupal* way to do it.

As I say, I find that if I fill out a form, don't submit, click a link, and then click back, the form elements are still populated, unless perhaps there's some AJAX/JS funkiness going on with them (the actual form elements). However *a little* digging suggests that's browser-dependent and won't work in certain situations (eg. over HTTPS). I'd love to know more about this behaviour.

I think ideally you'd use JS to put the data in the URL. If you don't need to support older browsers then you can use the History API (not that I ever have...) which would allow you to separate arguments in a more Drupally way: eg. `path/arg1/arg2/arg3`. Otherwise the traditional `window.location.hash` can be used instead.

You can use the session variable like Views, which is more flexible and simpler to implement, but can cause anonymous users to bypass caching.

---
Tags: forms, ajax, sessions
---


title: hide a node from node author in view

text:
# Question
Title: hide a node from node author in view
I have a view of content type 'video' which shows a preview videos of particular author. I have passed content id as contextual filter. Now,I want to show a node (video) to the other users but not the node author.How can I hide it from only the node author in my view?

# Answer
Without Code:

To adjust views to show/hide author content...

* under Advanced Tab create a Relationship, Content:Author, Require this field
* create a new Filter, User:Current, Relationship Author(or whatever name you gave the relationship), Is the logged in user -\> No

This will compare the author of the content to the currently logged in user and only show the content if they don't match. This method can be used to show only content by the current user by changing the 'Is the logged in user' -\> Yes
> 1 votes

---
Tags: views
---


title: HTML In a hook_menu title callback

text:
# Question
Title: HTML In a hook_menu title callback
I'm trying to insert a span class around some text in title callback. It passes through a `t()` function so all the html is escaped.

Is there a way round this?

My code is:

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

  $items['discussion'] = array(
    'title' => 'Discussion',
    'title callback' => 'custom_module_title',
    'page callback' => 'custom_module_tester1',
    'access callback' => TRUE,
    'menu_name' => 'document-menu',
    'type' => MENU_NORMAL_ITEM,
    'options' => array('attributes' => array('class' => 'discussion')),
    'weight' => 10,
  );

  return $items;
}
function custom_module_title() {
  $discussionnid = custom_module_postexist(3);
  if ($discussionnid) {
    return 'Discussion <span class="discussionnumber">85</span>';
  }
  else {
    return 'Discussion';
  }

}

```

# Answer
> 5 votes
The HTML in the title is escaped because template\_preprocess\_page() gets the title using the following code:

```
// Construct page title
  if (drupal_get_title()) {
    $head_title = array(strip_tags(drupal_get_title()), variable_get('site_name', 'Drupal'));
  }

```

drupal\_get\_title() then contains the following code:

```
function drupal_get_title() {
  $title = drupal_set_title();

  // during a bootstrap, menu.inc is not included and thus we cannot provide a title
  if (!isset($title) && function_exists('menu_get_active_title')) {
    $title = check_plain(menu_get_active_title());
  }

  return $title;
}

```

The title is escaped from that function.

As far as I know, the content of `<title>` should not contain HTML tags; that is the reason it is escaped.

In the W3C specifications for HTML 4 is reported the following text:

> Titles may contain character entities (for accented characters, special characters, etc.), but may not contain other markup (including comments). Here is a sample document title:
>
> ```
> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
>    "http://www.w3.org/TR/html4/strict.dtd">
> <HTML>
> <HEAD>
> <TITLE>A study of population dynamics</TITLE>
> <!-- other head elements -->
> </HEAD>
> <BODY>
> <!-- document body -->
> </BODY>
> </HTML>
>
> ```

In Changed Elements it's not reported any changes between HTML 5 and HTML 4 about the `<title>` tag.

In Drupal 7, you could set the title with `drupal_set_title($title, PASS_THROUGH)`, but the documentation says:

> Only set to PASS\_THROUGH if you have already removed any possibly dangerous code from `$title` using a function like check\_plain() or filter\_xss(). With this flag the string will be passed through unchanged.

`PASS_THROUGH` is used to avoid the title is filtered twice, not to filter the title at all.

Then, using `drupal_set_title()` is not possible from the title callback; you should set it in a different place. I would not suggest doing so, though.

# Answer
> 2 votes
You can use

```
drupal_set_title('your html title',PASS_THROUGH)

```

before to render your page.

`PASS_THROUGH` = Flag for `drupal_set_title();`, text has already been sanitized.

# Answer
> 2 votes
I had a similar situation where I wanted to display the weight of the menu item right next to the link. Since it seems problematic to insert HTML in the link title itself, I chose a different approach:

Add an extra attribute to your links and show it using CSS

```
$items['discussion'] = array(
  // ... all the other properties
  // Our special attributes:
  'options' => array(
    'attributes' => customAttr()
  ),
);

function customAttr() {
  $discussionnid = custom_module_postexist(3);
  if ($discussionnid) {
    return array(
      'class' => 'discussion',
      'data-discussionnumber' => 85
    );
  }
  else {
    return array(
      'class' => 'discussion'
    );
  }
}

```

This returns a link like:

```
<a class="discussion" data-discussionnumber="85" href="yourHref">yourTitle</a>

```

Now you can add the following CSS:

```
#document-menu a:after {
  content: attr(data-discussionnumber);
  /* your custom styles */
}

```

Hope this helps!

# Answer
> 1 votes
Define `title callback` a function to replace `t()`

e.g.

```
<?php
function node_menu() {
  $items['node/%node'] = array(
    'title callback' => 'node_page_title',
    'title arguments' => array(1),
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'node_access',
    'access arguments' => array('view', 1),
    'type' => MENU_CALLBACK,
  );
}

/**
* Title callback.
*/
function node_page_title($nid) {
  $node = node_load($nid);
  return "<span>" . $node->title . "</span>";
}
?>

```

# Answer
> 0 votes
If you arrived here looking for the answer for drupal 7. (I don't know if it works for drupal 6). You can add to the "options" array "html" =\> "true". This parameter will be passed to the l() saying to not parse the html tags. Use with precaution, because it's dangerous.

from hook\_menu:

> "options": An array of options to be passed to l() when generating a link from this menu item. Note that the "options" parameter has no effect on MENU\_LOCAL\_TASK, MENU\_DEFAULT\_LOCAL\_TASK, and MENU\_LOCAL\_ACTION items.

and from ():

> 'attributes': An associative array of HTML attributes to apply to the anchor tag. If element 'class' is included, it must be an array; 'title' must be a string; other elements are more flexible, as they just need to work in a call to drupal\_attributes($options\['attributes'\]).
>
> > 'html' (default FALSE): Whether $text is HTML or just plain-text. For example, to make an image tag into a link, this must be set to TRUE, or you will see the escaped HTML image tag. $text is not sanitized if 'html' is TRUE. The calling function must ensure that $text is already safe.

would be like that:

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

  $items['discussion'] = array(
    'title' => 'Discussion',
    'title callback' => 'custom_module_title',
    'page callback' => 'custom_module_tester1',
    'access callback' => TRUE,
    'menu_name' => 'document-menu',
    'type' => MENU_NORMAL_ITEM,
    'options' => array('attributes' => array(
       'class' => 'discussion',                //will be passed to l()
       'html' => true
       )),
    'weight' => 10,
  );

  return $items;
  }

  function custom_module_title() {
    $discussionnid = custom_module_postexist(3);
    if ($discussionnid) {
      return 'Discussion <span class="discussionnumber">85</span>';
    }
    else {
      return 'Discussion';
    }
  }

```

---
Tags: 6, routes
---


# Question
Title: Filter "exposed filter" data based on another "exposed filter"
I have to exposed filters from 2 vocabularies, filtering results for a page. I'm using views module for this Is there a way to create a bridge between them ? For example when I select something from the first filter the data from the 2'nd filter will change based on what I selected on first filter, and backwards.

If i'm thinking well there is no way to create a direct connection between those 2 filters (vocabularies), we have to use what they have in common, the content. So i'm guessing I need to get vocaluray 1 terms from the content after filter 2 has selected something.

* Filter 2 -\> generate content -\> generate filter 1 data again

Is there a way to do this without "hardcoding" ? Thanks

# Answer
> 0 votes
Try the Hierarchical Select module for that

> This module defines the "hierarchical\_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.

---
Tags: views
---


# Question
Title: Example Hook form validate, get all node information after save news field
In a custom module, I do some operations on several content node (add field\_collections and save) After that, I need to get all field\_collections of my content nodes. But when I get, I have the old field\_collections and not the new field\_collections I just save.

Exemple :

```
//I have this node in my submit hook
node0
    ->field0
    ->filed1

//I save a new field (via entity_metadata_wrapper and save() ), and I get this node after
//I Have
node0
    ->field0
    ->filed1

//But I would like have
node0
    ->field0
    ->filed1
    ->field2 //the new field I just save

```

Are there a Hook I can use after a validate form ? But I would like keep the information about who nodes has been save...for get only them Or an other way I don't know ?

I don't think I can clear the cache because my operations "save" and after "get" are in a heavy foreach

# Answer
> 0 votes
To grab your information before the node is saved you can use `hook_node_presave`, then if you want to gather information after its successfully saved simply use `hook_node_update`.

Also if you are saving it via the `entity_metadata_wrapper` you should still have access to the data after its saved.

```
$entity_wrapper->field_name->value(); //Should have field0, field1

//Add your value here

$entity_wrapper->save();

$entity_wrapper->field_name->value(); // Should have field0, field1, field2

```

---
Tags: forms, entities
---


# Question
Title: Migrating dates in the same timezone: convert arguments to subfields?
I have a migration that is successful except for the timezone.

```
$this->addFieldMapping('dest_date', 'source_date');

```

For some reason the above code causes a timezone conversion to happen between the source date and the destination timezone. The migration seems to assume the source is in UTC and needs converted to Chicago time, giving me a result that's six hours later than it should be. The source date is in fact from the same timezone, so I want to avoid converting it.

```
$this->addFieldMapping('dest_date', 'source_date')
  ->arguments(DateMigrateFieldHandler::arguments('America/Chicago', 'America/Chicago'));

```

The above code works perfectly, but when I run my migration I get this error:

> The field mapping arguments() method is now deprecated - please use subfield notation instead.

However when I try to use subfield notation, I end up with the same problem again that I did when I had no arguments/subfields at all:

```
$this->addFieldMapping('dest_date', 'source_date');
$this->addFieldMapping('dest_date:timezone', 'source_date:timezone');

```

The above code doesn't seem to help at all, (edit: This is not surprising, as my field doesn't seem to have "timezone" as a subfield.) and the migration still seems to assume the source is in UTC and needs converted to Chicago time.

How do I convert my arguments to subfield notation without breaking them?

# Answer
> 2 votes
You can use it like:

```
$this->addFieldMapping('dest_date:timezone')
->defaultValue('America/Chicago');

```

# Answer
> 2 votes
I struggled with the same thing for hours before caving in and hacking the date module a teensy little bit :-)

My datefields are of the type "datetime" so I had to insert a timezone variable on line 158 of the date.migrate.inc file of the date module - like this:

```
        case 'datetime':
      // YYYY-MM-DD HH:MM:SS.
      $timezone = 'Europe/Copenhagen'; #add this line
      $from = format_date($from, 'custom', 'Y-m-d H:i:s', $timezone);
      if ($to) {
        $to = format_date($to, 'custom', 'Y-m-d H:i:s', $timezone);
      }
      break;

```

You can just remove it after migration. I would love a better solution - I thought of extending the DateMigrateFieldHandler class, but that just gave me double dates :-/

Hope this helps

---
Tags: migrations, datetime
---


title: Embed a node add form on a parent node

text:
# Question
Title: Embed a node add form on a parent node
I have a product display node and I'm trying to add a rental form to the node so that anyone can submit a rental form and have that reference the node. I was thinking of making the rental form a new Content Type so that the author information is automatically stored. I was also looking at Entityforms and specifically Inline EntityForms since that seems to incorporate the entityreference field.

**Approach 1**

What's interesting about the Inline Entityform is that you don't need an Entityform type to use it. You can select the Target type as 'node' and have that create a node form within the parent node's edit page.

The problem I'm facing with this approach is that you can't render the form on the front-end. I've tried setting the Display settings to 'Rendered entity' and I'm still not seeing anything on the front-end of the parent node, logged in as admin.

Is the Inline Entityform module only for embedding node add forms to the back-end?

**Approach 2**

The second approach was using Inline Entityform to target a node of type 'Rental' with the same settings but I was still unable to produce a node add form on the parent node front-end.

I do not want to use Panels but it's looking like I might have to? Any thoughts are appreciated.

# Answer
Inline EntityForm is for placing an entity's form within an Edit page of an existing Node, eg (`/node/edit/123`). It's not for showing a form on a Nodes' page with a `view_mode` set to like `full`.

You want to use either:

And then either use Display Suite or alter the Node Template for your theme to include form for reservations when people view your Node.

Alternatively you can just use 2 content types: 1 for product and 1 for reservations. and use the Prepopulate module to build a link to create a Reservation -- which you can place on the product node. Clicking this link would send the user to create a reservation, you could always send them back to the product node using `$form['#redirect']` on your reservation type.

And if you were crazy you could try to make a url using Prepopulate that loads an Ajax popup node reservation form on the product page.

Hopefully one of these ideas sets you on your path.
> 0 votes

# Answer
You might be slightly off-course with inline entityform. If you can get it going all power to you.

I am thinking of your problem in the following terms:

* You have a content type "property page" and you have a number of nodes of that content type each representing a different property that's available to rent.
* User's can browse the available properties and when they find the one they like they can press a 'Rent Me' or 'Apply' button.
* This takes them to a form with the fields pertaining to the particular property that they came from already filled out, such as 'Greenview village, apartment 2'. From here they can fill in the form with their own data and submit the form.

If I have something wrong, do let me know and I'll adjust my answer. In the meantime:

I'd have a look at this tutorial first: "Creating a simple contact form per content item with entityform"

This method passes arguments through the url, which can get messy if you are trying to pre-populate multiple fields. Enter the 'Entity Reference Autofill' module.

> The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.

Finally if your site-users have already logged in you can populate pertinent fields in the form with their data using the 'Field Default Token' module.

From your Comment I see that you are trying to embed the entityform on a node, iN which case have a look at this tutorial: "embedding an entiyform on a node" - be sure to 'update' the 'rendered entity' display option in the 'manage display' tab even if you make no changes...
> 0 votes

---
Tags: entities
---


# Question
Title: Question field in the user registration process
I am wondering if there is a module which would enable asking users why they want to join a site - i have a very small forum and want to avoid spam bots.
I am using captcha and require administrative approval for a new user but I would like to have a field which asks "why would you like to join this forum?" and have that display somewhere that I can see it before enabling the account. Does anyone have any advice? Thanks, Amy

# Answer
Go to admin/config/people/accounts/fields and add the field. In field settings enable "Display on user registration form." - you can hide it everywhere else if is only for your eyes.
> 1 votes

---
Tags: users
---


# Question
Title: Ask visitor if he want to view page on his language
I use Internationalization module on Drupal 7 for multi-language content and my default language is English and I have one more language.

The thing I have to do is:

1. To check if visitor is from country that primary language is my second language on website (there are four countries that language is spoken), I think that this checking can be done by IP address of visitor.
2. If visitor is from one of that countries there will be shown modal popup with the question if the visitor wants that page to be shown in his language. If visitor answers affirmative that page will be shown in his language, but if he answers negatively the page will be shown in default language (English).
3. It is necessary to remember visitor choice so that the modal popup doesn't show up every time, I think that it could be done by saving the cookie in visitor's browser.

Is this possible to be done through some module or the combination of modules or it is necessary to be done programmatically?

Any idea or help where to start is welcome, also the suggestion of some different concept would be nice.

# Answer
> 2 votes
Just some ideas: I remember a WordPress multilanguage plugin setting that I had the option

> Detect the language of the browser and redirect accordingly.

That must work similar for Drupal. So, I'ld guess you would try that browser language approach. D6 even had an own function for this `language_from_browser`. I bet there must be something in D7 for that as well.

Once you have the language you might conditionally display the modal window from that. Inside the modal then there'ld be a little form, maybe just two submit buttons "Yes language", "No language", something like that.

Inside your form submit function you may find a way to trigger the redirect to the chosen language. Finally you might want to save the user's answer in a `$_SESSION` variable and bind that as a condition for the modal display also.

Put all of that in a little custom module and let us know how you've done!

---
Tags: 7, i18n-l10n, location, javascript
---


# Question
Title: How add javascrip file to a node? (module)
I have create a module who add a new node named SquareOffs. I make that in my squareoffs.info file.
I would like to add to that node a javascript file, squareoffs.js, but I don't know to do that.

I have seen the drupal\_add\_js() documentation but I don't know understand how it works, how can I add the js file to this node??

Thank you very much for your answers or your sugestions!!

# Answer
> 0 votes
Yes. `drupal_add_js()` is used to add js in your theme or custom module.

I assume that the node has been fetched under this custom module.

If you want to add in your module. Use this

```
drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/squareoffs.js');

```

The js file can be added as inline and external too.

For more details Click Here

Once the js file has been included, it will be applied to all the nodes under this custom module.

OR If you want to add a js for particular content type. You can add preprocessor function in my custom module:

```
function mymodule_preprocess_node(&$vars) {
    if($vars['type'] == 'Nodetype') {
        drupal_add_js('drupal_get_path('module', 'mymodule') . '/js/squareoffs.js');
    }
}

```

# Answer
> 3 votes
You can add your js through `drupal_add_js()` function. You can control on which pages this js should be added by implementing different hook and calling `drupal_add_js()` function in those hooks:

1) Use drupal\_add\_js() in hook\_init() if you want to add this js on all drupal pages.

```
function mymoduel_init() {
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.js');
}

```

2) Use drupal\_add\_js() in hook\_node\_view() with content type condition check if you want to add this js on only specific content types.

```
function mymodule_node_view($node, $view_mode, $langcode) {
  if($node->type == 'my_content_type') {
    $node->content['#attached']['js'][] = array (
      'type' => 'file',
      'data' => drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    );
  }
}

```

3) Use drupal\_add\_js() in module's preprocess function if you want to add this js only on specific node

```
function mymodule_preprocess_page(&$variables) {
  if (isset($variables['node']) && $variables['node']->nid == 'your node nid') {
    // Add js
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.awesome.js');
  }
}

```

You can implement this preprocess\_page at theme level like mytheme\_preprocess\_page($variable) in theme's template.php file.

# Answer
> 0 votes
If you are working on developing a website, I suggest you to use JS injector Module and you can insert you jQuery/JavaScript into your website theme. To insert a jQuery, navigate to `Configuration -> development -> Js Injector -> Add.`

You can add your JScode as :

```
(function ($) { // your jquery goes here... })(jQuery);

```

If you are working on developing a module, go through this link and add your javaScript.

---
Tags: 7, nodes, javascript
---


# Question
Title: Can't direct a domain to a working D7 test site
I've created a D7.29 test site on godaddy's "deluxe classic hosting" plan at www.mybusiness.com/test and it works great. The site structure is root\mybusiness\test. Now I've been trying to copy it to the root and direct a client's web domain to that copy and now all the user gets is the first page (very quickly I might add, like it was a static page) but all links that you click on or when trying to log in just result in "Internal Server Error..."

I then tried to direct the client's domain www.hissite.com to the original test site's folder at root\mybusiness\test and all it results in is the same error, even after waiting an hour.

I then read about the settings.php option of base\_url = 'http://www.hissite.com'; so I enabled that and still get the same error. What's wrong? How come I can't just direct a domain to a working Drupal instance?

Any help would be greatly appreciated!!

Dave N

# Answer
Fundamentally, there is absolutely no problem with pointing a domain to a functioning Drupal instance. That being said, there are many other things that can be going on here. Let's tackle a few of them.

1. First of all, when you change the DNS settings for a domain, it can take a day or more to fully propagate, due to the way different DNS servers cache their entries. To make matters worse, the change can make it to you at a different time than someone else, which makes it difficult to detect what is going on.

If you want to see results immediately for testing, then you need to manually add an entry to your hosts file that points the domain name to the server that you want to see the results for. In a Linux machine, the hosts file is `/etc/hosts`, and on a Windows machine, it is `\Windows\System32\drivers\etc\hosts`. You add an entry just by adding a new line to the end of the file in the form of:

`XXX.XXX.XXX.XXX www.hissite.com`

where the `XXX`s are the IP address of the target server. The change is instant when you save the hosts file (i.e. no need to restart).
2. `$base_url` is a setting that affects how Drupal creates URLs internally. If the links that Drupal is creating look correct (e.g., www.hissite.com/node), then it is working correctly.
3. This could be a problem with clean urls. If you go to `www.hissite.com?q=user`, and that works, but `www.hissite.com/user` does not, then the server is not correctly interpreting clean urls. Your only options are to either enable clean urls or to choose a different host, since you likely don't have direct access to the server settings. (Disclaimer: I haven't used GoDaddy's service, so I don't know the extent to which you can modify server settings.) Basically, if the server is running Apache, then, in order for clean urls to work, Apache must be allowed to parse your `.htaccess` files, and it must have `mod_rewrite` enabled.
4. A final test would be to see if perhaps the `.htaccess` file is not being interpreted at all. Try going to `www.hissite.com/index.php?q=user. If that works, but www.hissite.com/?q=user` does not, then it is definitely a server setup issue, and I do not know if GoDaddy provides you with the tools to fix it.

Finally, I want to address your fundamental problem as I see it: you are using GoDaddy. I'm slightly biased against them for various reasons, but mostly I think that you can have a better experience for roughly the same cost by setting up your own VPS somewhere. I use DigitalOcean, and have for quite some time (I have no affiliation with them other than being a customer). For the same cost of the GoDaddy deluxe hosting, you can have your own small VPS which can run several sites. I do this with my personal site, http://cscrunch.com, as well as a handful of other, family sites.
> 1 votes

---
Tags: 7
---


# Question
Title: drush 6.2.0 reports no version control found for core updates, but DOES find and use svn for module updates (pm-update)
for drush 6.2.0, when running:

```
drush pm-updatecode --version-control=svn --svnsync --svncommit

```

on a drupal 7 site that only needs module updates, drush will properly commit the changes to svn as expected:

```
Project committed to Subversion successfully

```

however, if the site has a core update, drush will report:

```
No valid version control or backup engine found (the --version-control option was set to "svn").

```

and fail. does anyone have any idea why this is occurring, or what i should do to fix it?

# Answer
I haven't used --version-control=svn for a while, and never liked --svncommit. In any event, it looks like you have found a bug in Drush. This should be reported in the Drush issue queue; however, since the current maintainers have pretty much moved on to git, I am not sure this code will continue to be supported unless a volunteer stands up to fix and maintain it.

In the meantime, you might try downloading Drush 5, and install it as a secondary version, perhaps setting up an alias 'drush5' to point to the older install, and use it only for core upgrades. If that does not work, you could even try going back to Drush 4. Note that neither Drush 5 nor Drush 4 are supported, though.
> 0 votes

---
Tags: drush
---


title: Push value into array using form

text:
# Question
Title: Push value into array using form
I am working on developing a type of bucket that would store my selected content in some sort of data container (I am hoping to store it in an array). The selected data comes from default views, I wrote an handler to add a 'ADD' button to the default view. I am new to drupal and have very less experience with form api and not really sure how to push/store the selected content.

The following is the handler code:

```
<?php

 /**
 * @file
 * handler class for the new field 'bucket'
 */

/**
* class definition
*/
  class bucket_views_handler_field_actions extends views_handler_field {
 /**
 * Render function: return html output
 */
  function render($values) {
   //debug ($values);
    $biomaterial_id=$values->biomaterial_id;
    $form=array();
    $form['Add']=array(
     '#type'=>'button',
     '#value'=>'ADD',
     '#access'=>TRUE,
      );
  }

```

# Answer
> 0 votes
You could try creating a session variable. Taken from this question

You can try this.

```
function lists_session($key, $value = NULL) {
static $storage;
if ($value) {
$storage[$key] = $value ;
$_SESSION['lists'][$key] = $value ;   // I use 'lists' in case some other module uses 'type' in $_SESSION
}
else if (empty($storage[$key]) && isset($_SESSION['lists'][$key])) {
$storage[$key] = $_SESSION['lists'][$key];
}
return $storage[$key];
}

```

So, to save a variable in Session:

```
lists_session("s_key", "value");

```

And to retrieve the value, just use:

```
$myVar = lists_session("s_key");

```

**EDIT**

To attach the above to the form submit (Add), try the following, taken from this question. You can do this in template.php with THEMENAME\_form\_alter if you prefer not to create a new module, but it would be theme specific if you do that.

You will need to create a custom module with hook\_form\_alter() implementation.

```
function [YOUR_MODULE]_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == "YOUR_FORM_ID")
  {
    // target the submit button and add a new submission callback routine to the form
    $form['#submit'][] = 'YOUR_SUBMISSION_CALLBACK_FUNCTION';
  }
}

```

The code above will execute your new callback function YOUR\_SUBMISSION\_CALLBACK\_FUNCTION AFTER the form's default callback function.

To make your new callback function called BEFORE the form's default callback function, use the following code instead of the giving above:

```
array_unshift($form['#submit'], 'YOUR_SUBMISSION_CALLBACK_FUNCTION');

```

To cancel the form's default callback function and force it to use your function ONLY, use the code below

```
$form['#submit'] = array('YOUR_SUBMISSION_CALLBACK_FUNCTION');

```

---
Tags: forms
---


# Question
Title: How can I translate this domain model into the desired front page
I am quite new to Drupal and CMS alltogether and have some problems choosing the right way to setup my site to achieve my desired result. What I want to do is to create a page for my basketball club to read about upcoming games and practices and get some game reviews.

**Domain Model:**

So I have a team entity type which represents the different teams in my club. Each team has some reviews, games and standings associated to them.

I think about representing each entity type as a content type and setup the relationship by using entity references.

*Is this the common way to do this are is there another recommended way?*

**FrontPage:**

And now I want the front page to look like this ("conceptually"):

I want a row for each team, containing the latest game review, the standings and the upcoming games. Of course I want only those related to the team to show up in the given row.

*And I honestly have no clou how to approach this? How would you do this?*

Best regards, Marco

# Answer
> 0 votes
Your best bet is probably Views. It can be set up to do exactly what you want. There are hundreds if not thousands of tutorials on how to use it.

# Answer
> 0 votes
You are right in using entity references. And you can implement it completely in views.

You can set the field display on an entity reference field to display the rendered referenced entity. You do this on the create content type display page. This might be the easiest route to go as it simplifies your view considerably. Now you only add your team type to the view and don't bother with the relationships at all as long as you select rendered entity as the output type.

You can go the fields route in views also. Team will be your base type for views, then you add relationships to the other three content types. You then add the required fields from all of the related content types, set their field display to none, add a global text field for each related type wherein you rewrite the content of the global text field and selectively include the fields you need. You then end up with three global text fields that each encapsulate only the fields of one related content type each.

You can also add a module or two. I would look at EVA and Display Suite. With both of them you are able to create a field on a content type (team) that can display the output of a view. You will then add three fields (one for each of the related content types) and three views that take the nid of the team as a contextual filter and return their respective results filtered thereon. The results can return rendered entities. Now you can reorder and format your fields using a specific view mode on the create content type display page.

---
Tags: entities
---


# Question
Title: How to make form update/rebuild every page load?
Part of my **custom form** that gathers petition signatures includes some markup saying "last signer: Bob, 3 minutes ago", looked up from a database.

But if the user does not submit the form, eg they reload the page, or look elsewhere then come back to the page, the form is rendered from cache and so it still says 3 minutes ago.

What can I do?

Notes:

* I am not using varnish or memcached or anything else fancy that might interfere with caching. It's a very simple sure. The behaviour is seen for anonymous users. The form is used in a block, and the block is defined with DRUPAL\_NO\_CACHE.
* The form has AJAX submission (although it must work for non-js-enabled browsers, too). I have since learnt that:

> cache: ... ajax\_process\_form() enables form caching for all forms that include an element with the #ajax property. (The Ajax handler has no way to build the form itself, so must rely on the cached version.)
>
> no\_cache: If set to TRUE the form will NOT be cached, even if 'cache' is set.

So the question seems to point to: how can I force a form cache reset for a page load that is NOT ajax-related, e.g. in `hook_block_view()`? As this would mean caching was ON (required by ajax), and can stay there for form submissions, but a page load without user input will regenerate the form?

# Answer
> 0 votes
If you are not using Varnish or other server caching, first, I would try CacheExclude Module or something similar to prevent the page that the form resides on from being cached. In this way it should reload every time.

---
Tags: 7, forms, caching
---


title: How to change Zen Grid System

text:
# Question
Title: How to change Zen Grid System
Zen is a great theme and comes by 3 columns gris as default and even when i read the documentation i don't know how to change the grid system to 2 columns 30%- 70% for ex.. Can you help me please.

# Answer
```
$zen-column-count: 10;

.container {
 @include zen-grid-container;
}
.column1 {
 @include zen-grid-item(3, 1);
}
.column2 {
 @include zen-grid-item(7, 4);
}

```

You include 10 columns, and use 3 for 30% and 7 for 70%. Reason being that columns are of equal width and if you want to implement two unequal columns you have to use multiples of a common denominator.
> 1 votes

---
Tags: theming
---


# Question
Title: Views: Only show 3 largest values and their sum per user
I am creating a scoreboard website for fisherman that shows the sum of their top catches for the day. A custom content type allows the anglers to upload a photograph, fish type, and fish length numerical value (DONE). Anglers may upload as many catches per day (DONE) as they want. I have Views showing me all fish caught (DONE). I have Views\_Calc showing me data about "all fish caught" per day (DONE).

However, I only want to calculate, display, and store in the database the SUM of the X longest fish an angler has caught that day.

So, I'm trying to build:

1) A View ranking anglers by the sum of their, say, 5 longest fish caught per day.

Consider that some anglers may have a tough day fishing and only be able to upload, say, 3 fish per day. Conversely (and this is the situation I am having trouble rendering) an angler may submit, say, 14 fish caught that day but I only want to display the sum of the 5 longest.

I would like the SUM to be a database entry so it is accessible via Views for other purposes.

The rendering may look like:

> ```
> RANK   |  ANGLER NAME  |  5 LONGEST FISH
>   1    |  John Smith   |   49.75 inches
>   2    |  Joe Blow     |   47.25 inches
>   3    |  Kevin Jones  |   42.50 inches
>   4    |  Dave Craig   |   37.75 inches
> ...
>
> ```

Any pointers? Thanks in advance!

# Answer
> 0 votes
If you don't want to build a custom module I would think Rules is your best bet. Also install Conditional Rules as what you will be doing will requires logic a bit difficult to accomplish with Rules alone.

I will create a Result content type that will hold the aggregated result for the day per angler, as well as entity references to the fish content type. Then, after the angler uploaded a new entry, the rule will cycle through the related fish types and do the Maths and store the result in the result field.

---
Tags: views
---