# Question
Title: How to theme a radio button field on node edit form?
The standard way the radio buttons field is rendered on a node add/edit form is that there is a wrapper div with classes:

`form-item form-type-radio form-item-mymodule-imglayout-und`

and inside there are input and label elements. Where to hook to change this? I would like the wrapper div to have classes:

`form-item form-type-radio form-item-mymodule-imglayout-und mycustomclass`

And the custom class should be dependent on the option the button represents, or just be sequential: first, second, third, ...etc

Additional info:

My point is to be able to add a distinct big background image to each radio button, depending on the option it represents. Like below - note that each radio button has an associated image, representing its option visually.

# Answer
> 2 votes
Here is a possible solution to this problem which can be implemented in a custom module

```
function mymodule_preprocess_radio (&$variables) {
  $element = &$variables['element'];
  if ((isset($element['#name'])) && substr($element['#name'],0,18) == 'mymodule_imglayout') {
    $variables['theme_hook_suggestion'] = 'radio__imglayout';
  }
}

function theme_radio__imglayout($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'radio';
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));

  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-radio'));

  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
  $id = $element['#id'];
  $mydiv = "<div class = 'imglayout {$id}'></div>";
  return   $mydiv .'<br/>'. $output  ;
}

function mymodule_theme($existing, $type, $theme, $path) {
   return array(
     'radio__imglayout' => array(
       'render element' => 'element',
     ),
  );
}

```

The `$mydiv` has a distinct class and is placed before the `<input>` and `<label>` elements, so just float it to the left and give each one width and height and a distinct background image - it will be displayed just above the radios (not below as I wanted originally but that's minor).

# Answer
> 2 votes
I think what you need to do is just altering the form array. You can accomplish this in your own hook\_form\_alter implementation.

For example:

```
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'YOUR_CONTENT_TYPE_node_form') {
        $form['YOUR_ELEMENT_NAME']['#attributes']['class'][] = 'your-custom-class';
    }
}

```

# Answer
> 0 votes
I accomplished this in the theme layer with the following theme function:

```
function THEME_form_element($variables) {
  $element = &$variables['element'];

  // This function is invoked as theme wrapper, but the rendered form element
  // may not necessarily have been processed by form_builder().
  $element += array(
    '#title_display' => 'before',
  );

  // Add element #id for #type 'item'.
  if (isset($element['#markup']) && !empty($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  // Add element's #type and #name as class to aid with JS/CSS selectors.
  $attributes['class'] = array('form-item');
  if (!empty($element['#type'])) {
    $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
  }
  if (!empty($element['#name'])) {
    $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  }
  // Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element['#attributes']['disabled'])) {
    $attributes['class'][] = 'form-disabled';
  }
  if (isset($element['#type']) && isset($element['#return_value']) && $element['#type'] == 'radio') {
    $attributes['class'][] = 'form-radio-option-' . drupal_html_class($element['#return_value']);
  }
  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";

  // If #title is not set, we don't display any label or required marker.
  if (!isset($element['#title'])) {
    $element['#title_display'] = 'none';
  }
  $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . $element['#field_prefix'] . '</span> ' : '';
  $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . $element['#field_suffix'] . '</span>' : '';

  switch ($element['#title_display']) {
    case 'before':
    case 'invisible':
      $output .= ' ' . theme('form_element_label', $variables);
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;

    case 'after':
      $output .= ' ' . $prefix . $element['#children'] . $suffix;
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
      break;

    case 'none':
    case 'attribute':
      // Output no label and no required marker, only the children.
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
      break;
  }

  if (!empty($element['#description'])) {
    $output .= '<div class="description">' . $element['#description'] . "</div>\n";
  }

  $output .= "</div>\n";

  return $output;
}

```

This overrides theme\_form\_element, assigning a value-based class to each unique radio element container.

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


# Question
Title: Creating a content type that merges fields with its assigned area within the body
I have a requirement to build a content type that has a number of fields and also the body section which is where the html goes. When new content is added using this new content type the user would enter information for all the fields (like city, state, zip, etc) and at the point of saving the content that is created is a combination of what was already inside the body section plus the fields values would go in their assigned areas within the body section. What possible ways could this be implemented? Any recommendations for modules that do the above?

# Answer
> 0 votes
I think it sounds like you want to write a node template. http://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7

Basically you are going to create a template file called node--content-type-name.tpl.php and in that template you have access to the $node object which contains fields. Then write your html and use the values from $node.

---
Tags: forms, nodes
---


# Question
Title: logging in after exiting website under maintenance
i was installing updates for drupal website, while on maintenace mode. waited for updates to finish and then signed out. i've been trying a lot of things i'm reading online and it doesn't work. on another note, possibly related, when i've tried to do some editing on certain blocks i get the message that i don't have sufficient permission to edit. also, while googling online i found my website, though, with a different url that had the log-in ability, but my credientials didn't work. i believe my next attempt is to insert or edit code in the db..how can i do that? or whats the best solution? sorry to type so much, i've been doing a lot of research on this and i've become desperate.

# Answer
Are you logging in as Admin (user 1) or a site administrator? They are the only ones who have the rights to login while the site is in maintenance mode. The URL should be http://www.example.com/user/login or http://www.example.com/index.php?q=user .

KMT
> 0 votes

---
Tags: database, configuration
---


# Question
Title: Generate a fancy PDF certificate from form?
Anyone have ideas on how to generate a fancy PDF certificate in drupal based on user-supplied form input? Here's an example of what I want to do here:

http://www.infiniteskills.com/cert/01596

This form just collects a name and build a nice PDF. Not sure if the email address is used for anything (other than perhaps collecting email addresses).

I've attached a screenshot of the final PDF so you can see the result without using the form.

Thanks for any ideas or pointers.

Edit: Adding a link the Drupal certificate module: http://drupal.org/project/certificate

This module requires the print module and seems a little heavy for what I'm trying to do. Also, as far as I can tell, it will only create a PDF from existing HTML page.

# Answer
You can build a proper fillable PDF form and then use the Fill PDF module to merge it with data from a node or a webform.

Have a look at the demo on the Fill PDF service website.
> 5 votes

# Answer
Did you see Certify in the Related Projects right sidebar of Certificate module you linked !?

It sounds leaner.
> 0 votes

---
Tags: forms, files
---


# Question
Title: How do I pull content from a view into an array?
I hav a strange task where I need to pull the content from a (well some) drupal view into an array so I can use that data later. I dont want to display contents right away, but I'll need to access it later.

I have already built the view but it was suggested that I can export the view and then create a module to grab the view data but I have no idea how to do that.

Basically what Im doing, is creating a view to pull say, 9 records of node type "blog" and on the front page, I want to pull that view, throw the results into a json array, and then do stuff with it later.

# Answer
Not sure if it's what you're looking for, but if you're using a template to display that view, you can access an array of the view data by using the php code

```
$view->style_plugin->rendered_fields;

```

This will give you an array of everything that the view has returned.
> 3 votes

---
Tags: views, 6
---


# Question
Title: form_set_error highlight single field in multiple value field
Is it possible to highlight only one field with form\_set\_error when this field belongs to a multiple value field. Let's say I have a field name field\_videos which accepts multiples values. After running validation, only video #2 isn't valid :

```
form_set_error('field_videos', t('Video URL not valid'));

```

How can I tell drupal to highlight only field #2 ?

Thanks

# Answer
> 8 votes
I solved this by using the delta of the field with the error. In this example, `field_acceptable_domains` is a multi-value text field and I'm using `valid_url` to validate each value.

```
// This is a multi-value field, so we need to loop through the values.
foreach ($form_state['values']['field_acceptable_domains'][LANGUAGE_NONE] as $delta => $url) {
  if (!valid_url($url['value']) && !empty($url['value'])) {
    form_set_error('field_acceptable_domains][' . LANGUAGE_NONE . '][' . $delta, t('The domain %domain is not valid.', array('%domain' => $url['value'])));
  }
}

```

---
Tags: 7, forms
---


# Question
Title: How do I associate a field value with another value of a multi-value field?
I've run into a situation with a project in regards to field organization. I've got 3 data types, a `price`, a `date range` and a `quantity`. I've currently got 4 prices and a date grouped with it using field groups. Quantities are a multivalue check list with values between 1-12. I have since learned that there is to be a different price for every quantity, so I would end up with up to four price and dates for each value of quantity I have.

So what I would like to know is the best way to go about this. Is there a way to set fields so that I when I can set an association between a group of dates & prices with a value of quantity or do I need to go for some kind of table-based approach?

Currently it is set up like this:

```
Node {
    price1
    date1
    price2
    date2
    price3
    date3
    price4
    date4
    quantity: 4, 7, 9, etc.
}

```

and I need to re-organize it like this:

```
Quantity: 4 { price1, date1, price2, date2…}
Quantity: 7 { price1, date1, price2, date2, price3, date3…}

```

# Answer
I've found what may be a possible solution using the Field Collection module.
> 0 votes

---
Tags: 7, entities
---


title: How do I turn off teasers?

text:
# Question
Title: How do I turn off teasers?
I have a Drupal 7 site and on some pages, such as the front page. I don't want a list of teasers to show; I just want a Basic Page to show. How do I do this?

I have looked in content types, blocks, and in the edit screens of the content items themselves, to no avail!

# Answer
You have different ways/options to solve your issue.

**Option 1:** Create a page node and then set node URL as default front page in `admin/config/system/site-information`

**Option 2:** Create a view page using Views module and set the page url as default front page (same as previous option).

**Option 3:** Download and Enable Empty Front Page module and then locate any block you want in the content region.
> 4 votes

---
Tags: nodes
---


title: no www redirects to front page

text:
# Question
Title: no www redirects to front page
I recently taken over a Drupal site to maintain and work on the design bit. I'm having an issue where if I enter a page on my site without the www prefix, I get directed to the front page. You should of course end up on the correct page anyway, maybe with the www prefix added.

I'm checking the .htaccess file and there i noticed this part:

```
 # If your site can be accessed both with and without the 'www.' prefix, you
 # can use one of the following settings to redirect users to your preferred
 # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
 #
 # To redirect all users to access the site WITH the 'www.' prefix,
 # (http://example.com/... will be redirected to http://www.example.com/...)
 # uncomment the following:
 RewriteCond %{HTTP_HOST} !^www\. [NC]
 RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
 #
 # To redirect all users to access the site WITHOUT the 'www.' prefix,
 # (http://www.example.com/... will be redirected to http://example.com/...)
 # uncomment the following:
 # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
 # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

```

As you can see I did comment out the first two rows so I thought this would correct this issue, but no, I get no change at all. Anyone got any idea about what could be wrong?

I also noticed this lines, which mentions a index.php redirect. But I can't really understand if this causes my problem.

```
 # Pass all requests not referring directly to files in the filesystem to
 # index.php. Clean URLs are handled in drupal_environment_initialize().
 # RewriteCond %{REQUEST_FILENAME} !-f
 # RewriteCond %{REQUEST_FILENAME} !-d
 # RewriteCond %{REQUEST_URI} !=/favicon.ico
 # RewriteRule ^ index.php [L]

```

There seems to be no 404 page but every wrong adress get redirected to the front page.

# Answer
> 1 votes
Try using this old method

```
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

```

Replace example with your domain name.

Still if you have the problem check your Redirects in Hosting Control Panel or you can contact them to support this.

---
Tags: redirection, .htaccess
---


title: Two different gallery in one gallery

text:
# Question
Title: Two different gallery in one gallery
I created two gallery with **different content type** and **different views** (gallery1 & gallery2)...and i want to make it in one gallery containing **one image of each gallery** (one of gallery1 & one of gallery2)... please help me with video or something else...and tell me what i have to do ? i use Drupal 7 & thx

# Answer
> 0 votes
Create a new View and add the two content type in **Filter criteria**

Add the two image fields in **Fields** section

Under **Multiple field settings** set "1" in display option for both images

Select your Format for views, hope it helps you!!

---
Tags: views, media
---


title: Password reset email is not valid?

text:
# Question
Title: Password reset email is not valid?
In setting up a new Drupal 7 site, I went to try out the password reset option, and while I received the password reset email just fine, clicking it takes me to a page with an error "You have tried to use a one-time login link that has either been used or is no longer valid".

I've tried sending the reset email a few times and clicking the link immediately each time, and keep getting the same error message. What sort of things make a reset link "no longer valid"? I'm working on a staging server that will be translated to a live server, so URLs and cookie paths might be getting tangled; where do I need to start looking to unravel this?

Note: The user accounts being tested were imported using the Migrate module from another system, hence their passwords are invalid, and I'm hoping users can just request a new password to login.

# Answer
> 0 votes
It's not documented nicely anywhere I can find, but it seems that you can't use the password reset option via email for a user who's an Administrator of the site. Instead you have to use some alternate method to change the database directly, like this.

# Answer
> -1 votes
That's not the case - you should be able to get admin password reset by using the link /user/password . The problem I found was its not set to my domain, instead it set to gmail.com .

After i changed to my domain, I started getting emails for Password Reset from my D7 installation.

---
Tags: 7, users
---


# Question
Title: accessing block type in the theme_preprocess_node()
I have a block which include a view which is based on node.tpl.php, and I want to change the mark up in the node.tpl.php file just for a specified block.

```
function theme_preprocess_node(&$variables) {
  $block = unknown_way_to_get_it();
  if ($block->region == "product_stream") {
    $variables['theme_hook_suggestions'][] = 'node__productstream';
  }
}

```

How do I get a block from the preprocess function?

# Answer
> 1 votes
You can't get access to a block object from a node preprocess hook; the context simply isn't passed down the chain.

As you're using a view, though, you can get hold of the View object, and test the name/display id. The basic idea would be:

```
function theme_preprocess_node(&$variables) {
  if (!empty($variables['view'])) {
    if ($variables['view']->name == 'some_view' && $variables['view']-> current_display == 'block_1') {
      $variables['theme_hook_suggestions'][] = 'node__productstream';
    }
  }
}

```

---
Tags: theming, blocks
---


# Question
Title: Where and how does drupal store the node body in drupal 7?
I am programatically trying to create a custom node to store some content, which I would like to display on a page. Following is how I am executing it.

```
    $node = new StdClass();
    $node->name = $value;
    $node->title = $node->name;
    $node->language = LANGUAGE_NONE;
    $node->body[$node->language][0]['value']   = $javascript.$html;
    $node->body[$node->language][0]['summary'] = $type;
    $node->type = "custom_type";
    $node->created = time();
    node_save($node);

```

I notice that the content I inserted are present in the tables 'field\_data\_body' and 'field\_revision\_body' I try to load the node and get the content

```
   $query = new EntityFieldQuery();
   $entities = $query->entityCondition('entity_type', 'node')
              ->propertyCondition('type', 'custom_type')
              ->propertyCondition('title', $type)
              ->execute();
   if (!empty($entities['node'])) {
        $node = node_load(array_shift(array_keys($entities['node'])));
        $html = $html.$node->body[$node->language][0]['value'];
   }

```

But what puzzles me is how from where is the content being loaded. I deleted the entries in both 'field\_data\_body' and 'field\_revision\_body', but the content still gets loaded.

So how does drupal7 save and load the contents of the node body?

# Answer
If you emptied out the field\_data\_body (and revision) table and you are still getting data that can only mean three things:

1. you emptied the wrong table (wrong database or the right database with the wrong prefix)
2. it's still cached (there's a clear cache button on the `admin/config/development/performance` page).
3. You are not using SQL to store your fields. Do you have `mongodb_field_storage` enabled? Something even more exotic?

