# Question
Title: How to set multiple domains for one language
I have a **multilingual** site with Drupal 7 using subdomains like en.example.com to detect the language. Everything works like expected, but I have a mobile version of the website witch I want to be accessible by domains like en.m.example.com etc. How do I do this? I can set in `admin/config/regional/language` only one domain per language, but would have to set two in order to get that working, like:

```
for English:
en.example.com & en.m.example.com

for German:
de.example.com & de.m.example.com
etc.

```

(I would like to have the same structure as Wikipedia has.) The problem is, that using subdomains for language selection, Drupal creates all internal links as absolute pathes. For example, a menu link will be created as:

```
<li class="menu-773"><a href="http://en.example.com/test" >test</a></li>
and not as
<li class="menu-773"><a href="/test" >test</a></li>

```

So, I could create a domain alias with Apache, to send requests from en.m.example.com to en.example.com, but all internal links would bring the user back from the mobile version to the normal. How can I solve this problem?

# Answer
The answer is: using multiple domains for one language is not possible with Drupal 7 and there is – as far as I know – no module that adds that functionality.

But to achieve this aim anyway, there is workaround: As mentioned above, the problem with language domains is, that all internal pathes that have an language specific path alias and are created with the Drupal core function *url()* are created as absolute pathes. Responsible for that behaviour is the function:

```
locale_language_url_rewrite_url(&$path, &$options)

```
1. Don't set a language domain for that default language. If you don't do that, Drupal will not create absolute pathes for the default language if – for example – use the domain *xyz.example.com*, where xyz.example.com is not set as domain for any language, Drupal will create al urls relative and so clicking of any internal link will keep the subdomain. But you can't use that method, if you want to have language sensitive subdomains as described above:

for English: en.example.com & en.m.example.com

for German: de.example.com & de.m.example.com etc.
2. So the second method would be, to alter the current language of all types with the function: hook\_language\_init. I use the following code, to get the above example working:

:

```
# hook_language_init()
function my_module_language_init() {
  // Current path
  $url = $_SERVER['SERVER_NAME'];

  // Global language object and get languages
  global $language;
  $languages = language_list();

  // Get all subdomains
  $reg = '/^((?:([^\.]+)\.)?(?:([^\.]+)\.))?([^\.]+\.[^\.]+)$/i';
  preg_match($reg, $url, $up);

  # We won't allow all subdomains, only 'm.' and 'm2.'
  # Change this for an other use case.
  if ($up[3] == "m2" || $up[3] == "m") {

    if (!isset($languages[$up[2]])) {
      $langcode = $language->language;
    } else {
      $langcode = $up[2];
    }
    $new_language         = $languages[$langcode];
    $new_language->domain = $new_language->language . "." . $up[3] .".". $up[4];

    // Set url options
    $options['language'] = $new_language;
    $types = language_types();

    // Set all language types and language domains
    foreach ($types as $type) {
      $GLOBALS[$type] = $new_language;
      $GLOBALS[$type]->domain = $new_language->domain;
    }
  }
}

```
> 2 votes

# Answer
Once you've set up Drupal to serve different languages in different domains, you need to instruct your web server to send requests from multiple domains to the same Drupal site.

In Apache, you'll need to edit the `.conf (httpd.conf)` file and add aliases to all the different domains. For example:

```
ServerName en.example.com
ServerAlias en.m.example.com

```

In addition to this, you'll also need to point the domain name server (DNS) to your server for all the domain names in different languages.
> 5 votes

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


title: EntityFieldQuery: Load all revisions

text:
# Question
Title: EntityFieldQuery: Load all revisions
I have a self-defined entity with revisions called `command`. The instance with `id=1` has 3 revisions. Now I want to load all these revisions. Tried this:

```
$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'command')
  ->propertyCondition('id', 1)
  ->age(FIELD_LOAD_REVISION)
  ;
$result = $query->execute();

```

but it gives me still only one revision, the current one. There's no difference to calling it without `->age(FIELD_LOAD_REVISION)`.

What am I doing wrong?

# Answer
> 4 votes
**Solution:** Use a regular query instead of a EntityFieldQuery to load all entity revisions.

**Explanation:**

In the age function on entity.inc there's this comment:

> Blockquote * Note that this only affects field conditions. Property conditions always * apply to the current revision.

So as long as you provide a **property condition**, you will get only the last revision id. If you query with **fieldCondition**, you will get the revisions, as the age method is actually querying the field revision table and not the node revision one (field\_sql\_storage.module):

```
  else {
    $tablename_function = '_field_sql_storage_revision_tablename';
    $id_key = 'revision_id';
  }

```

Otherwise, the entity table is queried so it will always return the entities and not the revisions.

You could do a addTag and modify the query object there but at this point the modifications will be so big that it's actually better to do a regular query instead.

Example using generic info for the entity and entity api entity\_revision\_load.

```
  $entity_type = 'command';
  $value = 1;
  $entity_info = entity_get_info($entity_type);

  $query = db_select($entity_info['revision table'], 'revision');
  $query->fields('revision', array($entity_info['entity keys']['id'], $entity_info['entity keys']['revision']))
    ->condition('revision.' . $entity_info['entity keys']['id'], $value);
  $revisions = $query
    ->execute()
    ->fetchAllAssoc($entity_info['entity keys']['revision']);

  $entities = array();
  foreach ($revisions as $key => $revision) {
    $entities[] = entity_revision_load($entity_type, $key);
  }

```

---
Tags: entities, nodes, database
---


title: Drupal 7 Customize Node Add Form

text:
# Question
Title: Drupal 7 Customize Node Add Form
First, let's describe what I have already:

* Vocabulary: "Categories" with some terms added(cat1, cat2, cat3)
* New content type "custom\_page" where I added a new field of type "Term reference" using vocabulary "Categories";
* Widget type for previous field is "Check boxes/radio buttons" because a custom\_page can be part of multiple categories;

It is possible when adding a new custom\_page, to add additional fields for each category selected?

Assuming, I checked "cat1" and "cat3" -\> it is possible to add 3 more fields inline (new\_field1, new\_field2, new\_field3) with every category selected?

Thanks, Alex

# Answer
> 0 votes
Can't do with core functionality. You need to modify form using hook\_form\_alter. Probably you would want to use Drupal form's AJAX to make fields appear.

I don't know if there is a contrib module to do this, I can't see any.

---
Tags: taxonomy-terms, entities
---


# Question
Title: Drupal 7: hierarchy disabled setting on taxonomy vocabulary
I would like to disable taxonomy hierarchy for a vocabulary. In older versions of Drupal there used to be a setting on the vocabulary page:

> Hierarchy: disabled

Can do I achieve this with Drupal 7?

# Answer
> 1 votes
I found how to do it. I ended up using hook\_form\_FORM\_ID\_alter on the taxonomy form in the admin area, like so:

```
function hook_form_taxonomy_overview_terms_alter(&$form, &$form_state) {
        $form['#parent_fields'] = FALSE;
}

```

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


# Question
Title: Using Ajax-Callback with ajax_command_invoke to invoke custom jQuery command
I have a button on a form that when clicked adds an additional subsection to the form via ajax. Now I need to make it so the form automatically scrolls to the start of the newly added content.

I rewrote the ajax callback function so it returns an ajax command array instead of just the changed form data, and added an `ajax_command_replace` call in the array to still have my content replaced. This works and from the user side everything is unchanged.

Now I found out that I can add an `ajax_command_invoke` command to have a jQuery function called upon the DOM element I want to interact with. Unfortunately there didn't seem to be an in-built `scrollTo` jQuery function, so I had to add my own.

This function works when I call it via Firebug, but the ajax callback just gives me an error:

> TypeError: $element\[response.method\] is undefined $element\[response.method\].apply($element, response.arguments);

So I guess my problem is that my custom jQuery module isn't actually added to jQuery at the time the callback is handled, but only after that?

Here's my configuration (sensitive data hidden with `<...>`:

Within the Drupal Module, my callback function:

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

  drupal_add_js(drupal_get_path('module', '<...>') . '/js/jquery_plugins.js');

  $commands = array();

  $commands[] = ajax_command_replace(NULL, drupal_render($form[<element>]));
  $commands[] = ajax_command_invoke('<...>', 'scrollTo', array(750));

  return array(
    '#type'     => 'ajax',
    '#commands' => $commands
  );

}

```

In the included file, my jQuery scrollTo function:

```
(function(jQuery) {
  jQuery.fn.scrollTo = function(data) {
    jQuery('html, body').animate({
      scrollTop: jQuery(this).offset().top
    }, data);
  };
})(jQuery);

```

Where should I include my jQuery module so the callback knows what I want from it when it's handled?

**Update:**

I had most of my help until that point from this similar discussion on Drupal.org. It seems to have worked for them.

# Answer
> 1 votes
Using `drupal_add_js()` in an AJAX callback will (at best) have weird results. Come to think of it I'm not sure I've ever actually seen it work.

The simplest solution is to add the JS in the form function itself, that way it'll always be available regardless of the AJAX state of the page:

```
function MYMODULE_some_form($form, &$form_state) {
  // Moved from the AJAX callback to here.
  $form['#attached']['js'][drupal_get_path('module', '<...>') . '/js/jquery_plugins.js'] = array();

  // ... Rest of the form
}

```

---
Tags: forms, ajax, javascript
---


title: Export modified Administration Views

text:
# Question
Title: Export modified Administration Views
I am using Aministration Views module to have a custom page for content list. I have added some new columns to the view and now I want to export all that in a Features so I can deploy it on my staging server. The problem is that I just can't export it in a feature, when I create the feature, it is just "empty", there is only a depedancy to admin\_views but I can't see changes I have made.

Anyone has a solution for this?

# Answer
To export a view, go to http://example.org/admin/structure/views/view/your\_view/export Then wrap it into a module using hook\_views\_default\_views() and export that module.

Not the easiest way, but reliable.
> 1 votes

---
Tags: views
---


title: Drupal db Queries

text:
# Question
Title: Drupal db Queries
I have this SQL query

```
"SELECT url_alias.alias FROM url_alias, taxonomy_index WHERE url_alias.source = CONCAT('taxonomy/term/',taxonomy_index.tid) AND taxonomy_index.nid = 6"

```

I need to execute it in my drupal module. How to do it?

# Answer
> 1 votes
```