As for how it gets stored, `node_save` calls `field_attach_insert` (and `node_load` calls `field_attach_load`) which, in turn, calls the field storage module which I presume is `field_sql_storage` and so `field_sql_storage_field_storage_write` writes your database records and `field_sql_storage_field_storage_load` loads them.

Also note that `array_shift(array_keys())` is wrong (`E_STRICT` error: `Only variables should be passed by reference` because array\_shift takes a reference and array\_keys is not returning by reference. Finally, you should feed your `EntityFieldQuery` code to the coder module to fix the coding standards: at least the code inside the if is indented wrong and the string concat operator (the dot) needs spaces on both sides. It hurts my eyes :)
> 2 votes

---
Tags: nodes
---


title: Compression in Drupal 7

text:
# Question
Title: Compression in Drupal 7
I am running Drupal (latest version 7.22 ) on Apache 2.2 and I have also installed Varnish (module and proxy). In Apache, I have disabled the mod\_deflate module. Reading around the web, it seems that the options on the performance page in Drupal (aggregate css,js) shouldn't compress the css and js files. However, browsing my site and checking the http headers, I see that I am receiving "Content-Encoding: gzip". Looking at the (default) .htaccess, I see that there are some rewrite rules in order to server gziped files to those clients that can read them. So, I guess this is where the "Content-Encoding: gzip" headers come from. Also, when I enable compression of cached pages on the performance settings page in drupal, I find that even the html of the page I am requesting (as anonymous user only) is returned compressed. My questions on the above are:

1) Do the options "Aggregate and compress CSS files." and "Aggregate JavaScript files." actually compress the aggregated files or is it just that .htaccess makes them seem like gziped? Using chrome developer tools, the files seem compressed. Checking them with the developer toolbar addon in firefox, however, (Information -\> View document size) they are not reported as compressed (while the html file is always being reported as such, even when I access it as authenticated user!)

2) If they are indeed gziped, where does the compression take place? Can I control the level of compression, etc somehow?

3) I am always receiving X-Drupal-Cache "MISS". I don't care much since I have Varnish installed. Yet, since I am not hitting the cache, how come I am returned a compressed html file (that is not in the cache)?

4) Is there any chance that the Varnish module messes anything up? I am accessing the website with https so as to be sure that Varnish is bypassed, in any case.

5) If I enable mod\_deflate, should I leave that part of .htaccess intact? I understand that mod\_deflate doesn't allow for precompression, but what if the compression is better?

6) Also, if drupal compresses on its own the css, js and html files, what is the point of enabling mod\_deflate for these files?

Here is the relevant part of my .htaccess file for reference:

```
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>

```

# Answer
> 0 votes
To sum up what I have found so far and fietserwin's answer.

1) Those options do compress. No matter what you have read elsewhere. I went through some bugs in the drupal bug tracker and there are a couple bugs (eg this discussion for d8) that discuss actually separating this behavior with different options in the Performance settings in drupal. Also, you can check it with Chromium devtools or Firefox Network panel (not through the size column, but by checking the response headers for Content-Encoding: gzip) and toggling the available options for css/js aggregation in drupal. The developer toolbar seems broken or I cannot understand what it does.

You can have aggregation but no compression by setting the css\_gzip\_compression and js\_gzip\_compression variables to FALSE (see fietserwin).

2) The compression happens in php code. For more detail, look fietswin's answer. Judging by his answer on the compression level, I guess that php (at least for drupal) compresses at the maximum level of compression. Note that compressing in php and not relying on the web server is common for many other php applications, eg owncloud, flyspray, etc.

3) This is a bit weird and still haven't figured out why it happens. I think it has to do with the varnish module. I am not saying varnish itself, since I am running varnish 2 with no compression support). It only happens when I access the site through varnish (ie, when I access it with https, which bypasses varnish, the page is not cached and not gzipped). And if I have the "Compress cached pages" option enabled. So, my guess is that the varnish module completely takes over the caching mechanism of drupal but still uses these options to set the behavior (compression,lifetime,etc) of the varnish cache.

Since I couldn't find any more info on this and I have mod\_deflate set to gzip all html files, I disabled this option to prevent the cached pages from being double compressed. Maybe there is a check or sth, as with css/js, to prevent this but I haven't found one.

4) *obsolete question*

5) Compression should happen in drupal, not in apache. There, it only happens once (in a while). So the .htaccess excerpt above should be left intact. What it does is:

```
RewriteCond %{HTTP:Accept-encoding} gzip #if the client can handle compression
RewriteCond %{REQUEST_FILENAME}\.gz -s #and if the (aggregated css file already exists
RewriteRule ^(.*)\.css $1\.css\.gz [QSA] #serve the compressed file instead

# The same for js files
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}\.gz -s
RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

# Do no actual rewriting but set the no-gzip apache variable to inform apache not to compress the already compressed files.
RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

```

So this part should be left intact to safely take advantage of the whole mechanism. The compression, as said above, probably is the best possible.

6) To add to fietserwin's answer, there might be other apps running on the server as well. All in all, just enable compression for css and js in apache as well, and drupal's htaccess will prevent double compression.

# Answer
> 3 votes
A start:

1) Yes.

Note: If I really want to know what is going over the line, I use fiddler (Windows).

2) See function drupal\_build\_css\_cache() in common.inc (line 3603). You cannot influence the level but you can influence whether it compresses or not with variable 'css\_gzip\_compression', see default.settings.php line 432.

BTW: You do not want to influence the compression level: for compress once, use many cases, maximum compression is always the best. Transfer time and decompressing time at the client is linear with compressed document size. So a 1-time slightly increased performance hit will save a lot of network activity and client side processing in the future.

3) -

4) -

5) Compression will be better as it will be done only once and it will be done better versus mod\_deflate that will compress on each request and therefore will use a lower compression level. I don't know much about mod\_deflate, but I guess that if there is already a Content-Encoding header that tells the content is compressed, mod\_deflate should not touch it. But I have had cases where I got a backup file that was compressed twice, so mod\_deflate might not be that smart and should explicitly be told to do so.

6) There is no point, but there might be for other requests, especially dynamic ones, i.e. non cacheable pages. Note that only aggregated css and js and cached pages (variable 'page\_compression') are compressed by Drupal. Non cacheable pages are not compressed by Drupal.

---
Tags: 7, performance, css-js-aggregation
---


# Question
Title: open node reference links in lightbox/ popup
I want in my node view pages, node reference links open in popup window or lightbox window. Does anyone have a solution?

# Answer
> 1 votes
In Views Use this code in "Rewrite the output of this field"

```
<a href="[path]" rel="lightframe[][My Title]">[title]</a>

```

Note: add "Node:Path" field before the Rewrite field.

You can also set the width and height of the popup window, see the read-me file in Lightbox2 module folder.

hope you will get idea from the above!!

---
Tags: 6, entities, nodes
---


# Question
Title: Product Reference inside a Product Reference?
In my attempt to solve a "variation can update second variation" issue, I am wondering if a Product reference can go inside another Product Reference?

So that the 'Variation' itself has a product reference inline form to another type of variation? ( I have tried and nothing shows up).

The idea is that loading 1 variation will then load the referenced product variations therein and combine the 2 to create the final price.

(This is a case where the 2nd variations price is based on what is selected in the 1st variation.)

# Answer
I figured this out by using taxonomy terms (categories in commerce kickstart), and then yes, indeed, make a product for each combination. (ive heard bulk product creation can do this, and incase you are dealing with a customer input size (how many inches long do you want it), then check out custom line items and Pricing rules.

Thread on drupal commerce \> http://www.drupalcommerce.org/questions/7894/adjust-variation-price-based-next-variation#comment-7566
> 0 votes

---
Tags: commerce, entities
---


# Question
Title: Load a variation (or Line Item) based a previous choice
I asked this similar question already (Variations price adjust based on previous variation), but I am thinking to make the solution more 'base'.

Is there a way to 'load' different fields based on a selection of a previous field?

If I select 'Size: Medium', I want to load those colors and styles that have a different price than 'Size: Small' has.

# Answer
> 0 votes
Please use COMMERCE OPTION module with COMMERCE PRODUCT ATTRIBUTES to explore the possibility of achieving this. Go through by documentation for using it properly & I hope you will have fun in achieving what you want...

# Answer
> 0 votes
My answer for the next guy searching here...

I figured this out by using taxonomy terms (categories in commerce kickstart), and then yes, indeed, make a product for each combination. (ive heard bulk product creation can do this, and incase you are dealing with a customer input size (how many inches long do you want it), then check out custom line items and Pricing rules.

Thread on drupal commerce \> http://www.drupalcommerce.org/questions/7894/adjust-variation-price-based-next-variation#comment-7566

---
Tags: commerce
---


# Question
Title: What is the most robust way to assert for a validation error?
I want to test the validation function in my custom module, and so I've written a simpletest that inputs an illegal value in a field and then attempts to save the node. Currently I'm using `assertText()` to find the string contained in the validation failure message on the page, but if someone changes the wording of the failure message in the future, this could break. Is there a more robust way to check that a field, or even a node save generally, failed validation?

# Answer
I found this solution, for Drupal 7.

```
try {
  custom_validation();
  // if validation passes incorrectly then:
  this->fail("Validation should have failed, but didn't");
}
catch (Exception $e) {
  $this->assertEqual('Expected error message', $e->getMessage, 'Test successful message');
}

```

Use `\Exception $e` in Drupal 8.

Thanks to dawehner on #drupal-contrib for help with this.
> 1 votes

# Answer
Since you are talking of custom validation, if the code is using form\_set\_error() or form\_error(), then there should not be any problem, if the test code and the form validation handler use the same string (which is passed / not passed to `t()` in both the cases).

Keep in mind that the modules enabled during a test execution are Drupal core modules enabled from the profile used for the tests, or modules explicitly enabled from the test class. The error message output from your form validation handler is not altered, if the modules enabled from the test class don't alter it.

An alternative method of checking if a validation handler returned an error would be setting a global variable, for example; that is something Drupal does, but only from a module that is used only for testing, not a module that is normally executed. For example, entity\_crud\_hook\_test\_comment\_delete() (the implementation of hook\_comment\_delete() done from the Entity CRUD Hooks Test module) uses a session variable that is set when the hook is invoked.
Notice that this is what Drupal normally does to verify a hook is effectively invoked when it should. When you need to verify if a form validation handler returned an error, I would rather use the method you are using, since:

* It doesn't require the form validation handler to know if it is being executed during test, or not
* It doesn't require the use of a test module

There are some cases where a module needs to be created with the only purpose of testing something, but that is not generally the case of verifying a form validation handler effectively returns an error when it should.
> 1 votes

---
Tags: testing, forms
---


# Question
Title: Mapping existing file against a new content type
I am facing a situation here.

I have a content type A with an image field(field\_upload\_snaps) in it. There is another content type B which also contains an image field(field\_valid\_snaps).

Now user will upload the pics from A content type. So if user upload 3 pics via A then 3 FID and their corresponding URIs will be created in file\_managed table in Drupal 7.

Now I have a requirement where I have to insert 2 images out of 3 programatically using Drupal code. Now there is no need to generate any new image copy in public URI as images already exist via A.

I tried two approaches:-

1) I have created a new node of Type B. I tried to fetch file URI,filesize,filemime and all relevant parameter from existing fid and associate with the node using this.

```
 global $user;
 $node = new stdClass();
 $node->type = "user_slideshow_snaps";
 $node->language = LANGUAGE_NONE;
 node_object_prepare($node);
 $node->uid = $user->uid;
 $file = (object) array(
  'uid' => $user->uid,
  'uri' => 'public://1.jpeg" ,
  'filemime' => 'image/jpeg',
  'status' => 1,
 );

 $node->field_upload_snaps['und'][] = (array)$file;
 $node = node_submit($node); // Prepare node for a submit
 node_save($node);

```

But it gives me an error that "Cant insert duplicate value in file\_managed". It will give because such value already exist in file\_managed via A. So I am not able to save value.

2) I saved node first and then manually insert in the image field like this.

```
 global $user;
 $node = new stdClass();
 $node->type = "user_slideshow_snaps";
 $node->language = LANGUAGE_NONE;
 node_object_prepare($node);
 $node->uid = $user->uid;
 $node = node_submit($node); // Prepare node for a submit
 node_save($node);

 db_insert('field_data_field_valid_snaps')
    ->fields(array(
    'entity_type' => 'node',
    'bundle' => 'user_actualD_snaps',
    'deleted'=> 0,
    'entity_id'=>$node->nid,
    'delta'=>0,
    'field_valid_snaps_fid'=>517,
    'field_valid_snaps_alt'=>'',
    'field_valid_snaps_title'=>'',
    'field_valid_snaps_width'=>200,
    'field_valid_snaps_height'=>300,
    ))
    ->execute();

```

But the line after node\_save() doesnt execute in this case. So I am not able to save it.

Are there any functions available which will map existing images into another table?

# Answer
> 0 votes
I think the File Field sources module will solve your problem. (The D7 version works directly with the core *Field* module). It will, among other things, allow you to re-use files by an auto-complete textfield.

Btw: Any file appearing in `file_managed` can only appear once in that table, so you should not be allowed to do what you try to do in your first approach.

# Answer
> 0 votes
File\_load API solved my problem of getting the dimensions of existing file and save in another content type.

---
Tags: 7, files, nodes
---


title: Adding a file to a node programatically

text:
# Question
Title: Adding a file to a node programatically
I am working on a module that is transferring files from my old site (hosted on the same server) to a new drupal based site. The files will be associated with a single content type (the content type has multipel file fields associated with it). I've written code to read a directory and then loop through the files, associating the files with the appropriate file file. So far the files are getting transferred correctly, but they aren't being associated with the new node. What am I missing