$results = db_query("SELECT url_alias.alias FROM {url_alias}, {taxonomy_index} WHERE url_alias.source = CONCAT('taxonomy/term/',taxonomy_index.tid) AND taxonomy_index.nid = :nid", array(':nid' => 6));

foreach ($results as $result) {
  // Whatever you want to do with results
}

```

# Answer
> 0 votes
db\_select:

```
$query = db_select('learning', 'n')
    ->fields('n')
    ->execute();
  $rows = array();
  while($data = $query->fetchObject()){
    // Fill the table rows
    $rows[] = array(
      $data->name,
      $data->email,
      $data->age,
      $data->gender,
      $data->about
    );

```

db\_insert:

```
function survey_form_submit($form, $form_state) {
  // Here u can insert Your custom form values into your custom table.
  db_insert('learning')
    ->fields(array(
      'name' => $form_state['values']['name'],
      'email' => $form_state['values']['email'],
      'age' => $form_state['values']['age'],
      'gender' => $form_state['values']['gender'],
      'about' => $form_state['values']['about'],
    ))->execute();
    drupal_set_message("successfully saved survey details.");
    drupal_goto('admin/people/survey');
}

```

---
Tags: 7, database, tokens
---


title: Default value to drupal variable

text:
# Question
Title: Default value to drupal variable
I have a piece of code that I want to have the default value be a variable, but I need to know how to set a default value if the variable is not set:

```
  $form['background_audio_height'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#default_value' => variable_get('background_audio_upload_path'),
'#size' => 5,
'#maxlength' => 3,
'#required' => TRUE,
);

```

How can I set a default value if background\_audio\_upload\_path is not set?

# Answer
You can pass a second variable to the variable\_get() function, which is a default value.

example:

```
variable_get('background_audio_upload_path', 'path/to/foo.bar');

```
> 7 votes

# Answer
```
<?php

function my_module_menu() {
  $menu['my_form_page/%'] = array
  (
    'title' => 'My Form',
    'page callback' => 'my_form_page',
    'page arguments' => array(1),
    'access callback' => TRUE,
  );
  return $menu;
}

function my_module_load_data($item_id) {
  return db_query('SELECT value1 FROM {some_table} WHERE item_id = :item_id', array(':item_id' => $item_id))->fetchObject();
}

function my_form_page($item_id) {
  $my_object = my_module_load_data($item_id);
  return drupal_get_form('my_form', $my_object);
}

function my_form($form, &$form_state, $my_object) {
  $form['element1'] = array(
    '#type' => 'textfield',
    '#title' => t('Item 1'),
    '#default_value' => $my_object->value1,
  );
  return $form;
}

```
> 0 votes

# Answer
If you're doing many operations with variables, consider using Variable module.

Once setup, it will save your time a lot. One of the problem that it will fix for you is the default value of the variable which you will need to change only in one place, instead of going through all the code. It will also provide you a configuration form for your variables for free.
> 0 votes

---
Tags: forms, configuration
---


# Question
Title: Changing the module path on custom install profile
I would like to have the profile install the modules I list in my profile `.make` to `sites/all/modules/contrib` instead of in the profile directory `profiles/my_sweet_profile/modules/contrib` is there any way to do this without having to use a script to copy the modules, and then rebuilding the drupal registry?

I have read this DA post, but the answers contained pertain to the more canonized distribution profiles (OpenAtrium). I am not going to be rerunning this installation profile on the same site, so there is no need for me to preserve the initial structure.

Thanks!

# Answer
> 1 votes
You can get an example in Videola profile: https://github.com/Videola/videola/blob/master/videola\_starter.make \- main make file which downloads only profile from github.

Then see main make file with all the modules: https://github.com/Videola/videola/blob/master/videola.make which shows you an example of what you want to do.

```
projects[admin][subdir] = "contrib"

```

---
Tags: installation, distributions, drush
---


title: Rules offset with a fixed time

text:
# Question
Title: Rules offset with a fixed time
I'm trying to set data value for a date field. The value is 7 days after a node was created. This works fine but I would like to have a fixed time of 6pm as the time value. Currently the time is set as the same time as the created node. How do I fix this?

# Answer
The Drupal way was easier than I thought.

I changed it to direct input and used

```
now +7 days 18:00:00

```

and it's working.
> 2 votes

# Answer
You can do this very easy in PHP (ver. 5.3 and newer) by operating on the PHP `DateTime` object. Example:

```
$date = new DateTime();
$date->add(new DateInterval('P7D'));
$date->modify("T18:00:00");

```

The first line is the constructor, and sets the time to now without an argument (you can set it to another time by supplying an argument). The second advances it by 7 days. And the third forces the time to 6pm (18:00:00 in ISO 8601 syntax).

Then to see the result:

```
echo $date->format('Y-m-d H:i:s');

```
> 1 votes

---
Tags: 7, rules, datetime
---


# Question
Title: How do I make a rule that deletes a node when it hasn't been viewed for "X" amount of time?
Im on d7. I what to delete nodes that are no longer "pertinent" on my site. I figure the best way to do tho would be with rules scheduler, but if anyone has any other suggestions, I would be open to them. Thanks

# Answer
> 1 votes
You could setup a flag and use rules to flag the page whenever it is viewed. Then add "node has flagging count" condition to your "delete rule" to check if it has less than the amount of views you want and delete it.

# Answer
> 1 votes
I am unfamiliar with any current modules that accomplish this. D7's default structure does not store last\_accessed or similar statistics outside the watchdog, which would be complex to parse and use.

IMHO accomplishing this goal would involve creating a custom module that :

1. Adds a field to store a 'last accessed' field linked to your nodes.
2. Hooks into hook\_node\_view to update this field each time a node is viewed
3. Hooks into hook\_cron to conditionally select any nodes with viewed age greater than your maximum. Call node\_delete for each. You could also set $node-\>status=0 and archive the content without deleting it.

Optionally, you could also add an admin dialog through hook\_menu that set a variable defining the maximium unviewed age of nodes.

# Answer
> 1 votes
If you enable and configure the core Statstics module, page accesses will get logged in the `{accesslog}` table. One of the columns is `timestamp`, which logs when a path was accessed.

I am unaware if you can integrate Statics into rules, but you could make a custom hook\_cron, query `{accesslog}`, check the `timestamp`, and then act appropriately. Just note that paths are logged, not nids.

Personally, I would unpublish the nodes rather than delete them. Also, the Statistics module can be a real performance hog.

---
Tags: 7, rules
---


title: How do I create new Message Templates?

text:
# Question
Title: How do I create new Message Templates?
I am using Drupal 6 with the Open Atrium distribution, as for now I am able to send email notifications every time I post or edit a news. However I'd like to create more message templates, specifically I'd like to use a different template based on the news tags. For instance if I publish a news with "gallery" tag I want to use a dedicated template and so on. Any idea on how I can accomplish that? Many thanks.

# Answer
Previewable email templates is a good module and supports Rules and Tokens.

> The Previewable Email Template (PET) module lets you create email templates, with token substitution, which can be previewed by the user before sending. The emails can be sent to one or many email addresses in a flexible way, and the recipients may or may not be Drupal account holders (users).
> 2 votes

# Answer
I don't know if you can do this strictly with rules and mimemail. I would supsect that the tie to taxonomy, rules and mimemail doesn't exist through the user interface of these modules. However, I know you could accomplish this within a custom module, a rules hook and mimemail. A simple example of how to use mimemail in a custom module is:

```
// email body
$email = "<h1>blah header</h1> <br> <p style="some inline styles">blah blah blah</p>";

$message = array(
  'to' => "someone@e.com",
  'subject' => "yes, a subject",
  'body' => $email,
  'headers'=>array(),
);

// Optionally add an attachement, this is an example from a form submit handler
$message['params']['attachments'][] = array(
  'filepath' => $form_state['values']['file'],
);

$MimeMailSystem = drupal_mail_system('mimemail', 'your_mime_template');
$message = $MimeMailSystem->format($message);

if($MimeMailSystem->mail($message)){
  drupal_set_message('sent.');
}else{
  drupal_set_message('booo, not sent.', 'error');
}

```

This example is for Drupal 7, I don't have any D6 installations to check but it should not be wildly different and I think is the same.

For completeness, if someone does ever want to add an attachment, here is the validate submit handler:

```
function _module_formname_validate($form, &$form_state)
{
    $file = file_save_upload('formFileField', array('file_validate_extensions' => array()));
    if($file)
    {
       if($file = file_move($file, 'public://')){
          $ext = strtolower(pathinfo($file->uri, PATHINFO_EXTENSION));
          //Acceptable extensions
          if ($ext === 'pdf' || $ext === 'doc' || $ext === 'docx' || $ext === 'txt') {
             $form_state['values']['file'] = $file->uri;
          }
          else {
             form_set_error("formField","Your file must be in a PDF, doc, docx or txt format.");
          }
       }
    }
    else {
       // Do something about the form not having an attachement, or don't.
       //form_set_error("formField","error, no attachement.");
    }
}

```

Update: For clarity, this is a completely viable solution. mimemail allows you to create custom templates based on modules. So, you would have to write a module that would create a template based on the taxonomy you desire. Otherwise, there is no way I can find to create different email templates based on taxonomy terms. So, this solution would be a great fit to solve this rather complex problem. In addition, it is very easy to create the templates themselves through the UI admin menu that mimemail has created. Hope this is helpful to you.
> 1 votes

---
Tags: notifications, distributions
---


title: Custom Login form question

text:
# Question
Title: Custom Login form question
In my website have two types people login one is designer another is reader, i want people come to login my website by role. Mean designer go to design login form to login. Reader go to reader login form to login. my question is:

1. how to show two login forms in same page?
2. how to check the role when the visiter login at the same time in login form?
3. is it any module i can use or i need do something customize the user module and how customize?

Plz help!

# Answer
Drupal does not support different login forms. User is either logged in or not, and his privileges depend solely on his roles.

1. You can put a block multiple times on one page using MultiBlock
2. User has his roles, check them normally. He will have his role no matter what form will he use.
3. If you want dynamically give roles, yes, you need to write your own module that will act kinda like login handler, but be prepared to live with huge access permissions problems.
> 2 votes

# Answer
If by login you actually mean the actual account creation, you might want to investigate the Auto Assign Role module:

The Auto Assign Role module serves three primary purposes. The first is to provide an automatic assignment of roles when a new account is created. The second is to allow the end user the option of choosing their own role or roles when they create their account. **The third is to provide paths that will trigger a specific role when an account is created.** The administrator has full control over these functions and can have them working together or independently of each other. Auto Assign Role is integrated with the Content Profile module so that you can have content types serving as registration pages. **You can even replace the default user/register page with a customized version of your own design**.

Otherwise, what @Molot mentioned previously is about it: Drupal doesn't rely upon where you login to generate roles for the user.
> 0 votes

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


# Question
Title: How to do a "Corner Stamp" with Masonry Views?
I am building a jQuery Masonry based website, and have content listed as responsive Masonry bricks thorugh Masonry Views.

I need to be able to insert a so called "Corner Stamp" (a static right corner element) in the views results, so that the results wraps around the corner stamp, as described here: http://masonry.desandro.com/demos/corner-stamp.html

In my case the corner stamp will be a unique View or Block with navigational features.

My question is:
How can I insert the corner stamp into a result set listed with Masonry Views?

Is this possible through Masonry Views (possibly with a template), or should I use jQuery Masonry without the module somehow?

Thank you in advance!

# Answer
Here's a thread in which considerable progress has been made: http://drupal.org/node/1988588#comment-7411276
> 0 votes

---
Tags: views, javascript
---


title: using css in wysiwyg for custom page

text:
# Question
Title: using css in wysiwyg for custom page
I want to allow my end users the ability to save custom css (sass would be better) along with the page content that they edit in a WYSIWYG. I know they can put styles inline but sometimes it's useful to be able to use css selectors instead. Is there a module that will allow this?

# Answer
> 0 votes
Module, no. At least none I know about. You can, however, add text field for css rules and output it inside style tag in your template. Would require some clever javascript to show it in realtime during edit, but should be possible without to much hacking.

---
Tags: 7, wysiwyg, theming
---


title: custom header image

text:
# Question
Title: custom header image
The design for my site includes a large image slider on the homepage and a static image of equal dimensions and position on the inside pages.

To accomplish this I created a custom content type for the slider images and I modified the "Basic Page" content type to have a header image field. Then I created two views. One for the slider and one for the header image. The image slider view uses the flexslider module to create the slideshow. The header image view displays the the header image field with the nid as a contextual filter.

I placed the views in the header region using the blocks system and configured the image slider to only show on the front page, the static header image view on all but the front page.

This worked until I noticed that content that wasn't a basic page and therefore my header image view had nothing to display.

So my questions are.. Did I set up for my scenario the right way (using views and blocks etc) and how can I set a default image to display when content other than a page is being displayed? I did set a default image on the header image field but that only works for pages where I don't specify a value for the header image field. I'm using the Zen starter theme is this sort of thing usually done in the theme?

Thanks for any advice you can give me :)

# Answer
> 1 votes
```
/**
 * Override or insert variables into the page templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("page" in this case.)
 */
function YOURTHEME_preprocess_page(&$variables, $hook) {

    // it allows to use any template named with dashes i.e: page--type--blog.tpl.php
    $variables['theme_hook_suggestions'][] = 'page__type__'. $node->type;

    // define it as a false, so you won't need to use isset() in your template files
    $variables['default_header_image'] = false;

    // an array with content types with contextual header image
    $slider_pages = array(  'page__type__slider',
                            'page__type__sometype'
                            );

    if (!in_array($slider_pages, $variables['theme_hook_suggestions'])) {

        // default header image
        $variables['default_header_image'] = 'your image code';
    }
}

```

**In your page.tpl file:**

```
<!-- Page header -->
<div id="page_header" class="">

    <?php if ($default_header_image): ?>
        <div id="default_image"><?php print $default_header_image; ?></div>
    <?php endif; ?>

</div>
<!-- end page_header -->

```

# Answer
> 0 votes
Image fields can have default image, you should upload it in content type settings area, field settings. It will be treated as field's content when you will render empty field. In other words, should work out of the box, just the way you want it.

Views for slider is usual solution, there are modules to speed things up, but that's all.

For static images in basic pages, using views seems weird. Why not just put that field on top of your display and theme accordingly?

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


# Question
Title: How to connect panel and translated panel after 'Add translation' node?
I translate the panel node by selecting Add translation. After doing this, I setup the panel title, layout etc. Press save, but I then end up with two nodes which aren't connected, ie. switching languages doesn't work. Then, going to the translation still shows the 'Add translation' link! This isn't the case for my other content types.

The only way around this at the moment is to manually couple the two translations together by entering the translated node's title in the 'SELECT TRANSLATIONS FOR' autocomplete search field.

Does anybody know how to solve this problem?

# Answer
Maybe too late, but just in case you still need it: http://drupal.org/node/1994046
> 1 votes

---
Tags: panels, i18n-l10n
---


# Question
Title: Setting a Drupal.settings JS variable from a form field
i'm working on my first custom module and really fumbling along :). thanks in advance for your advice!

**goal** i've added a checkbox to the comment form. if the user leaves it checked, then following comment insertion, i want to run some javascript on the following page.

**possible approach?** i've added the checkbox using hook\_form\_alter:

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

//show the checkbox
  $form['wt_comments_share'] = array(
    '#type' => 'checkbox',
    '#title' => t('Post this comment on your Facebook wall too. Spread the word!'),
    '#default_value' => 1
  );
}

```

this works fine. **however**, i'm struggling to pass the variable from php to js. i read up on adding variables to Drupal.settings using drupal\_add\_js(), but i don't have a solid understanding of basic concepts. this post seems to add values to Drupal.settings using #attached, but i couldn't figure out how to add the value of a normal form field.

i tried to run drupal\_add\_js() within hook\_comment\_presave or hook\_comment\_insert, to no avail:

```
function wt_comments_comment_insert($comment) {
  dpm( get_defined_vars() );

  //nothing
  drupal_add_js( array ("wt_comments" => $comment), 'setting');

  // nothing
  drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
}

```

So i added the variable to the global $\_SESSION object:

```
function wt_comments_comment_presave($comment) {
  $_SESSION['wt_comments'] = $comment->wt_comments_share;
}

```

then, within a hook that *does* run drupal\_add\_js, i add the new session variable to drupal settings as described here:

```
function wt_comments_page_alter(&$page) {

  drupal_add_js("jQuery(document).ready(function () {

      if ( Drupal.settings.wt_comments.wt_comments == 1 ) {

        // dance around! jQuery('body').css('background-color','green');

      }

    });",
    'inline'
  );

  //reset session variable
  $_SESSION['wt_comments'] = '0';

}

```

note: i wonder if hook\_page\_alter is the best choice here...

is this the right approach? thanks again folks! -ryan

# Answer
Adding the value of the new field `wt_comments_share` to `$_SESSION['wt_comments']` is considered a good idea.

Because you're using session to pass values, you don't need to pass it to `Drupal.settings` unless if you want to add new JS file.

To add javascript code to node view you need to use `hook_init` or `template_preprocess_node`

```
function wt_comments_init() {
  // check if page is node and wt_comments is set
  if($node = menu_get_object() && isset($_SESSION['wt_comments'])) {
    // check users allowed to comment on this node
    if($node->comment) {
      // add javascript code
      drupal_add_js("jQuery(document).ready(function () {
            if ( Drupal.settings.wt_comments.wt_comments == 1 ) {
              // dance around! jQuery('body').css('background-color','green');
            }
          });",
       'inline'
      );

      // unset session wt_comments
      unset($_SESSION['wt_comments']);
    }
  }
}

```
> 0 votes

---
Tags: 7, forms, javascript
---


# Question
Title: $views->render() does not display node_path
So I made a view and Im trying to pull the results into an array (which I am json encoding and sending to javascript but thats neither here nor there) but some of the node information isnt being pulled. Specifically the node\_path.

When I preview the view in the edit views page in the backend, the path shows up. But when I pull the view on the front end from my preprocess\_page function the node path is not outputted.

In my view, I'm displaying the following fields:

* Node: Post Date
* Node: Title
* Node: Teaser
* Node: Type
* Node: Path

And each of these fields shows up in the preview. But when I try to pull the view using the code below the path isnt output:

```
$blog_posts = json_encode(theme_get_view_result('front_page_blog_blocks'));

function theme_get_view_result($viewname) {
  // views_get_views_result($viewname) produces the same result as $view->result;
  // Im just showing that I tried both
 //return views_get_view_result($viewname);

  $view = views_get_view($viewname);
  if(!empty($view)){
    $view->preview();
    return $view->result;
  }else{
    return 'empty';
  }
}

```

what I also noticed, is that the date was output as a unix timestamp, and not the format I selected (custom, 'M j').

So the result produced in my console is:

```
    {"nid":"1","node_created":"1312470739","node_title":"blah blah blah this is my title","node_revisions_teaser":
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce auctor vestibulum gravida. Proin ornare nisi non orci feugiat ut hendrerit mi venenatis. Etiam diam ligula, pellentesque et vehicula sed, ultrices at lorem. Vivamus consectetur risus nisl. Vivamus luctus volutpat dolor,","node_revisions_format":"2","node_type":"blog"},

```

So notice: there is in incorrect timestamp, and the node path is missing. Im a total Drupal noob so I have no idea whats going on.

# Answer
aha! turns out render() only produces data saved in the database, and node paths are not saved in the DB. So my solution was to grab the node id from the rendered view, use that to get the node paths, and created a new field with that path like so:

```
function theme_get_view_result($viewname) {
  // views_get_views_result($viewname) produces the same result as $view->result;
  // Im just showing that I tried both
 //return views_get_view_result($viewname);

  $view = views_get_view($viewname);
  if(!empty($view)){
    $view->preview();
    return $view->result;
  }else{
    return 'empty';
  }
}

$blocks = theme_get_view_result('front_page_blog_blocks');
foreach($blocks as $k=>$v)
{
  $node_path = drupal_lookup_path('alias','node/'.$blocks[$k]->nid);
  $blocks[$k]->node_path=$node_path;
}

```
> 0 votes

---
Tags: views, 6
---


# Question
Title: Change the default upload file location for a particular content type
I have a content type "Test" which have "upload file" field. Only for this "Test" content type i want to change the location where uploaded file is stored. I want to store anywhere in my drupal instance not just only in sites/all/default/files/subdirectory.

How can I achieve this.

# Answer
> 5 votes
You might find some information about how to code changing file names in the File Path module.

File (Field) Paths allows you to automatically sort and rename your uploaded files using token based replacement patterns to maintain a nice clean filesystem.

# Answer
> 0 votes
**MaxRequestLen** sometimes gets lowered as a result of server/module updates. Also, adding modules that add to the request length can also introduce this problem. This is why disabling modules can sometimes "fix" the problem.

See http://drupal.org/node/1015938#comment-7412202 for a solution that involves updating your vhost file, eg:

```
<IfModule mod_fcgid.c>
  # 50MB
  MaxRequestLen 52430000
</IfModule>

```

Or try switching from **FastCGI** to **mod\_php** or **php-fpm** (if you're using FastCGI).

---
Tags: 7
---


title: Got error while posting comment

text:
# Question
Title: Got error while posting comment
I'm using **"Unpublish comments with keywords"** action. I've just noticed a PHP error on submitting any comment.

> drupal\_render() expects an array but comment\_unpublish\_by\_keyword\_action() calls it with $comment object. And we have a WSOD.

That's part of error.log

> \[error\] \[client 127.0.0.1\] PHP Fatal error: Cannot use object of type stdClass as array in /.../includes/common.inc on line 5672, referer: `http://.../comment/reply/28`

any suggestions?

# Answer
> 1 votes
It looks like it's already in the issue que at drupal.org (a better place to resolve module issues then here)

Although doesn't look the patch has been merged into the latest cut release (as of time of writing this), but you can see the changes that were made here:

http://drupal.org/node/1461732#comment-5727124

---
Tags: 7, comments, wsod
---


# Question
Title: How to trim trailing spaces from labels of radio buttons/select list elements
Every label of every element of every list has trailing space, and it is annoying and makes styling sometimes hard or in certain ways impossible. I was trying to add :before pseudo element to label with content: "\0020";, to make trailing spaces symmetrical at least, but it doesn't work. How to get rid of them?

# Answer
Yeah, this is a known issue. The form.inc file from /includes/form.inc which themes form labels outputs the following for labels:

```
$t('!title !required', array('!title' => $title, '!required' => $required))

```

The offending space is the space between '!title' and '!required', where !title will contain the actual label text and !required will contain a '\*' for fields that are required to be filled in the form...

In any case, this is all in core, and there is an initiative to fix it for Drupal 8: https://drupal.org/node/1623574. Definitely follow that or add your voice to the mix! Any fix will not be back-ported to Drupal 7, however, because lots of themes rely on that extra space and will be messed up if it is removed.

What you can do in your own case, though, is override the core hook\_form\_element\_label theme function.

So, in your custom theme, just create the necessary function in your template.php file:

```
function YOURTHEMENAME_form_element_label($variables)
{
}

```

Now just copy the entire function from /includes/form.inc and just change the very last return statement to not include the space unless there is a required star ('\*') to go after the label. Your new and improved return should be:

```
return ' <label' . drupal_attributes($attributes) . '>' . $t('!title!required', array('!title' => $title, '!required' => $required ? ' ' . $required : '')) . "</label>\n";

```

That should do it!! However, make sure you click around your site and check whether this messes anything else up before going in production. You may see some labels mashed into other stuff without the space, again because some themes have relied on it! And make sure to clear cache so the new function is picked up.

Let us know if it works...
> 6 votes

---
Tags: 7, theming
---


# Question
Title: How can I assign a URL with a fragment (#) as an array value?
In my form:

```
$form_state['redirect'] = 'mypage/' . $nid . '#comment-form';

```

redirects to:

```
/mypage/1%23comment-form

```

...so it doesn't jump to the comment form. I tried:

```
$form_state['redirect'] = l('', "mypage/$nid", array('fragment' => 'comment-form');

```

...that retuned a bigger mess. I need to link to:

```
/mypage/1#comment-form

```

Basically, I'm trying to jump to the bottom of the page the user is redirected to.

Thanks

# Answer
You can use an array for `$form_state['redirect']`, the elements of which mirror the arguments passed to the `url()` function.

So you can use...

```
$form_state['redirect'] = array(
  "mypage/$nid",
  array('fragment' => 'comment-form'),
);

```

The method it used quite sparingly in core (just 5 occurrences as far as I can tell); `node_form_delete_submit()` contains an example.
> 4 votes

---
Tags: forms
---


# Question
Title: Where do you set/change the SKU for a new/existing product? - Drupal 7 Commerce
i can't seem to find where to change the sku for an existing product variation. is this even possible? Where do i set this?

# Answer
You can change the product SKU on the product edit form.

e.g:

**admin/commerce/products/1/edit**

Because products are referenced on line-items etc.. by their ID value, it's actually OK to change SKU for existing products if needed.
> 2 votes

---
Tags: commerce
---


# Question
Title: Adding html to t() in Drupal 6 template.php?
Hi I am trying to add html to the "t('Older Posts')" and "t('Newer Posts')" Is this possible ? I can figure it out ???? I am in a Drupal 6 template.php file.

This is the code I am trying to add as html -

```
 <a href="" class="action"><span>Newer Posts</span></a>
 <a href="" class="action back"><span>Older Posts</span></a>

```

I need to replace the above in these spots located in the full function below ?

```
 t('Older Posts')
 t('Newer Posts')

```

I want to create something like this

```
 t('<a href="" class="action back"><span>Older Posts</span></a>')
 t('<a href="" class="action"><span>Newer Posts</span></a>')

```

Full Function

```
 function theme_views_mini_pager($tags = array(), $limit = 10,
 $element = 0,  $parameters = array(), $quantity = 9) {
 global $pager_page_array, $pager_total;

 // Calculate various markers within this pager piece:
 // Middle is used to "center" pages around the current page.
 $pager_middle = ceil($quantity / 2);
 // current is the page we are currently paged to
 $pager_current = $pager_page_array[$element] + 1;
 // max is the maximum page number
 $pager_max = $pager_total[$element];
 // End of marker calculations.

$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] :
t('Older Posts')), $limit, $element, 1, $parameters);
 if (empty($li_previous)) {
$li_previous = " ";
}

$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('Newer Posts')),
$limit,$element, 1, $parameters);
if (empty($li_next)) {
$li_next = " ";
}

if ($pager_total[$element] > 5) {
$items[] = array(
  'class' => 'action back pager-previous',
  'data' => $li_previous,
);

$items[] = array(
  'class' => 'action pager-next',
  'data' => $li_next,
);
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}

```

I am trying to figure out if this is possible I have tried many things and nothing has worked yet.

# Answer
> 2 votes
You should probably look into overriding the pager theme functions instead.

# Answer
> 0 votes
I would do it more like this:

```
$html = '<a href="" class="action back"><span>';
$html .= t('Older Posts');
$html .= '</span></a>';

```

---
Tags: views, 6, theming, paging
---


title: Custom tpl.php render issues

text:
# Question
Title: Custom tpl.php render issues
I'm in a custom tpl.php file. I'm also highly confused!

This line renders nothing...

```
render($content['field_subtitle']['0']['#markup']);

```

This line drops the subtitle as expected but in the Devel\_Themer formatting.

```
kpr($content['field_subtitle']['0']['#markup']);

```

I'm trying to custom-theme a content type in a custom node.tpl.php file. Everything should work as expected... but, of course... it's not. Any ideas?

# Answer
It looks like you could use:

```
print $content['field_subtitle']['0']['#markup'];

```

or else just

```
print render($content['field_subtitle']);

```
> 2 votes

---
Tags: theming
---


# Question
Title: How do I render a field on a node twice with two different field formatters?
Is it possible to render a field on a node twice with different field formatters?

I have a content type with the a field type "Email". This field needs to give me as output:

* A link to the default email form ("Email contact form")
* The original input in the field ("Default email link")

I have put the field formats in quotes above.

Does anyone have a clue on how to do this, or if this is even possible?

# Answer
Here is the correct way to do what you are after. See field\_view\_field for some documentation on rendering a field.

* You will need to replace "HOOK" with the name of your function name.
* You will need to add the correct settings for the display types (can be added to the display types array to keep the data together).
* The settings data can be found in the module that defines the field formatter. Looking through the field formatter definitions is probably the easiest way to find the correct settings for the display you are trying to achieve.
* You will need to ensure your field is called "field\_email" or update the code.

Code:

```
<?php

function HOOK_preprocess_node(&$vars) {

    $display_types = array(
        'email_contact',
        'email_default',
    );

    foreach ($display_types as $type) {
        $vars['content']['field_email_' . $type] = field_view_field(
            'node',
            $vars['node'],
            'field_email',
            array(
                'type' => $type,
                'settings' => array(...),
                'label' => 'above',
            )
        );
    }
}

```
> 1 votes

# Answer
You can output the field twice, using different formatters in the template

e.g, in node.tpl.php something like:

```
$output = array();
$email = field_get_items('node', $node, 'field_email');
$output[] = field_view_value('node', $node, 'field_email', $email[0], array(
            'type' => 'email_contact'));
$output[] = field_view_value('node', $node, 'field_email', $email[0],array(
            'type' => 'email_default'));
print implode(PHP_EOL, $output);

```
> 2 votes

# Answer
Not in core ways. You can, however, render field twice in tpl.php, but it will not give you two formatters.
> 0 votes

---
Tags: 7, entities
---


# Question
Title: What permissions are needed for omega tools to create subtheme
I am looking to use Omega Tools, and similar modules quite a bit in the near future, and I am running into this error when trying to create a subtheme using Omega Tools:

I'm at least familiar with the concept of permissions, but I'm unfamiliar with what permission needs to be given to what. Also, is this something that **should** be done? I know that write permissions shouldn't be given willy-nilly.

Note: `ygf` is the directory for the site. The current permissions on the folder are `rwxrwxr-x`The `all` folder, which is the default gives the same error.

# Answer
> 1 votes
To work, the user that runs your web server needs to have write permissions to the target folder. Typically, you have a user that owns the files and then the web server runs as the group so permissions of 755 (ex. rwxr-xr-x) would work on most files except files/directory that drupal needs to write to (ex. files directory, or in this case, your themes folder).

What you need to do is either

* change group ownership of the ygf folder above to the same user that runs your web server;
* or - you can blow open the permissions to the folder (ex. chmod -R 777 ygf) temporarily and then switch it back after this operation.

Regardless, you're probably going want to remove the write permissions on this folder after omega tools has generated the sub theme. Omega Tools just needs this temporarily and it can be risky to have group-writable folders outside of the files directory.

---
Tags: theming, files
---


# Question
Title: how to install drupal with myisam and different collation
How to install Drupal with MyIsam instead of InnoDb and with utf8\_unicode\_ci collation?

I know there are ways to change/convert both afterwards, but maybe its possible to specify it as installation parameter - it would be simpler.

# Answer
> 1 votes
You can do during the installation or you can convert

## For the installation, before you launch the install.php, you need to edit the "/includes/databases/mysql/schema.inc file.

```
// Provide defaults if needed.
$table += array(
  'mysql_engine' => 'MyISAM',    //Changed from Innodb to MyISAM
  'mysql_character_set' => 'utf8',
   mysql_collation' => 'utf8_unicode_ci',  //Added the collation
);

$sql .= 'ENGINE = ' . $table['mysql_engine'] . ' DEFAULT CHARACTER SET ' . $table['mysql_character_set'] . ' COLLATE ' . $table['mysql_collation'];

```

---

in case you want to convert already created tables. put the site on maintenance mode and use phpmyadmin to convert the engines and collations

---
Tags: 7, installation
---


# Question
Title: View that shows posts specific to the node
In my website, under every project we do, there is a project info post which summarises what the project is about as well as all the recent updates(posts) about that project.

this is what it looks like https://i.stack.imgur.com/GI2vM.jpg

I am trying to find a way i can view a 'project-info' node and add a 'view' that shows all the related 'project-posts' related to the particular project that the 'project-info' node is about.

I'm not sure where to begin.

(Drupal 7)

# Answer
You should begin around Views of course. Just make a taxonomy term per project, and use Views to create a page with all nodes of type "update(post)". Then in tpl.php for a texonomy field of "project info post", build a link based on taxonomy term. That's pretty much all.

Entity reference module is worth to look at, too. Using it you could relate all "update" nodes to "project info" node. Similar effect to taxonomy, has it's pros and cons of course. Read about both, and choose your poison - referencing node directly is cleaner way, but taxonomy seems to be supported better, and is in core so less contrib modules for you.

Last but not least - you could simply make the update posts a comments on project info post.
> 1 votes

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


# Question
Title: How to dynamically pass contextual filter to a block view without changing view settings
I have a content type called artists. In various locations I want to feature one of the artists. I have a view block that has a contextual filter for the node id.

I want to display this this block on various locations of the website. I want site admins to be able to change the featured artist ( node id ) but I don't want them to have access to the views interface ) how can I pass the the node id via the blocks interface or is there some other way that I can make a mini admin screen that will let site admins choose the featured artist?

I don't want to use the promoted to homepage feature on the content type or any other field on the content type as the artist themselves have access to edit their content.

Any advice would be greatly appreciated.

# Answer
You have a task:

> " I want site admins to be able to change the featured artist ( node id ) but I don't want them to have access to the views interface )"

and it seems you already decided to use specific solution:

> pass the the node id via the blocks interface

Don't do that. That's pretty weird and unneeded. Easier options are:

* Draggable Views and show only first one
* Use "sticky" or some other field to mark promoted artists (random order, limit 1 in case more than one is selected)
> 0 votes

---
Tags: views, blocks
---


# Question
Title: Simple dialog module and custom JavaScript not working properly. Ready function called multiple times on click
I am using the following code to convert unoredered html list into a select drop down list:

```
jQuery(document).ready( function($) {

//build dropdown - main navigation
$("<select />").appendTo(".region-menu-inner nav");

// Create default option "Go to..."
$("<option />", {
   "selected": "selected",
   "value"   : "",
   "text"    : "Navigate..."
}).appendTo("nav select");

// Populate dropdowns with the first menu items
$(".region-menu-inner li a").each(function() {
    var el = $(this);
    $("<option />", {
        "value"   : el.attr("href"),
        "text"    : el.text()
    }).appendTo(".region-menu-inner select");
});

//make responsive dropdown menu actually work
$(".region-menu-inner select").change(function() {
    window.location = $(this).find("option:selected").val();
});

});

```

At the same time, I am using Simple dialog module for Drupal7 to create modular window for several links on the page. This module comes with only one js file. The code this module is using is below:

```
/*
  @file
  Defines the simple modal behavior
*/

(function ($) {
  /*
    Add the class 'simple-dialog' to open links in a dialog
    You also need to specify 'rev="<selector>"' where the <selector>
    is the unique id of the container to load from the linked page.
    Any additional jquery ui dialog options can be passed through
    the rel tag using the format:
       rel="<option_name1>:<value1>;<option_name2>:<value2>;"
    e.g. <a href="financing/purchasing-options" class="simple-dialog"
          rel="width:900;resizable:false;position:[60,center]"
          rev="content-area" title="Purchasing Options">Link</a>
    NOTE: This method doesn't not bring javascript files over from
    the target page. You will need to make sure your javascript is
    either inline in the html that's being loaded, or in the head tag
    of the page you are on.
    ALSO: Make sure the jquery ui.dialog library has been added to the page
  */
  Drupal.behaviors.simpleDialog = {
    attach: function (context, settings) {
      // Create a container div for the modal if one isn't there already
      if ($("#simple-dialog-container").length == 0) {
        // Add a container to the end of the body tag to hold the dialog
        $('body').append('<div id="simple-dialog-container" style="display:none;"></div>');
        try {
          // Attempt to invoke the simple dialog
          $( "#simple-dialog-container", context).dialog({
            autoOpen: false,
            modal: true,
            close: function(event, ui) {
              // Clear the dialog on close. Not necessary for your average use
              // case, butis useful if you had a video that was playing in the
              // dialog so that it clears when it closes
              $('#simple-dialog-container').html('');
            }
          });
          var defaultOptions = Drupal.simpleDialog.explodeOptions(settings.simpleDialog.defaults);
          $('#simple-dialog-container').dialog('option', defaultOptions);
        }
        catch (err) {
          // Catch any errors and report
          Drupal.simpleDialog.log('[error] Simple Dialog: ' + err);
        }
      }
      // Add support for custom classes if necessary
      var classes = '';
      if (settings.simpleDialog.classes) {
        classes = ', .' + settings.simpleDialog.classes;
      }
      $('a.simple-dialog' + classes, context).each(function(event) {
        if (!event.metaKey && !$(this).hasClass('simpleDialogProcessed')) {
          // Add a class to show that this link has been processed already
          $(this).addClass('simpleDialogProcessed');
          $(this).click(function(event) {
            // prevent the navigation
            event.preventDefault();
            // Set up some variables
            var url = $(this).attr('href');
            // Use default title if not provided
            var title = $(this).attr('title') ? $(this).attr('title') : settings.simpleDialog.title;
            if (!title) {
                title = $(this).text();
            }
            // Use defaults if not provided
            var selector = $(this).attr('name') ? $(this).attr('name') : settings.simpleDialog.selector;
            var options = $(this).attr('rel') ? Drupal.simpleDialog.explodeOptions($(this).attr('rel')) : Drupal.simpleDialog.explodeOptions(settings.simpleDialog.defaults);
            if (url && title && selector) {
              // Set the custom options of the dialog
              $('#simple-dialog-container').dialog('option', options);
              // Set the title of the dialog
              $('#simple-dialog-container').dialog('option', 'title', title);
              // Add a little loader into the dialog while data is loaded
              $('#simple-dialog-container').html('<div class="simple-dialog-ajax-loader"></div>');
              // Change the height if it's set to auto
              if (options.height && options.height == 'auto') {
                $('#simple-dialog-container').dialog('option', 'height', 200);
              }
              // Use jQuery .get() to request the target page
              $.get(url, function(data) {
                // Re-apply the height if it's auto to accomodate the new content
                if (options.height && options.height == 'auto') {
                  $('#simple-dialog-container').dialog('option', 'height', options.height);
                }
                // Some trickery to make sure any inline javascript gets run.
                // Inline javascript gets removed/moved around when passed into
                // $() so you have to create a fake div and add the raw data into
                // it then find what you need and clone it. Fun.
                $('#simple-dialog-container').html( $( '<div></div>' ).html( data ).find( '#' + selector ).clone() );
                // Attach any behaviors to the loaded content
                Drupal.attachBehaviors($('#simple-dialog-container'));
              });
              // Open the dialog
              $('#simple-dialog-container').dialog('open');
              // Return false for good measure
              return false;
            }
          });
        }
      });
    }
  }

  // Create a namespace for our simple dialog module
  Drupal.simpleDialog = {};

  // Convert the options to an object
  Drupal.simpleDialog.explodeOptions = function (opts) {
    var options = opts.split(';');
    var explodedOptions = {};
    for (var i in options) {
      if (options[i]) {
        // Parse and Clean the option
        var option = Drupal.simpleDialog.cleanOption(options[i].split(':'));
        explodedOptions[option[0]] = option[1];
      }
    }
    return explodedOptions;
  }

  // Function to clean up the option.
  Drupal.simpleDialog.cleanOption = function(option) {
    // If it's a position option, we may need to parse an array
    if (option[0] == 'position' && option[1].match(/\[.*,.*\]/)) {
      option[1] = option[1].match(/\[(.*)\]/)[1].split(',');
      // Check if positions need be converted to int
      if (!isNaN(parseInt(option[1][0]))) {
        option[1][0] = parseInt(option[1][0]);
      }
      if (!isNaN(parseInt(option[1][1]))) {
        option[1][1] = parseInt(option[1][1]);
      }
    }
    // Convert text boolean representation to boolean
    if (option[1] === 'true') {
      option[1]= true;
    }
    else if (option[1] === 'false') {
      option[1] = false;
    }
    return option;
  }

  Drupal.simpleDialog.log = function(msg) {
    if (window.console) {
      window.console.log(msg);
    }

  }

})(jQuery);

```

Link that is using this module, in the source looks like this:

```
<a href='/user' name='user-login' id='user-login' class='simple-dialog' title='Login '  rel='width:400;resizable:false;position:[center,60]'>Log in</a>

```

The problem is that when you click on the login link (or any link that is meant to have a popup window), it takes a second or two to load the popup and when it actually loads, second set of select dropdown list is being generated. If you click login link one more time, it generates third select list. Basically it duplicates whatever is converted from ul li into select list. If you click on the link 5 times, it generates 5 select drop downs, one at a time, but adds them in addition to existing dropdowns.

Thanks for help in advance.

# Answer
> 1 votes
It's a good practice to test if changes was already made or not before starting to make them. ready() method is guaranteed to be fired when document is ready, but I can't find anyone mentioning it is guaranteed to run once and only once. And when you open popup window that's already opened, it seems reasonable some browsers will treat document in it as ready again. So why not just wrap your code in an if, testing for menu's existence?

---
Tags: ajax, javascript
---


# Question
Title: unable to set dateboosting in apachesolr with D6
I'm using Drupal 6.22 with apache solr module for search functionality, specifically using 6.x-1.6 version of solr. I had a date field for my node added to the solr indexing named as `ds_myDate` in ISO-8601 format (Y-M-DTH:i:sZ) and used it for sorting the search results which worked fine.

Recently I decided to replace the sort with a search boost functionality so that most relevant search results are boosted based on the `ds_myDate` field. In my custom module's `hook_apachesolr_modify_query` adding the following code (based on understanding from http://wiki.apache.org/solr/FunctionQuery#Date\_Boosting)

```
$params['bf'][] = "recip(ms(NOW/HOUR,ds_myDate),3.16e-11,1,1)";

```

to effect the boosting threw 400 error stating **Can't use ms() function on non-numeric legacy date field ds\_myDate**. Hence I tried using an alternative of adding the same in the queryfield instead of boostfield in the same hook as

```
$params['qf'][] = "recip(ms(NOW/HOUR,ds_myDate),3.16e-11,1,1)";

```

which got added but did not show any impact on the search results.

As I have very little or no access to the Solr server or its logs I logged the solr query in the search function and in both cases the field was added to the query. In the former case of using boost field (throwing 400 error) the solr search url would return a path like

```
...qf=tags_inline^5.0&bf=recip(ms(NOW/HOUR,ds_myDate),3.16e-11,1,1)
&bf=recip(rord(created),4,3403,3403)^200.0&fq=...

```

and in the latter method of using as queryfield would return

```
...qf=tags_inline^5.0&bf=recip(ms(NOW/HOUR,ds_myDate),3.16e-11,1,1)
    &bf=recip(rord(created),4,3403,3403)^200.0&fq=...

```

Would be great to know what I'm doing wrong here or how this implementation in Drupal could be done properly since 7 has a hook like `hook_apachesolr_query_alter` where the date boosting could be done.

# Answer
For the legacy date field that the `ds_` dynamic field is set to use in the 1.6 version schmea.xml, you can use the `rord()` function. It's not considered best practice any longer but it works with field types that don't enable using `ms()`. More information at Solr Wiki. The example query goes like this (copying it here to avoid link rot):

```
recip(rord(creationDate),1,1000,1000)

```
> 1 votes

---
Tags: 6, search
---


title: How to use Form_submit hook?

text:
# Question
Title: How to use Form_submit hook?
I have a form, automatically generated by a content type. I want to run a form\_submit function to input/change some data to get saved in the database.

The content-type already has these fields setup, but I want them to be determined in a form\_submit function rather than via user input.

I can get a form submit function, but I don't know how to add to the array of values being submitted without having to write the whole query myself. What variables do I need to grab and how to alter them to do this?

To be more specific.. in the form\_alter, this does what I want. `$form["field_org_id"]["und"][0]['value']['#default_value'] = $org->id;`

But how do I do the equivalent out of site in the form\_submit? (this is a content-add form and hoping not to rewrite the entire query)

# Answer
1. You have to use hook\_form\_alter or hook\_form\_FORM\_ID\_alter
2. Add your submit handler to $form\['#submit'\] like this `$form['#submit'][]='my_submit'`
3. And write your code:

```
function my_submit($form, &$form_state) {
  // your code
}

```
> 25 votes

# Answer
The FORM\_FUNCTION\_submit() function fires automatically when the form with the prefix generator function is submitted:

```
function generate_special_form(){ // this function name is "FORM_FUNCTION" above
    $form = array();
    $form['field_org_id'] = array(
        '#type' => 'textfield',
        '#title' => 'Organisation',
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

```

When that function submits it will automatically call the function generate\_special\_form\_submit() with 2 parameters, you can get the submitted values like this:

```
function generate_special_form_submit($form, &$form_state){
    // Form above was submitted, now lets clean up $form_state['values'],
    // that's the submitted values in an associative array.
    form_state_values_clean($form_state);
    // And here is the value that was submitted:
    drupal_set_message($form_state['values']['field_org_id']);
}

```

It looks like you're trying to modify a form that is generated in core. If that's the case, use hook\_form\_alter to add the $form\['#submit'\] value as Jibran outline above.
> 3 votes

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


# Question
Title: How do I create a file download popup form?
I am new to drupal, and I want to create a popup form with with form fields for name and email, and a buttom to download and to close the popup.

When users click on the download link, the popup form appears; users enter their name and email address; once the data have been validated, the users can download the file, and see how many users downloaded it.

How can I achieve this.

# Answer
> 0 votes
Email Download does just what you want.

> A tiny module to make downloads only available to people who submit their email address to the site in case the site creator doesn't want visitors to be required to create an account. The email is checked for validity and a cookie with a hard to guess authentication string is stored in a browser cookie. The next time (and of course this first time) the user makes a download, the cookie is checked and the user can proceed. This of course requires cookies to be on on the client side.

---
Tags: 7, files
---


# Question
Title: Pass offset and limit in Drupal embed view
I am having below code to embed a view

```
$view=views_get_view('questions');
$view->set_display('block');

// execute view
$view->execute();
$viewArray = $view->result;

```

How do I set an offset in this? So that I can get the content I need?

I will be displaying a set of content in a page after processing it. I will need to skip first contents sometime. Like skip first 1 sometime or first 3 some other time.

# Answer
> 3 votes
| skip first 1 sometime or first 3 some other time.

Is there a reason you can't do this in the view? If you use a pager you can specify an on offset in pager options.

If you need to do this in code, you do something like:

```
$view=views_get_view('questions');
$view->display['block']->display_options['pager']['options']['offset'] = 'OFFSET NUMBER';
$view->execute_display('block'));

```

# Answer
> 1 votes
You can do it in that way:

```
$view = views_get_view('testimonials');
$view->set_display('block');
$view->set_offset($offset);
$view->set_items_per_page(2);
$content = $view->preview();

```

# Answer
> 0 votes
You can also do this in a custom module using `hook_view_pre_view()` like so:

```
/**
 * Implementation of hook_views_pre_view().
 */
function MODULENAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'whatever' && $display_id == 'something') {
    $view->set_offset(5);
    $view->set_items_per_page(10);
  }
}

```

---
Tags: 7, views
---


# Question
Title: How do I overwrite the particular webform submit event in template.php?
I want to control a particular webform submission event, and I am trying to use the following function in my template.php file.

```
function bartik_form_webform_client_form_7_submit(&$form, &$form_state) {}

```

The function is not working. How can I achieve this?

# Answer
Try hook\_form\_alter() or hook\_form\_FORM\_ID\_alter(). This will help you to alter the array of the submission handlers and add a new submission handler.

```
function hook_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'Your-Webform-ID') {
    $form['#submit'][] = 'custom_settings_form_submit';
  }
}

function custom_settings_form_submit($form, &$form_state) {
  // Your code here.
}

```
> 2 votes

---
Tags: 7, webforms
---


# Question
Title: array_flip() error while creating a menu item with form
My aim is to create a new menu item and display the user profile form on that page.

Here is the code I am using.

```
/**
 * Implements hook_menu().
 *
 */
function profile_preferences_menu(){
    $items['user/%/edit/profile-preferences'] = array(
        'title' => t('Profile Preferences'),
        'page callback' => '_profile_preference_display_preference',
        'page arguments' => array(1),
        'access arguments' => array('access profile preferences'),
        'type' => MENU_LOCAL_TASK,
        'weight' => '0'
    );
    return $items;
}

/**
 * Implementation of hook_permission().
 */
function profile_preferences_permission() {
    return array(
        'access profile preferences' =>  array(
            'title' => t('Access List of profile preferences'),
            'description' => t('Access permission to view all the profile preferences.')
        ),
    );
}

/**
 * Function to fetch and display preferences form.
 */
function _profile_preference_display_preference() {
    global $user;
    module_load_include('inc', 'user', 'user.pages');
    $form = drupal_get_form('user_profile_form', $user, 'account');
    unset($form['account']);
    return $form;
}

```

When I access it using the administrator account, it works perfectly; when I access using another user account (who has the required permission) it gives me the following error.

I wonder if there is any issue with the implementation of `hook_menu()`.

# Answer
> 1 votes
The code that is causing the error is the following one, executed from DrupalDefaultEntityController::load().

```
  // Create a new variable which is either a prepared version of the $ids
  // array for later comparison with the entity cache, or FALSE if no $ids
  // were passed. The $ids array is reduced as items are loaded from cache,
  // and we need to know if it's empty for this reason to avoid querying the
  // database when all requested entities are loaded from cache.
  $passed_ids = !empty($ids) ? array_flip($ids) : FALSE;

```

I could not track down which function is calling `user_load()` or a similar function to load a user entity. As far as I can see, the form validation and form submission handlers added to the form use `$form['#user']` or `$form_state['user']` (which is set from the `$account` parameter passed to `user_profile_form()`). Keep in mind that `$form` and `$form_state` are used when saving the entity, such as in the following function call done from user\_profile\_form\_submit().

```
entity_form_submit_build_entity('user', $account, $form, $form_state);

```

It is always a bad idea to unset a form item, as that would be causing problems with the code that expects those form items to be present.
Removing them, you are also avoiding that the corresponding items in `$form_state['values']` are present. This is probably causing the error you see.

As side note, your page callback is getting a parameter, but that is not used. Instead, your code is using the global user object, which means the shown form is for the currently logged in user, not for the user whose ID is passed in the URL.

I would also change user/%/edit/profile-preferences with user/%user/edit/profile-preferences. The latter automatically validates the user ID and loads the user object, which is then passed to the page callback.

---
Tags: hooks, routes
---


# Question
Title: How Can I Create a Front Page Based on Blocks?
I am building a front page that comprises a number of Views-based blocks. How can I create a front page that has no actual "content" (besides these blocks) without getting a "Page not found error"?

The best I have been able to do is create a Views page and set a filter that will never return a result e.g. nid \< 0. I set the path to the front page and the title to none. This seems like unnecessary overhead.

Surely, there must be a better way?

# Answer
If it was me, I would create a custom page-front.tpl. I'd omit the $content region and probably create a few custom regions for the homepage. I can then place my blocks into the regions.

D6 create page-front.tpl.php
D7 create page--front.tpl.php

Cheers.
> 2 votes

# Answer
Consider using Panels and Ctools Page Manager to create a page and populate it with blocks or other content. You can use one of the built-in layouts, create your own, or use one from Panels Extra Layouts

Once you've built your page, you can then assign its path to the site's front page.
> 1 votes

# Answer
Front Page module is supposed to solve problems like yours:

> The Front Page module allows for customised home pages dependant on role. The pages can be of the following types:
>
> * **Alias** (only 2.x branch) - Allows for another Drupal path to be shown as the home page without redirecting the user.
> * Redirect - Allows you to redirect users to a local or remote URL.
> * Themed - Allows you to enter some static text that will be placed into the content area of a standard Drupal page.
> * Full - Allows for static content to be displayed to the screen as is. This method does not pass through Drupal's theming system.

Alias should be most interesting for you.
> 0 votes

# Answer
Here's what I would do:

* Create a new content type called "Homepage"
* Edit the default display of the content type to hide what you want (e.g. Body).
* Create a Homepage node and point front page to it in admin settings.
* Add blocks to their respective regions (you could also use a grid system like Zen Grids which comes with Zen, this is what I do1)
* You can override page--node--homepage.tpl.php to do stuff like removing the title, or any extra control you want over it.

---

1 A grid system is a really nice way to control the position of elements on your site. Generally I use regions to control the vertical order of elements, and then the grid to position horizontally.
> 0 votes

---
Tags: views
---


title: Disappearing tokens

text:
# Question
Title: Disappearing tokens
Has anyone seen tokens disappear? First I noticed `[site:name]` gone, then I entered the Patterns section of URL aliases and saw a bunch of errors caused by invalid tokens. In particular, the following tokens became unrecognized: a taxonomy term token `[term:parents:join:/]` a node token `[node:field-kateg-zastos:url:path]`

I have an (almost) mirror copy of the site, with the same version of Token (1.1) installed, and without any token problems.

# Answer
> 1 votes
The problem got solved through regression tests on a site copy, with a surprising outcome: The Node export module is at fault, even the latest development snapshot (7.x-3.0-rc3+32-dev) built on 17 Jun 2012. An issue has been filed for the module.

# Answer
> -1 votes
Ensuring that the module 'Entity Tokens' is installed and enabled is another possible solution.

---
Tags: tokens
---


# Question
Title: Create a node's author by passing an argument...?
I have a view in which I can see a list of all my users.

I would like to be able to click on one of the names in this list and create a node and have the user that I clicked on be the author of this new node.

Is it possible to do this by passing an argument in the URL, or perhaps there is an easier way to do this that I had not thought of.

Thanks.

# Answer
Use views rewrite on username field to create a "create node" link and prepopulate module using tokens from the views. In this case the username token for the author field.
> 4 votes

# Answer
Thanks to Dee for the idea.

Turns out that use the prepopulate module was indeed the correct way.

One thing to watch is that if you want to create an author using prepopulate, you need to write:

```
[author][name]=[name]

```

The `[name]` in `[author][name]` will get turned into the username in that token...

So use `[author]%5Bname%5D` instead - worked for me...
> 0 votes

---
Tags: views, users
---


# Question
Title: Related node views - some elements with date field, some without. How to include elements with no date in results?
I have a views block that displays related nodes based on tags. (See Entity Reference get nodes based on tags.) The comment links to the solution I found.

Now, I have to add another filter to the view.

Some of the related nodes have a date field (start and end date), and some do not. When I add a filter to exclude nodes where end dates have come and gone, no related nodes without the date field is shown.

How is it possible to filter out nodes where the end date is greater or equal to now on nodes with the date field, but still show nodes that do not have the date field?

# Answer
> 1 votes
Problem is in the very SQL. No date field in node means null value in result set. Any logical operation with null ends up returning null, see manual. And null is a logical false for conditions. So, each time you test a date to see what are OK, MySQL excludes them - lack of date is not a date in acceptable range.

If views would support negative filtering (exclude matching), it would be just as you want it. But views support only positive filtering (include only matching).

Enough of diagnosis, time for solution! On the block's header `Filter criteria` you have a dropdown with `add` seelcted. Drop it down and use `And / Or, rearrange`. Make your filters OR, and after date limit add some other filter, one that will return true for no-end-date nodes. Here comes the tricky part - you can select the same field multiple times, but you cannot use null in place of date. If nodes without a date are simply of another content type, you are good. If they are of the same type, you have a problem - I'll add solution for that particular case if I'll find it.

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


# Question
Title: Does Drupal modify folder permissions during runtime?
Does Drupal modify the permissions on folder within the sites folder? Is there an edge case where this is possible outside of install?

I've been seeing an issue where a sites folder whether it be default or blah.com is getting it's write permissions removed after loading the site.

It's not specific to one codebase, it occurs across multiple codebases (no modifications to core) and across multiple versions 6/7.

This is problematic when using git with a specific site folder as git can no longer perform checkouts and merges without the write permissions.

# Answer
String `chmod` is found in 11 files in my Drupal 7.22 installation. Next 9 occurrences are found in Drush and Coder modules, and one in Examples for Developers module.

One of the files frequently turned read only is settings.php and it is done exactly to stop people from overwriting it with automatic tools.
> 2 votes

# Answer
Yes drupal modify `default` folder permission during runtime, and this folder is what exactly you should add it to your `.gitignore` because it contains user uploaded files which have not value to keeping in repository.
> 2 votes

---
Tags: files
---


title: Problems moving to production site

text:
# Question
Title: Problems moving to production site
I have developed a D7 website locally (WAMP), now I want to move it to a production server.

The production server has a SVN repository, so when I want to move my local files to the server I do a commit of all the changed files. To sync the databases I get a dump of the local DB and I import it in the DB on the server. First of all, is this a proper way to move my site to production or is there a better workflow?

The problems I encounter are these:

* When I enable caching and aggregation on my local site and then sync the two databases, when I go to the production site it's like all my stylesheets are gone. There's no css styles applied whatsoever.
* When I disable caching and aggregation and sync the databases, the styles are back but it's like it's the design of a month ago. The design of the local site doesn't resemble the design of the production site. When I look at the page source, I see the CSS files getting called as: pages.css?mmtwln. What does this ?mmtwln mean?
* I can't login to the admin pages on the production site. When I enter my username and password nothing happens but the page getting refreshed. No error message, no red border around the textboxes. The rewrite module is enabled on the production site. I also set the $base\_url and $cookie\_domain in the settings.php (I have a multisite configuration, should $base\_url and $cookie\_domain go in sites/default/settings.php or sites/mysite/settings.php?).

If anyone can help me with any of these questions, or point me in the right direction I'll be forever grateful.

# Answer
> 3 votes
* Exclude `/sites/*/files/css` and `/sites/*/files/js` from repository. It's just a cache so it should never be committed or migrated.
* Before each migration purge `/sites/*/files/css` and `/sites/*/files/js`. That way you will get rid of months old cache. After each migration, make sure these directories are writeable. `mmtwln` seems to be a string added by Drupal or some module to prevent proxy caching, or it may be a string added by a proxy itself. it shouldn't affect static files at all (except cache prevention, but even that isn't sure)
* Your site fails at saving cookies. Check your cookie domain settings in sites/mysite/settings.php and make sure you have right data in example.org/admin/config/system/site-information

If above is insufficient:

* manually (via ssh/sftp/ftp) compare offending CSS files. Does the version downloaded from server look the same as version you was sure you uploaded? If not, consult your sysadmin as your server is malfunctioning somehow.
* if the version you download from server via ssh is the same you uploaded, but differs from the one you downloaded via http, check carefully your .htaccess - probably there are some redirection rules that make your server to serve file from different location. Common offender is boost module, if you used to have it installed and now only it's rewrites are left, you can easily get the exact behaviour you described.

---
Tags: 7
---


title: How to add new roles in drupal 7?

text:
# Question
Title: How to add new roles in drupal 7?
Drupal by defaults gives us three roles

1. Administrator
2. Authenticated users
3. Anonymous user

Can i add a new roles in it? Like:

* suscriber
* trusted customer

# Answer
> 5 votes
Yes, it is possible.

1. Go to "Home » Administration » People » Permissions"
2. Select the roles shown at the top right
3. Add a new role using the input textbox at the bottom

Your role will be created.

---
Tags: users
---


# Question
Title: Candidate page template filename for particular custom content type entry
I'm working on a Drupal 7 website. I created custom content type for works. I have many fields, and some of them are related to page layout like particular page bg for each entry. So I need custom page.tpl for this particular content type.

So I activated and opened Theme Developer module, and clicked the body area to get candidate name for this particular content type page entry. and it gives me the screen below which doesn't mean anything to me :/ When I click the node area, it is fine, it gives node--work.tpl.php, **but I need for page. I tried "page--work.tpl.php", it didnt work.**

What am I missing?

# Answer
> 11 votes
```
function mytheme_process_page(&$variables) {
    $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
}

```

Assuming your machine-readable content type name is "work", page--work.tpl.php will work.

Refer to this thread for more info.

# Answer
> 2 votes
In template.php add:

```
function themeName_preprocess_page(&$vars) {
  if (isset($vars['node'])) {
    // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--',    $vars['node']->type);
  }
}

```

You can omit `str_replace()`; test what version works best for you.

Then, create a template file whose filename is page–-\[content\_type\].tpl.php. (Replace \[content\_type\] with the content type machine name.)

See http://drupal.org/node/1089656#comment-4426790.

# Answer
> 1 votes
In case you want the node id as well, use this.

```
function mytheme_process_page(&$variables) {
  if (isset($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__type__'. $variables['node']->type;
    $variables['theme_hook_suggestions'][] = 'page__node__' . $variables['node']->nid;
  }
}

```

# Answer
> 0 votes
Having a different template for each content type is not a good practice according the guys at Drupal. That is the reason you don't find `page--work.tpl.php` in the candidate template file list. They feel only the node template files should be different. However if you want to hack in, go ahead.

Use path alias to set up a path based on the content type. And then insert this code

```
 if (module_exists('path')) {
    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
    if ($alias != $_GET['q']) {
      $template_filename = 'page';
      foreach (explode('/', $alias) as $path_part) {
        $template_filename = $template_filename . '-' . $path_part;
        $vars['template_files'][] = $template_filename;
      }
    }
  }

```

into the `phptemplate_preprocess_page(&$vars)` function in `template.php` in the theme folder.

You can modify the code a little to make it more efficient though.

---
Tags: 7, theming
---


# Question
Title: Altering display mode for authoring information
I'm trying to deal with authoring info for articles in Drupal 7. I've found the way to hide or unhide it, and that's all I can do. But what I'd need is find a way to display on certainly tagged articles, but hide when that specific tag is not added. Is there any solution for this without coding? CSS is okay, but I know no PHP.

Thank, cs.

# Answer
As you prefer css, checkout the module Field Formatter CSS Class

> The Field formatter CSS class module allows you to set any text/list/option/taxonomy field to render as CSS class on the node. This enables the node author to select predefined CSS styling per node.

Also Field Formatter Class

> This module allows site administrators to add classes to the outer HTML wrapper for any field display.

Then you can hide your info with css based on this unique class provided by either of these two modules
> 0 votes

---
Tags: entities
---


# Question
Title: Custom made blocks not getting displayed in Blocks page
I am new to Drupal. I tried to write custom module(Sample).. After completion of Module, Enabled at Module. But it is not showing at Block Page.

Please check the below code and correct me..

**first.info**

```
;$Id$

name = First
description = A first module.
package = Drupal 7 Development
core = 7.x
files[] = first.module

;dependencies[] = autoload
;php = 5.2

```

**first.module**

```
function first_block($op = 'list', $delta = 0, $edit = array()){
    switch ($op) {
       case 'list':
        $block = array();
        //List out all blocks you want to create here
        $block[0]["info"] = t('Display info');
        return $block;
       case 'view':
        switch ($delta) {
          case 0:
            $block['subject'] = "ADMIN Header of the block";
            global $user;
            if(in_array('Site admin', array_values($user->roles) || $user->uid == 1)) {
              $block['content'] = "input form";
              $block['subject'] = "Header of the block";
            }
            return $block;
        }
    }
}

```

# Answer
> 2 votes
Did you try to (steps in order):

1. use a minimal hook\_block\_info() definition for your block (such as the one below or even without 'cache' option!) the very first time?
2. manually remove your block's entries in **block** table, if any?
3. then clean all caches?

## Longer version of why these steps may help:

Using a **minimal** block definition such:

```
function sso_block_info() {
  $blocks['applinks'] = array(
    'info'   => t('Single Sign On'),
    'cache'  => DRUPAL_NO_CACHE, // this can also be left out!
  );
  return $blocks;
}

```

Would not list my block in the "Disabled" pseudo-region of *admin/structure/block*!

Troubleshooting revealed that block had been inserted in **block** table, but its value for the *region* column was blank and not the usual '-1' that every other currently disabled block contained!

*Tip:* updating this value to -1 directly within DB made block '*Single Sign On*' show up in block admin's *Disabled* zone instantly!

Then I manually removed my block's entries from DB and cleaned caches to effect Drupal calling again hook\_block\_info. This time my block showed up correctly in block admin UI the first time!

My hunch is that existing config entries in DB for blocks will sometimes interfere with what is indeed correct block registration code! Cache clearing will not affect entries in block table! I guess that certain perhaps invalid combinations of options in hook\_block\_info() will cause D7 to register a block with a blank value for the region (a block appears in) instead of -1 (a disabled block).

# Answer
> 0 votes
Add this line to your hook\_block.

```
 global $user;

```

The `$user` variable cannot be accessible within a function without declaring as global.
Thus, if you logged in as administrator, your condition will not work and your block has no content and subject.

```
 if(in_array('Site admin', array_values($user->roles) || $user->uid == 1)){
          $block['content'] = "input form";
          $block['subject'] = "Header of the block";
 }

```

Regardless of Drupal 6 or 7, you must declare $user as global so that you can use it in the functions (hooks).

---
Tags: 7
---


# Question
Title: How to allow users who have cancelled their accounts to re-activate / re-enable them?
If a user cancels their account on a Drupal 7 site, is there a way to allow them to re-activate their account without requiring administrator intervention?

If a user has second thoughts and wants to rejoin the site using the same e-mail address, I would like to make it easy for them. I have set the **Account cancellation method** to *Disable the account but keep the content*.

# Answer
I ended up doing this using the Rules and Flag modules. I created a per-user flag, "Cancel my account," and the made some rules that would automatically unpublish all content posted by a user if and only if that user flagged himself/herself. I then created another set of rules to re-publish everything if the user then unflagged the "Cancel my account" flag on himself/herself.
> 0 votes

# Answer
There are two URL which can help you in achieving this. First you will have to use Advance User module & then you can extends some hooks of it according to your need for account re-activation. There is a blog written on similar issue which may help you - Enable/Disable User.

I hope you find your solution.
> 1 votes

# Answer
You should use hook\_user\_cancel\_methods\_alter for this. Later on I think when user wants to reactivate his/her account. It will active.
> 0 votes

---
Tags: users
---


# Question
Title: Control content access based on field value in user profile?
I have two specific user types on my website: "Manager" and "Employee". I will have ten managers and 100 employees. Each Manager will manage 10 employees.

Employees will have permissions to create "Content Type A" nodes. I want their managers to be able to edit/view only those "Content Type A" nodes that were created by their employees.

I created a User Reference field in the profile form. that UR field is populated only with the names of the Managers. When a new employee is registered their manager's name will be selected from that UR field.

I feel like I should be able to control each Manager's access to Employee-created content based on that UR value in each employee's profile, but I can't quite wrap my head around how to accomplish that. Would Views be the best bet, or would I need to develop a custom permissions module that compares the logged-in Manager's UID with the UID related to the Manager selected in the UR field on the employee profile? Or perhaps some kind of Rules setup?

Thanks!

# Answer
> 3 votes
User Relationships module seems to be the answer:

> * **User Relationship Node Access** lets users control access to their content based on relationships

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


# Question
Title: render() is not returning anything on custom theme
I am using the newsletter\_export module to allow users to select multiple nodes and export them as html. The node this action is performed on is a content type which uses entity reference to grab content from selected other nodes. The newsletter\_export is also the name of the template file which renders it. It depends on the node\_export module to do this.

However, it doesn't work on the theme that I am working with. It works fine on the Bartik theme. The code in the module that doesn't work is below: the variable for $raw\_markup is always empty.

This level of coding in Drupal is new to me so any tips on fixing or just where to look to fix the problem is really appreciated! The variable $item is just the nid of the node.

```
$node = node_load($item);

  // TODO: Should we add the check for view hook back in for custom node modules?
  // Filter and prepare node in our custom build mode
  $render_array = node_view_multiple(array($item => $node), 'newsletter_export'); //, $weight = 0, $langcode = NULL)

  // TODO: Allow modules to change $node->content before the node is rendered.
  //node_invoke_nodeapi($item, 'view', $teaser, FALSE);
  $type = 'node';
  drupal_alter(array('node_view', 'entity_view'), $render_array, $type);

  // TODO: Set the proper node property, then unset unused $node property so that a
  // bad theme can not open a security hole.

  $raw_markup = render($render_array);

```

# Answer
Simple, and frustrated I spent so long on this.

I copied the tpl file from the module to my theme assuming I could customise it there. But when I deleted it from my theme directory it just started working. The template page inheritance is confusing...
> 0 votes

---
Tags: importing-exporting, emails
---


# Question
Title: Browsing private and public files in IMCE
I have set up a public and a private file location (/admin/config/media/file-system). The private file location is not under the Drupal directory ( it's /opt/private\_files ). I have set the "Default download method" to "Private local files served by Drupal."

I have configured a profile for IMCE ( /admin/config/media/imce ) called "User-1" with a "Directory Path" of {root}/. "Including subdirectories".

I have assigned this profile to the role "administrator" under "Role-profile assignments" for both "PUBLIC FILES" as well as "PRIVATE FILES".

But when I access IMCE directly using mydomain.com/imce I only see the private files.

How can I switch or access the public files ?

# Answer
> -2 votes
While writing this question I found it:

You can access the public files like this: mydomain.com/imce/public

and the private files: mydomain.com/imce/private

---
Tags: 7, files
---


# Question
Title: How do I select a page using views_embed_view?
I am writing a rather intensive ajax interface that requires me to manhandle views quite a bit. I am retrieving the results of the ajax triggers using

```
views_embed_view($view, $display, $arg1, $arg2);

```

Everything works great except the default pager ajax drops the custom info I'm dumping into `views_embed_view`

How can I use views\_embed\_view to select which pager page to return?

drupal 7, views 3

# Answer
I found the answer after a good deal of research and testing.

`views_embed_view()` does not have a way to do this. However, we can use the same method that `views_embed_view()` used.

```
1  $view_args = array($terms); //, $search_text
2  $view_object = views_get_view($view_name);
3  $view_object->set_current_page($offset);
4  $html = $view_object->preview($view_display, $view_args);

```

Line 1,2, and 3 are a simplified version of `views_embed_view()`. I'm bypassing permissions here so check out the function code to see how to do that part.

Line 3 is the part that sets the pager offset and solves my problem.

Note: their are two functions for setting the page offset and I used the wrong one the first time and it caused a log of confusion. The first function `view->set_offset` does not seem to work. I think it sets the correct value in the view object but without doing the theme and query work. so `view->set_current_page` is the one you want to use. I think it goes through the pager plugin to set the query and theme implications as well as set the offset.
> 2 votes

---
Tags: views
---