```
$result = new stdClass;
$result->type = "results";
node_object_prepare($result);

//add values to text fields here
...

//open the source directory
$d = dir($seasonDir);
while(false !== ($entry = $d->read())) {
      if($entry != "." && $entry != "..") {
        //set the file location
        $fileLocation = $seasonDir . "/" . $entry;
        //get the file contents
        $fileContents = file_get_contents($fileLocation);
        //save the file
        $file = file_save_data($fileContents,'public://results/'.$entry,FILE_EXISTS_RENAME);
        //store the file for copying to a subdirectory later
        $result_files[] = $file;
        //create an array to assign to the various file fields
        $file_details = array(LANGUAGE_NONE => array('0' => (array)$file));
        switch($entry) {
          case "results.inc.html":
            $result->field_results_html = $file_details;
            break;
          case"clubs.inc.html":
            $result->field_clubs_html = $file_details;
            break;
          case "events.inc.html":
            $result->field_events_html = $file_details;
            break;
          case "index.xml":
            $result->field_results_index = $file_details;
            break;
          case "events.xml":
            $result->field_results_events = $file_details;
            break;
          case "clubs.xml":
            $result->field_results_clubs = $file_details;
            break;
          case "results.xml":
            $result->field_results = $file_details;
            break;
          default:
            //because the resuls_files field allows multiple files, this
            //field has to use a different method of assigning the file
            $result->results_files[LANGUAGE_NONE][] = (array)$file;
            break;
        }
       }
    }
    $d->close();

    node_save($result);
    //now move the files to the folder using the node ID as the subfolder
    $newdir = 'public://results/' . $result->nid;
    if(file_prepare_directory($newdir, FILE_CREATE_DIRECTORY)) {
      //move the files into this directory
      foreach($result_files as $file) {
        file_move($file, $newdir . '/' . $file->filename, FILE_EXISTS_REPLACE);
      }
    }
    else {
      drupal_set_message("could not create $newdir");
    }

```

At the end, all the nodes have been created, the files have been moved to the correct sub directory, but the node doesn't show any attached files. What am I missing?

# Answer
I think from what I understand; you are trying to add each file(s) to its node folder `public://results/[nid]/filename.ext`

As solution to your issue, first you need to save the node before you attach the file(s) to it. Then move/save file(s) to its desired location. Then attach the moved file(s) to the selected node again.

Change your code to look like the following:

```
$result = new stdClass;
$result->type = "results";
node_object_prepare($result);

//add values to text fields here

// save node
node_save($result);

//open the source directory

$d = dir($seasonDir);

while(false !== ($entry = $d->read())) {
  if($entry != "." && $entry != "..") {

    $dir = 'public://results/' . $result->nid;
    // create folder str
    if(file_prepare_directory($dir, FILE_CREATE_DIRECTORY)) {

      //set the file location
      $fileLocation = $seasonDir . "/" . $entry;

      //get the file contents
      $fileContents = file_get_contents($fileLocation);

      //save the file - added nid as sub folder
      $file = file_save_data($fileContents, $dir . '/' . $entry, FILE_EXISTS_RENAME);

      // important if you are importing none image files
      $file->display = 1;

      // you don't need to copy files to an array anymore

      // create entity object to store file(s) to the node

      $entity = new stdClass();
      $entity->nid = $result->nid;
      $entity->vid = $result->vid;
      $entity->type  = $result->type;

      //create an array to assign to the various file fields
      $file_details = array(LANGUAGE_NONE => array('0' => (array)$file));

      switch($entry) {
        case "results.inc.html":
          $entity->field_results_html = $file_details;
          break;
        case"clubs.inc.html":
          $entity->field_clubs_html = $file_details;
          break;
        case "events.inc.html":
          $entity->field_events_html = $file_details;
          break;
        case "index.xml":
          $entity->field_results_index = $file_details;
          break;
        case "events.xml":
          $entity->field_results_events = $file_details;
          break;
        case "clubs.xml":
          $entity->field_results_clubs = $file_details;
          break;
        case "results.xml":
          $entity->field_results = $file_details;
          break;
        default:
          //because the resuls_files field allows multiple files, this
          //field has to use a different method of assigning the file
          $entity->results_files[LANGUAGE_NONE][] = (array)$file;
          break;
      }

      // save entity
      field_attach_presave('node', $entity);
      field_attach_update('node', $entity);
    }
  }
}
$d->close();

```
> 2 votes

---
Tags: files
---


# Question
Title: Node form with fields loaded from another node or other entity
I am stuck on this problem, I was making a 'field' to be available on many content types, but this field has itself many fields, so i decided making an entity to have those fields seperate. I choose an entity because i don't these information to be accessible in the searchs etc, and I don't need revisions. Now on the node form submission i would like to have both the fields of the node and the fields of the entity showing up on the same form, as if this entity was a field. How can i do that ?

* If I use form\_alter: ok i understood how to add widgets to the form, but then that means i have to re-write all the validation code etc from all fields ? Is it possible to load fields so that they will keep all their properties? (validation, submission etc)
* Would it be possible to create a field module that would load other fields from a node/entity type on each hook ?
* Any other solution ?

Idealy i would to find or make an 'entity-reference' module that does that job! (load field from one in the other when creating, editing, loading a node) !!

any help welcom, thanks !

dylan

# Answer
Isn't module Inline Entity Form exactly what you are looking for? Here is a quote about it (from the module's project page):

> Provides a widget for inline management (creation, modification, removal) of referenced entities.
>
> The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form.
>
> Existing entities can also be referenced.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: Hide Group audience/content visibility in node
When displaying a node belonging to some OG, the group audience and the group content visibility is displayed at the end of the node just after the content of the node.

Is it possible to disable that ? I would avoid code editing if possible.

# Answer
In the OG content type, you will see a field for group audience. You can simply hide it in the Manage Field tab. Or, you could use CSS. In both cases, you are not hacking the core code.
> 3 votes

---
Tags: organic-groups
---


# Question
Title: Create a public profile page for specific roles only
Here is what I am trying to do.

I used profile2 to create an employee profile type that only users with the user role of employee could fill out.

What I want to do with views ( which I am not even sure if its possible) is have views create a profile page for each employee with a path of about-us/\[user:full-name\] (a field I created for the employee profile) and only create it for employee user.

Any help would be appreciated, thanks.

# Answer
> 0 votes
It seems that what you are looking for is to modify the URL structure. In my mind, View is for the layout. Since I assume you have a content type for Profile2 profiles, you can simply install PathAuto and configure it so your URLs have that structure.

# Answer
> 0 votes
You could easily do that with views too.. I think you will need to use argument handling in views. But only issue is the query argument should have more qualifying filter like drupal user id or employee id (if you are maintaining them).

This could go along with users full name field to make your url about-us/\[user:fullname\]/\[user:uniqueid\]

Let me know if you need more details.

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


# Question
Title: Send newsletter action - after saving simplenews node
I would like to do the same thing that described here: http://drupal.org/node/1427246

So, I use drupal 7, simplenews, schedule, and import modules.

I want to import my simplenews nodes, and they have scheduled date and time to publish...

But the problem for me is there is no way to set "send newsletter" status for the newsletter nodes automatically. I should click on each and every node to approve it to send.

On the link above there is a solution:

> "Create a rule that is triggered when a node is inserted (update makes no sense as you can't resend a newsletter, add a condition on the node content type and then execute the Send newsletter action."

My question: how can I activate the "Send newsletter action". It is not appear on the list of available actions.

# Answer
You need to enable the simplenews\_rules module which comes packaged with simplenews - this has the action for sending a newsletter defined:

```
'simplenews_rules_action_send' => array(
  'label' => t('Send newsletter'),
  'group' => t('Simplenews'),
  'parameter' => array(
    'node' => array(
      'type' => 'node',
      'label' => t('The newsletter node to be sent.'),
      'description' => t('The newsletter node that should be sent.'),
    )
  )
),

```
> 1 votes

---
Tags: emails
---


# Question
Title: Theming the field.tpl.php - accessing variables from a field collection
I've got a field template which is rendering a field collection field using the standard field.tpl.php file:

```
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?></div>
     <?php endforeach; ?>
  </div>

```

I want to output the a CSS class inside the div in the loop with some text which comes from a colour field inside the $item variable.

EG. I would like to access the variable such as: **render($item\['field\_colour'\]);** in the loop, but this obviously doesn't work.

What's the best practice for doing this?

# Answer
> 1 votes
In standard field.tpl files you can access your field collection items using this code:

```
foreach ($items as $k) {
  foreach ($k['entity']['field_collection_item'] as $id => $field_collection) {
    $field_collection_item = field_collection_item_load($id);
    $field_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);
    $field_colour = $field_wrapper->field_colour->value();
  }
}

```

I don't know if it is a best practice to do that, but this is my way.

---
Tags: entities, theming
---


title: change the page title of user page

text:
# Question
Title: change the page title of user page
the html title of the user pages are the user id and the website name. Is there a way to instead change the user id to the user name?

ie.

\[user id\] | website name \>\>\> \[user: name\] | website name

# Answer
> 2 votes
For a no-code solution try the page title module, which allows you to override page titles all over the site, with the use of tokens to improve flexibility.

---
Tags: users, 7
---


title: Add class to term-reference output

text:
# Question
Title: Add class to term-reference output
I'm trying to add a simple class to a link outputted via `print render($content['field_tags'])`. I'm using the Bootstrap theme. These are the approaches I've tried so far:

1. Hooking into template\_preprocess\_node - no luck here as the html isn't generated yet.
2. Hooking into template\_field - this contains exactly what I expect but the links being generated don't obey the classes set here.
3. Hacking node.tpl.php and manually outputting the terms - this sort of works but it's not the best solution.

This is the output as it is at the moment:

```
<a href="/tags/drupal" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">drupal</a>

```

I don't want to add any more modules as there has to be a code solution to this, I'm not sure what I'm missing here. How do I add a class to link outputted in field\_tags?

# Answer
One option would be to preprocess the field:

```
function MYTHEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_tags') {
    array_walk($vars['items'], function(&$el) { $el['#options']['attributes']['class'][] = 'some-class'; } );
  }
}

```
> 2 votes

---
Tags: taxonomy-terms, theming
---


title: Comment form above comments?

text:
# Question
Title: Comment form above comments?
Is there a simple way to move the comment form above the comments in Drupal 6?

# Answer
You can use the Comment form above comments module which adds option to place comment form above the comments thread.
> 2 votes

# Answer
This is a very simple thing to do in your theme so if you don't want to install another module just to do it you can override the comment-wrapper.tpl.php template file in your theme.

Just copy that file to your theme from the comment module (or if your theme is a sub-theme you there might be one in your base theme, in which case use that one - in this case the example coe below may not exactly match your base theme's code).

Then move this part:

```
<?php if ($content['comment_form']): ?>
  <h2 class="title comment-form"><?php print t('Add new comment'); ?></h2>
  <?php print render($content['comment_form']); ?>
<?php endif; ?>

```

So it is where you want it. In this case probably just above the line:

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

```

You can do this for a specific node type by renaming the file to comment-wrapper--node-NODETYPE.tpl.php, where NODETYPE is replaced with the machine name of your content type (with any underscores changed to dashes).
> 0 votes

# Answer
The simplest way I found was with CSS Note: I only want to do this with a specific Content type with the class ".node-chat-with-a-character" the height/padding of 200px was specific to my solution, and was a number I arrived at after removing a lot of extraneous things from the comment form.

```
/*put comment submit above comments*/

```

.node-chat-with-a-character #comments { position: relative; padding-top: 200px; }

.node-chat-with-a-character #comments .comment-form{ position: absolute; height: 200px; top: 0px; }
> -1 votes

# Answer
Put this in a block; it is the best and easiest method.

```
<script type="text/javascript">
  $(function(){
    $('.box').prependTo('#comments');
  });
</script>

```
> -1 votes

---
Tags: 6, forms, comments
---


# Question
Title: Are Wysiwyg and CKEditor modules incompatible now?
Apologies if this question has been raised elsewhere, but I couldn't find anything directly related to it.

I'm in the process of setting up my first Drupal site. I want to be able to include images in the body of posts but without turning on "full HTML". Chapter 4 of *Using Drupal* (2nd Edition) describes a way of doing that involves using both the Wysiwyg and CKEditor modules.

However, when I install the latest versions of both modules (Wysiwyg: 7.x-2.2; CKEditor: 7.x-1.13), I get the following message on the CKEditor configuration page:

> "The WYSIWYG module was detected. Using both modules at the same time may cause problems. It is recommended to turn the WYSIWYG module off (click here to disable)."

If I ignore the message and try to configure Wysiwyg I get the following message:

> "The version of CKEditor could not be detected. Extract the archive and copy its contents into a new folder in the following location: sites/all/libraries/ckeditor
>
> So the actual library can be found at: sites/all/libraries/ckeditor/ckeditor.js"

But ckeditor.js is saved in the above directory.

I've tried installing other editors besides CKEditor (e.g., TinyMCE), but I get a similar result.

I've got CKEditor installed and working fine, but it only generates HTML code, not tags that the Media module can process. Consequently, images only appear in "Full HTML" mode, not in "filtered HTML" mode.

I'm really interested in finding out how can I include images in posts using filtered HTML mode (either by using CKEditor/Wysiwyg or by some other method). Very grateful for any suggestions.

# Answer
Yes you use one or the other of the CKEditor & WYSIWYG modules.

They both provide the same sort of functionality.

As to which is better is up to your preference. You can try them both and see which one you prefer.
> 3 votes

---
Tags: wysiwyg
---


# Question
Title: Why is my form validation only working for some fields with ajax submit?
I have a custom form that uses ajax submit successfully. However, form validation is not working as expected. Fields marked as required are being highlighted in red, but other fields that do not pass validation are not being marked.

```
function my_custom_form($form, &$form_state, $nid=NULL) {
  global $user;
  $form['nid'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
  );
  $form['#attributes'] = array('enctype' => "multipart/form-data");
  $form['video_fid'] = array(
    '#title' => t('Video'),
    '#type' => 'managed_file',
    '#description' => t('Upload your video.'),
    '#default_value' => variable_get('video_fid', ''),
    '#upload_location' => 'public://video/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('mp4'),
      // Pass the maximum file size in bytes
      'file_validate_size' => array(MAX_CUSTOM_UPLOAD_FILE_SIZE),
    ),
    '#progress indicator' => 'bar',
    '#required' => true,
  );
  $form['title'] = array(
    '#title' => t('Title'),
    '#type' => 'textfield',
    '#description' => t('Video title, ex. "First Attempt" etc.'),
    '#default_value' => '',
    '#size' => 60,
    '#maxlength' => 64,
    '#required' => true,
  );
  $form['notes'] = array(
    '#title' => t('Notes'),
    '#type' => 'textarea',
    '#description' => t('notes about this video'),
  );
  $form['team_message'] = array(
    '#markup' => 'Your team: <strong>'.$user->name.'</strong> (you)<br/>',
  );
  $form['teammates'] = array (
    '#type' => 'textfield',
    '#autocomplete_path' => 'my_custom/teammate/autocomplete',
    '#description' => t('Type each teammate\'s username, separated by commas'),
    '#element_validate' => array('_my_custom_form_team_validate'),
    '#ajax' => array(
      'callback' => 'my_custom_form_validate_teammates',
      'wrapper' => 'teammates-error',
      'method' => 'html',
      'effect' => 'none',
      'progress' => array (
    'message' => NULL,
      ),
    ),
  );
  $form['teammates_verify'] = array (
    '#type' => 'markup',
    '#prefix' => '<div id="teammates-error">',
    '#suffix' => '</div>'
  );
  if ('' != _are_teammates_valid($form_state['values']['teammates'])) {
    $form['teammates']['#error'] = true;
    $form['teammates_verify']['#markup'] = '<span class="error">'.t('The following are not valid users: ')._are_teammates_valid($form_state['values']['teammates']).'<pre>'.print_r($form_state,1).'</pre></span>';
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#ajax' => array(
      'callback' => 'my_custom_form_callback',
      'wrapper' => 'level-form',
      'method' => 'replace',
      'effect' => 'fade',
      'name' => 'submit',
    ),
    '#value' => t('Submit'),
  );
  return $form;
}
function _my_custom_form_team_validate($element, &$form_state) {
  if (!empty($element['#value']) && '' != _are_teammates_valid($element['#value'])) {
    form_error($element, t('!teammates are not valid user. Please check spelling.', array('!teammates' => _are_teammates_valid($element['#value']))));
  }
}
function my_custom_form_validate($form,&$form_state) {
  // validate file upload
  // validate teammate list
  if (''!=_are_teammates_valid($form_state['values']['teammates'])){
    form_set_error('teammates');
  }
}
function my_custom_form_validate_teammates($form, &$form_state) {
  if ('' != _are_teammates_valid($form_state['values']['teammates'])) {
    form_set_error('teammates');
  }
  return $form['teammates_verify'];
}
function _are_teammates_valid($teammates) {
  if ('' != $teammates) {
    $team = drupal_explode_tags($teammates);
    $bad_usernames = ',';
    foreach($team as $possible_teammate) {
      $teammate = user_load_by_name($possible_teammate);
      if (!$teammate) {
        $bad_usernames += $possible_teammate;
      }
    }
    if (2 < strlen($bad_usernames)) {
      form_set_error('teammates',t('The following are not valid users: ').substr(2,$bad_usernames).t('. Please recheck spelling.'));
    }
  }
}
function my_custom_form_callback($form, $form_state) {
  my_custom_form_validate($form,$form_state);
  if (form_get_errors()) {
    return $form;
  }

  global $user;
  $nid = $form_state['values']['nid'];
  // $account = user_load($user->uid);
  $file = file_load($form_state['values']['video_fid']);
  if (!$file) {
    $pre['message'] = array(
      '#markup' => '<p class="error">'.t('Please upload file first').'</p>',
    );
    return $pre+$form;
  }
  $file->status = FILE_STATUS_PERMANENT;
  file_save($file);
  // TODO change this file_usage_add() call to reflect current module ownership - see http://api.drupal.org/api/drupal/includes!file.inc/function/file_usage_add/7
  file_usage_add($file, 'user', 'user', $user->uid);

  if (!file_save($file)) {
    return t('There was an error uploading the file');
  }

  $team = array_map('user_load_by_name',drupal_explode_tags($form_state['values']['teammates']));
  array_unshift($team, $user);
  foreach ($team as $teammate) {
    $vnid = _make_video_node($teammate->uid,$form_state['values']['title'],$form_state['values']['notes'],$form_state['values']['nid'],$file);
    _make_completion_node($teammate->uid, $form_state['values']['title'],$form_state['values']['notes'],$vnid,$form_state['values']['nid']);
  }

  if (_my_custom_form_completes($nid, $team)) {
    drupal_set_message('Level Completed');
    return '<h2>'.t('Level completed!').'</h2>';
  }
  drupal_set_message('Error Completing Level');
  return '<h2>'.t('Error Completing Level').'</h2>';
}

```

# Answer
It would be helpful if you could write which fields actually get validated. But from the code I guess the only validation working is

```
function my_custom_form_validate($form,&$form_state) {
  // validate file upload
  // validate teammate list
  if (''!=_are_teammates_valid($form_state['values']['teammates'])){
    form_set_error('teammates');
  }
}

```

It looks like you have created many different validation functions. But the hook validate is per form and not per field. So if was to wrote a validation function for your form I would try this:

```
function my_custom_form_validate($form,&$form_state)
{
   if (_are_teammates_valid($form_state['values']['your form field'])!='')
   {
     form_set_error('teammates');t('Your error message.'));
   }
   if ($form_state['values']['your form field']!='What it should be')
   {
     form_set_error('your form field');t('Your error message.'));
   }

   // ... and so on...
 }

```

You basically create one validate function and check each field in "$form\_state\['values'\]" and set the correct error message.
> 3 votes

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


# Question
Title: Displaying parts of main menu in separate blocks
I need to display my main menu in separate blocks: the first sub-menu in one block, and the following two sub-menus in another block. I'm using Drupal's native menu module and also the nice menus module.

How can I do that?

# Answer
> 0 votes
Consider using menu\_block and defining 2 blocks with the depths you desire within the main-menu for each block; and then place them in the drupal Regions you want. The menu\_blocks I believe will play nicely with Nice Menus if you have "expand all child elements" of this menu option checked.

---
Tags: 7, routes, navigation
---


title: Captcha does not save form_id

text:
# Question
Title: Captcha does not save form_id
I added the CAPTCHA module to my drupal 6 website using this procedure and I'm trying to add the captcha to my user registration page.

However when I go to /admin/user/captcha the list with the default forms is empty. I expected the default list.

I entered user\_register as the form\_id, selected the standard captcha from the dropdown and pressed save. However it does not add the new form to the list. It's still empty. I also tried to save other values without success.

UPDATE: I also tried reinstalling the captcha module and flushing cache without success. It's weird because I never had this problem on an other site with the same module/version

Installed version of the module: 6.x-2.4

UPDATE 2: I enabled both the Captcha module and the Captcha compatibility module in the modules list.

# Answer
> 0 votes
The problem was the site didn't have writing permissions to the database. This meant that on installation of the module the necessary tables where not created and thus the above problem occurred.

---
Tags: 6, captcha
---


# Question
Title: how to add newsletter subscription during registration?
Here what I want to do. I loaded a checkbox list of taxonomy term on the registration form. Also I have a check box for "subscribe newsletter". so the user can check the his favourit taxonomy and "subscribe newsletter". I want to know how can I alter the submission of register form to gather this data?

# Answer
> 2 votes
you can achieve this either by using Mailchimp Module

```
                          OR(by custom coding)

```

You can alter your registration form using hook\_form\_alter. Now in your form you can add add two new elements that is :-

1. A checkbox saying- Signup to receive alerts.
2. A text field to capture email address.

Now you can override your form on submission and pass the email captured above to mailchimp function that adds users to email lists via ajax call.

Hope this helps!!!

---
Tags: 7, forms
---


# Question
Title: Inserting a dotted line between articles
Can anyone help on how I can insert a dotted line between articles? Currently I created it in view Global Custom text field using horizontal rule `<hr>` which gives a solid line, but I need dotted lines instead. Any idea?

# Answer
> 2 votes
Use **CSS** instead, adding a bottom border to the articles:

```
article { border-bottom: 1px dotted black; }

```

If you also want to hide the bottom border of the last element, just add:

```
article:last-of-type { border-bottom: none; }

```

It is possible depending on the theme you are using that the article contains `first` or `last` inside class tag.

---
Tags: views
---


title: Drupal 6 import/export book

text:
# Question
Title: Drupal 6 import/export book
I'm looking for a module to export/migrate a books (with all child pages) from a Drupal ( 6.x) Installation to another.

Thank you in advance for your kind replies

# Answer
The module Migrate is the most versatile Drupal tool for database migration.

However, book module migration is still not trivial. Books are nodes, so they can inherit most of their migration from a common class. But to preserve book node hierarchy that is stored within menu links, you need to use special code to migrate the hierarchy. Here is a sketch of the required workflow:

* Migrate nodes as normal.
* Get hierarchy from the source database `book` table, and weights from the `menu_links` table.
* Place a `public function complete()` in your `Migration` class to call `_book_update_outline()` to migrate the hierarchy.

A more detailed receipe, with a special code example, is at Drupal.org: Book node migration.
> 1 votes

---
Tags: nodes
---


# Question
Title: Conflict between with a function in two different modules
I have the same function in two different modules to change the page: **node/add**.

I need the second one(see below) to override the first one. I implemented hook\_install to change their weight but is not working. My guess is that the hook\_install function is executed after those modules.

How can get this done?

Codes below:

My hook\_install function

```
/**
* Implements hook_install().
*/
function utilities_install(){

db_update('system')
    ->fields(array('weight' => 10000))
    ->condition('name', '[content_type_thumbnail]', '=')
    ->execute();

}

```

Function in **commerce\_backoffice\_product** module:

```
 /**
 * Implements hook_theme_registry_alter().
 */
function commerce_backoffice_product_theme_registry_alter(&$theme_registry) {
  $theme_registry['node_add_list']['function'] = 'theme_commerce_backoffice_product_node_add_list';
}

/**
 * Override node_add_list theme.
 */
function theme_commerce_backoffice_product_node_add_list($variables) {
  $item = menu_get_item();

   .... code ....

  return theme_node_add_list($variables);
}

```

Function in **content\_type\_thumbnail** module

```
/**
 * Implements hook_theme_registry_alter().
 */
function content_type_thumbnail_theme_registry_alter(&$theme_registry) {
  $theme_registry['node_add_list']['function'] = 'content_type_thumbnail_node_add_list';
}

/**
 * Override of theme_node_add_list().
 */
function content_type_thumbnail_node_add_list($variables) {

  .... code ....

  return $output;
}

```

# Answer
Rather than module weighting, I would suggest using hook\_module\_implements\_alter to ensure your hook gets run last. So, something like this:

```
function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'theme_registry_alter') {
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

```
> 1 votes

---
Tags: 7, theming
---


# Question
Title: "This is a debugging block" on Permissions page
On my dev site, everything is working fine EXCEPT the permissions pages. This includes `/admin/people/permissions` and the permissions pages for individual modules (example: `/admin/people/permissions#module-advanced_forum`).

I have the Faster Permissions module installed, and this module gives a list of all the modules installed with links directly to their individual permissions. This page is working fine.

All of these pages are working fine in my production site, so there is something about my dev site that is causing this error. Has this happened to anyone before? What could be the problem?

FYI, debugging blocks have been turned off in settings.

# Answer
If you are using the Omega theme debugging blocks are always visible to uid=1. Check out this issue.
> 0 votes

# Answer
I believe I have figured it out. My site seems to have a lot more permissions set than other Drupal sites. I just doubled the PHP memory limit to 1 GB and the page loaded ALMOST normally. I got an unresponsive script warning. I then looked at the error log for the site and saw that the PHP was timing out, so I doubled the timeout. Now the permissions page loads as it should.
> 0 votes

---
Tags: debugging, users
---


title: How do I release a Drupal Distribution

text:
# Question
Title: How do I release a Drupal Distribution
I have been developing a site and I feel that it would work really well as a Drupal distribution. I have no idea about how to create one, but I am familiar with drush make, install profiles etc. What is a Drupal distribution and how do I release one? What are the main benefits?

# Answer
Take a look at Packaging a distribution on Drupal.org

**Here are the steps:**

1. Assemble the pre-requisites
2. Create a Drush Make file
3. Convert to a Drupal.org-specific Drush Make file
4. Build and verify it works
5. Commit your code to Git
6. Release your code on Drupal.org
7. Maintain your distribution

Another great tutorial How to Write a Drupal 7 Installation Profile

Also there is Profiler Builder module.

> Profiler Builder is a module for automating the creation of installation profiles and distributions. It has support for the Profiler installation profile simplifier library but is able to run independent of it (1.0-RC4+). This module creates a downloadable tar package that gives you a well made installation profile and associated drush make file based on the site its installed on.
> 4 votes

---
Tags: distributions
---


title: Persistent Audio Player

text:
# Question
Title: Persistent Audio Player
Is there a way to have a persistent audio player between page navigations? HOw do you prevent the player from restarting on a page refresh.

# Answer
> 1 votes
There are a lot of challenges to overcome but it's doable. My sandbox project makes a persistent player possible in Drupal 7. Check it out: Ajax pages.

# Answer
> 2 votes
The only way to do that is to actually NOT refresh the page each time but rather use ajax or something similar to refresh only certain areas of the page while leaving the player area intact.

An example of this is pitchfork.com. It has a player in the upper right gutter. When you click on a link, what happens is the main content area of the page is reloaded but the page stays the same, so the player keeps on playing.

But, if you hit the reload button on your browser, it stops and starts all over again because the page itself was reloaded.

Of course, you could always put the player in a pop-up/under window and then you wouldn't have to worry about it as much.

# Answer
> 0 votes
The post about Render only the contents of page.tpl programatically? gave some insight on how to do it, using the Ajax Regions module. Here is an excerpt from the module's project page:

> ... allows to configure flexibly the internal links of your site, which will update the appointed regions using Ajax, instead of full page refresh.

---
Tags: 7
---


# Question
Title: Make drupal cck field behave as "an add more button"?
Is it a way to make a Drupal 7 entity field behave as 'an add more button', but with finite number of values?

For example, initially there is only one form field for inputting the value showing, then I can keep adding up to 4 more form fields. I can set it to maximum 5 fields, but it will show 5 fields all at once. The client only wants to show 1 field initially.

# Answer
This functionality is not available out of the box. But it's something people have been asking for (repeatedly) since at least D6 CCK 2:

User goron has developed a contrib module for Drupal 7 called Multivalue Settings.

But be aware - from the module description page:

> Warning: this module is still very buggy. Actually, it only works in very few use cases. I suggest to only attempt using it with core fields (not fields from contrib modules). Even this may not work.

And it hasn't been updated in over a year.

**Screenshot of Multivalue Settings functionality:**
> 1 votes

# Answer
go to admin/structure/types/manage/**\[content type\]**/display/teaser select the fields you want to display and hide. Teaser will give you readmore by default.

or if this is not you are looking for you have to theme using jquery to hide and show the content
> 0 votes

---
Tags: 7, entities
---


# Question
Title: Load Pages Using AJAX to Allow for a Continuous Music Player
I'm looking to create a music player that will play continuously between page loads. After some research, I've decided AJAX is the best way to do this.

I'm looking to load all the site content using AJAX (minus the music player) in one container and place the music player in a separate container div at the bottom of the page.

How would this be done? Thanks is in advanced!

# Answer
> 1 votes
To quote my answer to the same question at StackOverflow:

> Ajax pages makes it possible to load every page via Ajax with minimum effort. A player can be put in a region outside of the Ajax-loaded area, making for continuous playback. There are demo links on the project page, check them out.

---
Tags: ajax
---


# Question
Title: Drupal 7 sites hogging my shared hosting account
Two months back I launced 3 new Drupal-7 based sites on my shared hosting account but soon I found that my account was touching maximum process limit of 25 in my account and that my D7 sites were having only 400 or so page views daily. To compare it with D6 site, it could handle 4000 pages views without any problem.

Hostgator support confirmed too many processes of D7 sites. I've also checked it and I find that D7 index.php is running for much more time than D6 counterpart. So instead of it exiting in .5 second, I guess it's taking 3 seconds( rough estimate). I don't think those are eating too much of CPU in that case my sites would have been suspended.

To resolve it I'm moving my D7 sites to VPS so that process limit is increased.

I'm using all Drupal default install settings. No booster etc modules.

Any suggestions?

# Answer
> 2 votes
Shared hosting is the bane of the internet -- I recommend not using shared hosting if at all possible stick with the VPS. Did you turn on Aggregation, and caching in your drupal install? Did you install APC and configure drupal to use it. If you use APC and are a read-heavy anonymous traffic site, then APC can be configured to store all your pages in an in-memory cache and you never even hit the DB.

Tweaking a website to maximize server usage is really *really* website specific. The low hanging fruit is stuff like Performance settings in Drupal, APC, maybe Nginx for a webserver, etc. Beyond that profile your site.

Alternatively as you mentioned you could cache to disk by using like Boost.

---
Tags: 7, performance
---


# Question
Title: How to put two form elements in a row using Drupal Form API?
I am creating a form in Drupal 6 using form API.

I need to put a textfield and a select next to each other. they are for entering something like 'www.domainname.com' . www. is fixed. domainname section is given from user in a textfield and .com section is chosen from select element by user.

So they should be in a line. but as I see I can put these two form elements in a line, they are in their div container.

Would you help me? Thank you.

# Answer
> 5 votes
This is a CSS issue. All you need to do is limiting the width of both elements and then float them to the left; this will make them inline. Be sure to wrap them both in a div with the "clearfix" class to clear the float.

---
Tags: forms
---


# Question
Title: CAPTCHA default for Blog post forms does not work in Drupal 7
I'm trying to get CAPTCHA to be automatically added to my blog post forms so that I don't have to enable it individually on each blog post. I've followed the suggestion on this post, but unfortunately, this doesn't work for me. I've enabled everything that I should, but the CAPTCHA doesn't work for blog posts unless I manually enable them per post. This is not practical. I've used the CAPTCHA module fairly extensively before, so I understand how it works, but it's just not doing what I've told it to do.

Does anyone know what may be keeping my site from enabling CAPTCHA as the default for blog posts?

# Answer
> 2 votes
Following the same post you saw, this time use "**comment\_node\_blog\_form**" as your form id, or "comment\_node\_CONTENT\_TYPE\_form" if your content type is not called blog

---
Tags: 7, captcha
---


# Question
Title: How to link different contents together and display the linked content on the same page?
I am fairly new to Drupal and would need some help.

on my site I have to show a few images (A - B - C - D ) created by a content type X.

Each of these images will link to a different content Type Y ( 1 - 2 - 3 - 4 ).

So when I click on A , the content 1 should show below it. Same for content B -2 , C -3, D-4.

I am not sure how to achieve such a result and what are the tools to use.

Thank you for your help.

# Answer
> 0 votes
Images are just media assets on a site. By which I mean you're relating something specific in X to another thing in Y -- you could just as easily relate content titles.

You likely want to either relate things together using `Tagging` via Taxonomies. Taxonomies can also have associated images for example. Or, you want to relate content around with relationships:

Without a concrete mocked-up example with wireframes and in-depth explaination of requirements .... good luck.

# Answer
> 0 votes
I would probably use taxonomy, relation and the views module to accomplish this. Once you associate your associate your image content \[A-B-C-D\] with your content Type Y \[1-2-3-4\] then you can easily display this in a View (probably a grid style, but whatever works best for your needs). Views allows you to use a relationship between the two content types and rewrite what the \[image\] field links to.

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


# Question
Title: Context reaction : Exclude specific block?
I've got a website with 3 large contexts : \- internet \- intranet \- shop

These 3 contexts are "tight" (sorry about my english, I think this is the word).

My Block UI (admin/build/block) provides to every pages 2 blocks in my website first sidebar.

In my Shop context, I've got a specific header, footer, and about 6 blocks in the first sidebar. The conditions are quite simples : Paths only. \- shop/\* \- cart/\* and some others.

My node-product pages are in my Shop context conditions, and that's fine. (I don't want my users to lose the shop header, shop menu, shop footer and so on...) when they are on a product page.

**Now, what I would like to do is to exclude 3 of my 6 side blocks on my node-product pages.**

So I was thinking... What if we had an "Exclude Blocks" Reaction in context ? That is exactly what I need to do what I'm expecting.

I tried to adjust visibility settings in block UI, but it seems that context UI overrides it...

Shall I duplicate my Shop context to have a Shop-product one ? Is that clean ? I mean... All this context definition is correct, and I only want to exclude 3 blocks... Isn't that overkill to duplicate all my settings ?

Any Ideas ? Thanks guys.

# Answer
> 0 votes
It might not be overkill to duplicate the context if it works ;)

Context is often used with Delta to provide layout and theme adjustments for internal pages. After setting up a few Delta layouts you will be able to specify a Context/Delta reaction and switch the applied Delta template for your Shop-product page.

Take a look at this decent Delta+Context tutorial. Good luck!

EDIT: If you're not already committed to a theme, the Omega theme has some incredible integration with Context/Delta - intro tutorial here.

---
Tags: 6, blocks
---


title: Filtering a date field in views

text:
# Question
Title: Filtering a date field in views
I have set up a view that shows users a set of nodes for an athletic season that runs September through August. Each node has a field called Start Date. I would like to filter this start date using the year of the season, i.e. 2012 for the 2012-2013 season. I've looked into contextual filters but I don't think this is going to work for me, as I don't see a way to provide a range (say 2012-09-01 through 2013-08-31). Will this require a custom module and if so, where can I get some concise instructions on hooking that custom module in with the specific view. Most of the documentation I read gives a quick code snippet with no specifics on where that snippet is supposed to go.

# Answer
> 2 votes
You can try setting a flag before node save.Set the flag if start date is Aug and End date is Sep.this flag field will be hidden field and you can pro-grammatically check the start date and end date before node save in hook\_node\_presave and in the same hook if you find condition to be true set the flag but remember to compare the date considering the same year option.Now On the views first filter the results on the basis of hidden flag field(as 1 or whatever you set) then add a start date expose filter with granularity as year only and make it expose to users.

Only reason I prefer to filter the results while creating the nodes was to simplify the filters in views, as it may be tough to filter out results in views untill you figure out how you can set interval as single and same year.

# Answer
> 3 votes
Is the "Start Date" field a date field? Or is it a text (or some other type of field)?

If it's an actual date field, you can configure this behavior through the UI.

Add the field as a filter in the Filters section. Then you should see an `Is between` operator radio button. Select that and enter your range in the Value section. Screenshot:

You need to activate the date\_views module to see the filters appearing in the Views module interface.

---
Tags: views
---


# Question
Title: Implementing redirection on node viewing without affecting solr search indexing
My logic demands that for a specific content type provided a node (Ex) node/123 has one if its CCK field named web link with a URL value like http://someothersite.com in it, viewing the given node mysite/node/123 should redirect to the respective URL http://someothersite.com given in that field.

I've implemented this with a custom module's `hook_nodeapi` `view` case to check the value of the field and perform the redirect. However doing so has inadvertently affected my apachesolr search indexing which invokes the hook on view condition (through `node_build_content`) to generate the node for being indexed.

This has forced me to currently skip such specific nodes from not being indexed, however I wish to know if there's a better way of programatically implementing the aforementioned redirect without hook\_nodeapi to keep the sanity of search indexing intact.

# Answer
> 1 votes
How about doing this in `hook_init()` instead, eg, something along the lines of...

```
function YOURMODULE_hook_init() {

   $mgo=menu_get_object();

   if (!empty($mgo->type) && $mgo->type=='THE_TYPE_YOU_ARE_LOOKING_FOR') {

      if (!arg(2)) { // eg so we ignore node/###/edit etc
        if (!empty($mgo->field_THE_FIELD_YOU_ARE_REDIRECTING_TO[0]['value'])) {
          drupal_goto($mgo->field_THE_FIELD_YOU_ARE_REDIRECTING_TO[0]['value']);
        }
      }
   }

}

```

Caveat: I've never used apachesolr, so you may need to wrap this with further logic to make sure you are running when a user actually goes to the page, eg, arg(0)=='node' and is\_numeric(arg(1)) kinda stuff.

ADDITION:

You might be able to just check args inside nodeapi() as well, eg:

```
if (arg(0)=='node' && is_numeric(arg(1)) && !arg(2)) {
  // do your magic
}

```

---
Tags: redirection, search
---


# Question
Title: Are old nodes automatically archived over time?
I just went to a site that I haven't touch in a while and I see this on the homepage: The requested page "/" could not be found.

I went into Administration » Configuration » System and saw that the Default front page was set as: /node/1 When I tried to pull up that node, I got a page not found error: The requested page "/node/1" could not be found

I suppose it's possible that someone else who has access to the site deleted this node accidentally, but I'm just wondering if it may have been auto-archived or something instead.

Are there hackers that gain access to sites and then just delete their front page? Or should I be pointing the finger at the other people who have access to the site?

# Answer
Drupal does not archive or otherwise delete or modify content automatically over time. There are a few possibilities as to what happened to node1 including:

* An administrator or someone with permission to delete nodes of that content type deleted it
* there is a rule or other module configuration that deletes nodes after a certain amount of time
* Node 1 was deleted a long time ago and someone changed the front page after the fact (not likely as I think drupal verifies the path when you save that setting)

Drupal does keep a record of when nodes are deleted in the watchdog table. The watchdog table has a UI which can be found at /admin/reports/dblog. You can filter this list by type, but note that Drupal only stores a finite number of rows in this table with First In First Out as a rule. So it's possible that the record of node 1 being deleted has also been deleted.
> 6 votes

---
Tags: nodes
---


# Question
Title: sharing authentication within two drupal distributions
I am looking for a module or a way where two different drupal distributions can share the same authentication or user database ? Is there a module that can help with that ?

possibilities-

if user A logged into site-1, the user should be logged in automatically to site-2.

if thats not possible, if user 1 creates a login on site-1, he should also be able to use the same login credentials on site-2 or vice versa.

# Answer
> 1 votes
This method comes with a list of caveats, but it's possible to simply share the users table across multiple installations via a table prefix array in settings.php.

> **Example: Sharing Users**
> This example shows how to share users. The users from a master site prefixed with 'master\_' are shared to a slave site prefixed with 'slave1\_'.

```
$db_prefix = array(
    "default" => "slave1_", // the prefix for tables that are not shared.
    "users" => "master_",
    "sessions" => "master_",
    "authmap" => "master_",
    "sequences" => "master_",
    "profile_fields" => "master_",
    "profile_values" => "master_",
);

```

# Answer
> 1 votes
Possibility 1: Try OAuth module

> OAuth is an open protocol to allow secure API authentication in a simple and standard method from desktop and web applications.

Possibility 2: Try Bakery module

> Bakery provides a "single sign on" feature for Drupal based sites that are on the same second-level domain (i.e. example.com, subsite.example.com, subsite2.example.com). It could also provide support for any other website that implements the same web cookie, xmlrpc, and POST methods.

Also, check other options

Comparison of Single Sign On (SSO) Modules

# Answer
> 0 votes
I guess drupal gardens do the same you are asking for. Basically one of your drupal installation act as drupal open id as server and other as client,kinda login with facebook. So user first registers to drupal open id server and gets an open id and now user logs in other drupal installation with same id and this drupal server interacts internally to other drupal server for authentication so if you are logged in drupal open id server installation you can direclty logged in to drupal open id client installation, drupal gardens passes your open id as url.

this approach may require time and research.

---
Tags: 7, users
---


# Question
Title: Updating a module via backend or manually didn't work. No drush available. What else can I try?
I have to administrate a site I didn't build. An older version (7.x-3.0-beta4) of http://drupal.org/project/context (7.x-3.0-beta6) gives me security alerts and suggests to update immeditaley(!).

The automated update process works fine until it comes to the point where the database should is updated. I just says: No pending updates. Back in the modules overview it still is the old version (7.x-3.0-beta4) and message prompts again: update immediately.

So I tried updating manually. Deleted the context module folder in sites/all/module. And uploaded the freshly unpacked new version (7.x-3.0-beta6). Then I ran updated.php and: same again. Drupal still says old version and tells me to update immediately.

Then I tried to uninstall the complete module through the 'uninstall module' dialogue, though I don't know if uninstalling it completely is a good idea (Is it? Or will data get lost?). But even that didn't work. I deactivated all the three parts of that module (context, context ui, context layouts), then went to the uninstall site but there I wasn't given the chance to check the main part (context).

Even when deleting the whole module folder, the module still appears in every list and the alert message still prompts me to update.

So, what can I do to force the database to update and finally recognize the new files? Or what else would be a point I maybe missed to try?

# Answer
> 1 votes
If you aren't able to update a certain module, look out for a second maybe renamed folder containing that module. It may then be better to keep the second (renamed) folder and update that one manually, cause that one already is associated to the database.

# Answer
> 1 votes
Have you flushed your caches? Sometimes you will see old data, even in regard to modules because of cache issues.

---
Tags: updating, 7
---


# Question
Title: How can I use tokens for Addressfield values without using Addressfield_tokens?
I would like to use the Town/ City field as a token for Pathauto. I thought the Addressfield\_tokens module was perfect for this, but Entity Tokens breaks Pathauto's patterns control panel; the issue seems to be common and unresolved.

I'm wondering what other options I might have for extracting the Town/ City value from Addressfield and using it as a token in a Pathauto pattern?

# Answer
If Pathauto uses the core Token system, then you can follow along in this issue where we'll be adding token support directly to Address Field asap.
> 0 votes

---
Tags: 7, tokens, path-aliases, entities
---


# Question
Title: Webform Conditional is not firing when using a hidden field
I am trying to hide/show a field from the user based on a hidden field, whos value is set from the server. I have set up a conditional so that if the hidden field 'X' value is 'a', then field 'Y' will be shown.

However, field 'Y' is being shown no matter what. I have tried reversing the logic (if hidden field 'X' value is not 'a', then hide 'Y'), but that did not change anything.

After much testing, it seems as though the conditionals of Webform will not actually do anything based on the value of a type 'Hidden' field. If I create the same logic with a 'Textfield' instead, the conditional fires as expected.

Is this a bug? Am I doing something wrong? The end result I am trying to accomplish is to hide or show a field based on an input that the user cannot change themselves.

# Answer
Following up on my response above, things like FAPI `autocomplete_path` and as your seeing webform conditional (i think) use the States API. Which is a limited version of scriptable javascript API from within Drupal7.

Drupal does ship with jQuery UI built in. And you can make direct usage of jQuery to alter/modify forms directly using drupal core components -- such as the bundle standard jquery packages that come with Drupal 7. Want a working jqueryui autocomplete example as an example -- here's 1 in Russian (Google translate works well here):

http://serho.ru/notes/raznoe/jquery-ui-autocomplete-widget-v-forme-drupal-7

I realize your request may be a non-coding module only solution; but such modules and APIs basically have limits as you've seen. There are pieces of drupal core that exist to let you homegrow your own solution.
> 0 votes

---
Tags: webforms
---


# Question
Title: Approach for building local/city versions of a national website?
I'm looking for ideas and advices on how to adapt a national website to cities depending on whether the user is logged in or not.

As for a news website, the front page for anon users would be a mashup of nodes from all the regions. But registered users will set their city during the registration process or later by editing their profile and will then have a local adapted version of the website.

Any ideas on how to achieve this are welcome

# Answer
> 1 votes
I'd recommend the Domain Access module(s) as the easiest way to set this up with multiple sub-sites (even with sub-domains) but still having a central site to control content and access:

> The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database. The module allows you to share users, content, and configurations across a group of sites

It comes with a dozen or so helper modules and a few stand-alone projects that make it easy to create and manage sophisticated site networks.

---
Tags: 7
---


# Question
Title: Make a from element visible when a radio button is clicked
I have a problem to make a date and a list element in a form in HTML invisible if the user selects one way, and visible if the user selects two. How can I write the JavaScript code for that?

# Answer
> 2 votes
No need to write JavaScript for that; if you are working in PHP, you can use #states on the form element.

Example: form\_example\_states\_form.

```
  $form['high_school'] = array(
    '#type' => 'fieldset',
    '#title' => t('High School Information'),

    // This #states rule says that the "high school" fieldset should only
    // be shown if the "student_type" form element is set to "High School".
    '#states' => array(
      'visible' => array(
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );

```

---
Tags: forms, javascript
---


# Question
Title: Drupal 7 When a new user registers, where is the confirmation e-mail sent?
Im using Drupal 7, when a new user registers an account I want to be able to approve/deny their membership and then allow them on the website as a registered user. When a new user registers, where is that registration e-mail sent to? And can I change where that e-mail goes?

# Answer
> 4 votes
Set the new user account setting to "administrator approval is required" here:

Admin \> Configuration \> People \> Account Settings

---
Tags: emails, users
---


# Question
Title: Redirect the users to the page they were watching before logging in or registering an account
I have a custom login, sign-in and sign-up page in two tabs; I want logged-in users to be redirected to the same page they were watching before logging in or creating an account.

How can I achieve this?

# Answer
I hope you want to keep users on the currently visited page after logging in or out. If it is so, then download and install the Login Destination module. It is also possible to keep users on the currently visited page after logging in or out.
> 1 votes

---
Tags: 7, users
---


# Question
Title: Access denied to file in sites/all/default/files
I am getting:

```
access denied   04/30/2013 - 16:56  sites/default/files/styles/thumbnail/public/KRIS... admin

```

in my error message log when trying to do some file updating. I am guessing this is a permissions problem, but i am running on a local server. How do I change permissions in drupal for access to read/write to the files folder on a mac in terminal?

# Answer
> 1 votes
Problem was `$conf['image_allow_insecure_derivatives'] = TRUE;` in the settings.php file. An update from drupal 7.20.

# Answer
> 2 votes
Drupal.org has a great guide on permissions.

**The TLDR; version.**

You can change permissions by opening up your terminal and perform the following commmand:

`(sudo) chmod <mode> <path>`.

For more information about `chmod`, check the manpage. Or just perform:

`chmod --help`

# Answer
> 0 votes
you should give permissions to it using

sudo chmod 777 sites/all/default/files

This would remove the problem of permissions and would give rights for read, write and execute permission to the files folder.

---
Tags: files
---