# Question
Title: Special Character Encoding Issues in Node Titles
I work in an IT department at a museum whose website is built on Drupal. I have experience with other CMSs, but I've only worked with Drupal a little bit. So far, I've been able to help them fix quite a few bugs with their site, but I can't find any information on how to resolve this particular one. On any content type, if the Title field has a special character it displays the character correctly on the site, but if it's linked to on Facebook and it pulls the title, it ends up showing the entity number instead.

An example:

```
Science Movie Night: The Shaman's Apprentice

```

becomes

```
Science Movie Night: The Shaman's Apprentice

```

I've searched around, but I haven't found anything talking about how to combat this.

# Answer
> 2 votes
I just checked with Drupal 7, and it will replace Unicode Character 'APOSTROPHE' with its NCR equivalent (`'`) in headings. This is *not* a bug, but a security measure.

Apperently, when FaceBook receives this, it changes it to `&#39`, with the result you observe. IMHO, this is a bug in how Facebook treats incoming NCRs, and has nothing to do with Drupal. (It is not a good idea for Drupal to have plain apostrophes in headings.) You may want to report this bug to Facebook, but it will probably not be their top priority.

You may also add a feature request to the authors of the module the sites uses to interact with FaceBook, asking it to rewrite NCR apostrophes into a single byte ASCII before sending to FaceBook. They may be more symphatetic.

(Btw: This problem has already been mentioned on stackoverflow: https://stackoverflow.com/questions/11821400/apostrophes-turns-crazy-on-facebook-app \- but I'm pretty sure the upvoted answer is hokum.)

---
Tags: 7
---


title: Adding files to a node

text:
# Question
Title: Adding files to a node
I am adding files to a file field in my node object. Do I have to specify a path for the file(s)? Can't I just add the files to the DB and just add the file objects to the node? I'd rather let Drupal care about the file system.

# Answer
> 2 votes
No, you don't have to specify a folder, file field will use 'sites/default/files' by default. In the file field settings there is a textfield to set a subfolder if needed.

---
Tags: 7, files
---


# Question
Title: why, when I call an AJAX callback, the form submission handler is also called?
I am trying to understand why, when I call an AJAX callback, the form submission handler is also called. I looked at the AJAX documentation and I see no mention of this behavior.

Is this supposed to happen? How do I stop it?

# Answer
The submit function is where you should be executing your code. If you are executing your code in the ajax callback, you are probably doing it wrong. The ajax callback should only return what is needed to be returned. You can use logic to check things in the form generation function (like checking variables to change parts of the form), but any logic needed to be run on form submit, should be done in the form submit function/s.

```
function myform_example_form($form, &$form_state) {
  $form = array();
  $form['submit'] = array(
    '#type' => 'submit',
    '#prefix' => '<div id="myform">',
    '#suffix' => '</div>',
    '#ajax' => array(
      'callback' => 'myform_example_ajax_callback',
      'wrapper' => '#myform',
    ),
    '#submit' => array(
      'myform_example_submit',
    ),
  );
}

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

function myform_example_ajax_callback($form, &$form_state) {
  return $form['submit'];
}

```

If you really need to stop the submit function on a submit button you can do it by setting #executes\_submit\_callback.

eg.

```
function myform_example_form($form, &$form_state) {
  $form = array();
  $form['submit'] = array(
    '#type' => 'submit',
    '#prefix' => '<div id="myform">',
    '#suffix' => '</div>',
    '#ajax' => array(
      'callback' => 'myform_example_ajax_callback',
      'wrapper' => '#myform',
    ),
    '#submit' => array(
      'myform_example_submit',
    ),
    '#executes_submit_callback' => FALSE,
  );
}

```
> 2 votes

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


# Question
Title: regex works in PHP fiddle but not in Drupal
I am having a problem getting some regex to work in Drupal. The below regex works fine:

```
<?php
 $test = "1111~~test1<>2222~~test2<>3333~~test3<>44444~~test4<>11112~~test5";
 $regex = '/~~(.*?)(<>|$)/';
 $matches = array();
 preg_match_all($regex,$test,$matches);
 $test = implode(', ', $matches[1]);
 print_r($test);
?>

```

But when I try to use this to parse the contents of $items\[0\]\["#markup"\] in my field file it does not work, even though the content of that field are the same (look at it through print\_r). This code works inside the tpl file, but as soon as I replace $test with $items\[0\]\["#markup"\] it stops working, does anyone know why this could happen?

EDIT: I think part of the issue is that regex in Drupal may not work with \<\> tags?

Thanks

# Answer
> 1 votes
Yep, the issue was I couldn't use the \<\> symbols. Have to use &lt and &gt instead.

---
Tags: 7, entities
---


# Question
Title: Link to a different view mode from entity reference
Created a entity reference field i CONTENT A and linking it to CONTENT TYPE B. It works fine and takes me to the linked FULL CONTENT. Is it possible to link it to a different view mode like a TEASER or other view mode.

# Answer
> 0 votes
I've used View Mode Page before, and it might do the trick for you. Basically assign a view mode for a content type given a URL pattern. Pretty neat.

# Answer
> 1 votes
a link: `/some/somthing/here` is just a link. It resolves to a resource on Drupal (see `hook_menu`).

A node by default lives at the url `node/NID` which shows the `full` view mode. You need Views, a Context, a Panel -- and a different url then `node/NID` to show a different view mode.

So yes ... you can make a different url to show a teaser. How you make the url is up to you.

---
Tags: entities
---


# Question
Title: Can I remove/hide the "Provide a Menu Link" checkbox when creating new content type?
I am creating a site where authenticated users (not too computer savvy) will be entering in data to the content types we create and the "Provide a Menu Link" may cause them too much trouble. Is there a way to remove or hide this option when I create my custom content types?

# Answer
> 1 votes
In drupal 7, go to edit your content type and in the tabs at the bottom there should be 'menu settings'. If none of the checkboxes under 'Available menus' are checked, then the option of creating a menu item is not displayed when creating content of that type.

# Answer
> 0 votes
You can do this by creating a special role for your non-computer savvy users (go to People menu, then click on Roles tab and add a role). Once you have their role defined, that role will now appear as a long list of checkboxes on the right under the Permissions tab. Scroll down and make sure you uncheck the Menus (Administer menus and menu items) permission. This should prevent them from ever seeing the "Provide a Menu Link" tab when they edit content and/or messing up your menu structure. You can verify this by logging in as that role and then adding/editing content. This also gives higher-level users with Menu permissions (like yourself) the ability to edit menu preferences and tidy up as needed.

# Answer
> -1 votes
If the users do not have the rights to add new menu items, the option should not be visible to them.

---
Tags: nodes
---


# Question
Title: Link Taxonomy with Node via Feeds, Entity Reference and Views
I have a JSON feed that basically describes various objects described in an **object** lets say for example different cars. In the feed, there is an **object\_type** attribute that is just a number. Those numbers refer to different car brands which are described in a **list** object.

Thus the JSON Path is similar to:

```
$.object.object_type
$.list.id
$.list.name
// Where if 'object_type' == 'id', then display: 'name'

```

I've created 2 Feed Importers using JSONPath and was able to add my '**objects**' (cars) to a custom node item (car\_item) as well as to add my '**list**' (of car brands) to a taxonomy vocabulary (brand\_vocab). However I don't seem to be able to actually 'link/relate' them together.

For the brand\_vocab, I have added an Entity Reference field (field\_brand\_id) and set the Target Type to be a Taxonomy Term (using Mode simple). For my Feed Importer for **car\_item**'s, I\`ve added the mapping for the json query to link to field\_brand\_id and set it to id for the query.

In fact, the taxonomy terms don't contain the filled in results for the id even though when I debug the Importer it all works fine.

Ideally I want my custom view to have a drop-down filter of the taxonomy terms (car brands) for the different custom nodes (car items). I have the view set-up, with the taxonomy vocob (brand\_vocab) as a drop-down, just the filter doesn't work as the link between the node and taxonomy isn't working yet.

---

UPDATE: 10/01/2012

Ok so at the moment I have:

Feed Importer

* Object (Cars)
    + Set as Custom content Type: Cars
    + Mapping for: name
    + Mapping for: brand
* Object Type (Car Brands)
    + Set as Tax Term: object\_type
    + Mapping for Term Name: name
    + Mapping for Term GUID: guid

Content Type

* Cars
    + name
    + brand = Entity Reference
    + Target Type: Taxonomy Term - object\_type

Now viewing the actual node for the Cars - I have the right Car Brand showing up as name and not the 'id' which is what I want.

However, the taxonomy term is not actually added to the Content type.

That and I have 2 Entity References that I need to use (Object Type and Category Type), however the content type shows both as the same term! So it seems to be that Entity Reference just checks the ID and then displays that and not the ID and Vocabulary (since I selected one ER to be for 1 Vocab bundle, and the other to be for another Vocab bundle).

---

What am I missing?

# Answer
> 0 votes
OK so I decided to scrap the Taxonomy Vocabulary and use new Content Types instead.

Haven't been able to figure out a good way to link multiple Taxonomy Vocabularies to Content Types via importing in Feeds and using Entity Reference with Views.

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


# Question
Title: how can i remove 'create new account tab ' from login page and show 'access denied' for 'user/register' in drupal  6?
i have two roles in my sites and i have created a separate user registration pages for both roles with different urls.Now i want to remove the "create new account" tab in login page and i want to show "access denied" message for user who try to visit "user/register" page.i am working in Drupal 6.

I removed the 'create new account tab' in theme layer and if user try to access "user/register" means, it shows the default registration page. i want to show access denied message instead showing default registration page. is there any another method or any module for this? how can i implement it?

# Answer
You can create a custom template file, i think user-register.tpl.php and put your personal message in it. This will then just show your message instead of the registration form.
> 0 votes

# Answer
Under admin/user/settings, change "Public registrations" to "Only site administrators can create new user accounts."
> 3 votes

# Answer
I think you should use the hook\_menu\_alter function in a custom module.

http://api.drupal.org/api/drupal/developer!hooks!core.php/function/hook\_menu\_alter/6

You can change the page callback or access callback as per your requirements.
> 2 votes

# Answer
If you are interested to remove tabs, try the Tab Tamer module.

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
>
> Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully when JavaScript is disabled.
>
> Tab Tamer utilizes Drupal's cache system to help conserve server resources.
> 0 votes

---
Tags: users
---


# Question
Title: Create an admin menu in a MENU_LOCAL_TASK
I have added a MENU\_LOCAL\_TASK to a node. Within that local task I want to display an admin menu block using `system_admin_menu_block_page()` however I always get `You do not have any administrative items.` I have no trouble getting admin menu pages to work as MENU\_NORMAL\_ITEMS. Any ideas what I am doing wrong? Code below.

```
function my_module_menu() {
  $items = array();
  $items['node/%node/settings'] = array(
    'title' => 'Account settings',
    'description' => 'Manage your account settings.',
    'page callback' => 'system_admin_menu_block_page',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_LOCAL_TASK,
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
    'weight' => 1000,
  );
  $items['node/%node/settings/upgrade'] = array(
    'title' => 'Upgrade your account',
    'description' => 'Use this form to upgrade your account.',
    'page callback' => 'my_module_upgrade_account',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['node/%node/settings/cancel'] = array(
    'title' => 'Cancel your account',
    'description' => 'Click here to cancel your account and remove all your data.',
    'page callback' => 'my_module_cancel_account',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function my_module_access_account_settings($node) {
  if ($node->type == 'my_node_type') {
    return TRUE;
  }
  return FALSE;
}

```

# Answer
After further investigation reading the code here, it appears that this can be done.

For example, `admin/tasks` has admin menu children in a `MENU_LOCAL_TASK` however, it appears that it looks at the current local task's parent item and then looks for `MENU_NORMAL_ITEM` children.

Unfortunately, this doesn't work in my case since I use wildcard urls (%node) and my local task is not the default one. (like the `admin/tasks` one is).

So I came up with a workaround function that achieves what I need.

The function `my_module_account_settings($node)` basically queries the DB for the current `MENU_LOCAL_TASK`'s `mlid`, then queries the database for ALL menu links that have the current `MENU_LOCAL_TASK`'s `mlid` as their parent.

I then call the theme function for `admin_block_content` and boom.

Let me know if anyone comes up with either a better, or more correct way of doing this.

```
function my_module_menu() {
  $items = array();
  $items['node/%node/settings'] = array(
    'title' => 'Account settings',
    'description' => 'Manage your account settings.',
    'page callback' => 'my_module_account_settings',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_LOCAL_TASK,
    'weight' => 1000,
  );
  $items['node/%node/settings/upgrade'] = array(
    'title' => 'Upgrade your account',
    'description' => 'Use this form to upgrade your account.',
    'page callback' => 'my_module_upgrade_account',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['node/%node/settings/cancel'] = array(
    'title' => 'Cancel your account',
    'description' => 'Click here to cancel your account and remove all your data.',
    'page callback' => 'my_module_cancel_account',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function my_module_account_settings($node) {
  $current =  menu_get_item();

  // get current MENU_LOCAL_TASK mlid
  $current_mlid = db_select('menu_links' , 'ml')
    ->condition('ml.link_path' , $current['path'])
    ->fields('ml' , array('mlid'))
    ->execute()->fetchField();

  // get all menu_links where the parent link id is the current
  // MENU_LOCAL_TASK
  $rows = db_select('menu_links' , 'ml')
    ->condition('ml.plid' , $current_mlid)
    ->fields('ml' , array('mlid', 'link_path'))
    ->execute()->fetchAllKeyed();

  foreach ($rows as $mlid => $path) {
    // load each of the admin menu items within this local task
    // in my case i replace the placeholder/wildcard with the node nid
    $item = menu_get_item(str_replace('%', $node->nid, $path));
    if ($item['access']) {
      $items[] = $item;
    }
  }

  // return the themed block
  return theme('admin_block_content', array('content' => $items));
}

function my_module_access_account_settings($node) {
  if ($node->type == 'organisation') {
    if (user_access('edit org account settings')) {
      return TRUE;
    }
  }
  return FALSE;
}

```
> 2 votes

---
Tags: routes
---


title: login block without a "log in" button

text:
# Question
Title: login block without a "log in" button
I want to create a very minimal login block and thus wouldn't like to have the "log in" button at all. I would like to have only the username and password fields, and log on by hitting "enter".

I have added `display:none` CSS property to the button, but this will stop form from being submitted. What else could be done ?

# Answer
The jquery approach to achieve this one which worked for me (drupal 7) is the following code

```
$("#edit-pass").keypress(function(event) {
  if ( event.which == 13 ) {
    $('#edit-submit').click();
   }

});

$("#edit-name").keypress(function(event) {
  if ( event.which == 13 ) {
    $('#edit-submit').click();
}});

```

`#edit-name` and `#edit-pass` are my two login fields.
> 0 votes

---
Tags: blocks, users
---


# Question
Title: How to display date and time inside a form #markup?
I want to retrive a UNIX epoch (as returned by the PHP function `time()`) and display it as a formatted date as part of a text (i.e. a `#markup` element) in a form. This is not a field where the user is supposed to enter a date. It is just showing the current date and time in a human readable format inside the form.

Is know that I can get a human readable date and time from a Unix epoch with the PHP `date()` function.

However, I am looking for the "Drupal" way of doing this. I think this means that I should display the date and time in the *short format* set by the site manager under *Home » Administration » Configuration » Regional and language*.

Is there a way to do this (or is there another way that is condidered "the Drupal way")?

**Edit:** Function `format_date()` turned out to be the right answer. It depends on a set of format variables (e.g. `date_format_short`) being set. If this variable is undefined, you only get the US-centric formats hard-coded into `format_date()`. The confusing bit is that when you visit the *Home » Administration » Configuration » Regional and language* admin page, it shows you some formats (and I therefore errenously assumed that these formats were those that were defined for the site). But these formats are *not* defined until you press *Save configuration* on that page.

# Answer
> 3 votes
Sounds like you want to use the `format_date()` function.

```
$now = time();
$date = format_date($now, 'short');

```

You can use it with any of the date formats that are defined in your system, or you can pass in a custom `date` string.

---
Tags: 7, forms, i18n-l10n, datetime
---


# Question
Title: Dynamic select list in the form API (dependent dropdown list)?
First I want to select State (like Tamil Nadu, Sikkim, Kerala) after selecting state, depended city list will be display another dropdown list ( for example Tamil Nadu -\> Chennai, Salem, Karur and Kerala -\> Trivandrum, Kochin etc)

Please help me please how to make it, here i have tried some coding but does not work, Please help me

Sstate - Table

```
$query_state = db_select('state', 's');
$query_state->fields('s',array('State_code','State_name'));
$query_state->orderBy('State_name','ASC');
$state_results = $query_state->execute();
$options_state = array();

foreach($state_results as $state_record) {
  $options_state[$state_record->State_code]=t($state_record->State_name);
}

$form['state'] = array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' => $options_state,
  '#required' => TRUE,
);

```

City - Table

```
$query_city=db_select('city', 'c');
$query_city->fields('c',array('District_Code','District_Name'));
$query_city->condition('State_Code','$state_record->State_code','=');
$query_city->orderBy('District_Name','ASC');
$city_results = $query_city->execute();
$options_city = array();

foreach($city_results as $city_record) {
  $options_city[$city_record->District_code]  =t($city_record->District_Name);
}

$form['city'] = array(
  '#type' => 'select',
  '#title' => t('District'),
  '#options' => $options_city,
  '#required' => TRUE,
  '#states' => array(
    'visible' => array(
      ':input[name="state"]' => array('value' => $options_state)
    )
  )
);

```

# Answer
> 1 votes
Basically, in your form declaration, you have to add

In your `form['state']` :

```
'#ajax' => array(
  'callback' => '_ajaxfunction',
  'wrapper' => 'divaroundseconddropdown'
);

```

Then in your `form['town']` :

```
'#prefix' => '<div id="divaroundseconddropdown">',
'#suffix' => '</div>',

```

Now in your `_ajaxfunction` :

```
function _ajaxfunction($form, $form_state) {
  return $form['city'];
}

```

Now, back to your form\['town'\], you simply have to build your $options with the `$form_state['values']['state']` variable, which will contain what has been filled in the first dropdown.

Everything is documented here.

\[EDIT\]

First replace $state\_record in your $query\_city by `$form_state['values']['state'];` \*You can check if the value is formatted the right by `dpm($form_state);` in your \_ajaxfunction.

Then :

```
$form['state']= array(
  '#type' => 'select',
  '#title' => t('State'),
  '#options' =>$options_state,
  '#required' => TRUE,
  '#ajax' => array(
    'callback' => '_ajaxfunction',
    'wrapper' => 'divaroundseconddropdown'
  ),
);

$form['city']= array(
  '#type' => 'select',
  '#title' => t('District'),
  '#options' => $options_city,
  '#prefix' => '<div id="divaroundseconddropdown">',
  '#suffix' => '</div>',
  '#required' => TRUE,
  '#states'=>array(
    'visible'=>array(
      ':input[name="state"]' => array(
        'value'=>$options_state))));

```

Close your function, open a new one :

`function _ajaxfunction($form, $form_state) { return $form['city']; }`

# Answer
> -2 votes
You can try the following,

```
$form['state'] = array(
    '#type' => "select",
    '#options' => $category,
    '#name' => "category",
    '#attributes' => array(
        'onchange' => 'getCategory(this);',
     ),
    '#id'   => "state",
    '#default_value'=> $cat_default,
    '#prefix' => '',
);
$form['city'] = array(
    '#type' => "select",
    '#options' => $skillset,
    '#name' => "skillset",
    '#id'   => "city",
    '#default_value'=> $skil_default,
    '#prefix' => '',
);

```

Using the onclick getCategory(this) function you can fetch the city corresponding to the state using AJAX and add to the second field i.e. city using javascipt

```
document.getElementById("city").innerHTML = result;

```

---
Tags: forms
---


# Question
Title: Using the Panopoly and Commerce Kickstart distributions together
I want to create an e-commerce site, and also have the ability to easily create landing pages, using the wonderful responsive layouts of the panopoly landing page editor.

What is the easiest way to go?

1. Install panopoly on top of commerce kickstart distribution?
2. Install commerce modules on top of the panopoly distribution?
3. Edit the distrubtion makefile \- like someone did with other distributions.

How to do it successfully? And did somebody do it?

# Answer
> 6 votes
I would do #2. To my knowledge, all of the modules in Commerce Kickstart can be downloaded separately; Commerce Kickstart just offers some default configurations. If you run into trouble setting up the Commerce modules, you can always install a copy of Commerce Kickstart on a local machine/another server and reference that while you are setting up your main site.

By contrast, the problem with #1 is that not all of Panoply is easily configurable if you are not using that distribution (for example, the responsive layouts). So it will be much easier to use that, especially if you are going to host it on Pantheon, which is behind Panoply.

You could edit the distribution makefile but that is probably more trouble than it's worth; the Commerce modules are designed to be installed on any Drupal site, so adding them to Panoply is very straightforward.

---
Tags: commerce, distributions
---


# Question
Title: referencing/linking to an entityform and passing nid/other field information through the URL
Thanks in advance for any help with this - I feel a bit like I'm down a rabbit hole. I know there must be several ways to do this, but I'm running into some obstacles.

I'm trying to set up an event registration, but for various reasons, Entity Registration, Node Registration, and Signup don't work for what I'm looking for. I have a content type "event," and I'd like to link to an entityform to allow anonymous users (not registered on the site) to sign up for events. Ideally, information about the event would pass through the url or through using references to the entityform and populate the Event field and the Event Type field.

I tried using node reference URL and entity reference prepopulate, but ran into some major issues trying to reference/link to the actual entityform, as opposed to creating new content through a link.

I'm using entityform because of views integration, because I don't want anon folks to have to create new content (i.e. have a content type "registration" and have them create new ones to sign up), and also because I'm validating their email against an email collected through another registration form (volunteer registration, and I can't do that with the anon\_email field in Entity Registrations.

One caveat - I'm building this site for a tiny non-profit, without the resources to do any real development in the future, so I'm trying to find a solution using features that already exist (or mostly exist).

Thanks so much for any suggestions/pointers! I've been stuck on this for a while now, and I know I'm probably just missing something big.

EDIT:

Found an inelegant solution by passing info through the url. entityformurl/?event=\[node:nid\] did the trick. (Where my field name is event). If there is a better way to do this, I'd love to hear it.

# Answer
> 4 votes
I finally figured out how to get everything I wanted to happen, and figured I would post it here in case anyone had similar difficulties. Entity reference prepopulate + a views block that links to my event registration entityform. This blog was extremely helpful: https://wunder.io/blog/simple-contact-form-per-content-item-with-entityform/2012-10-24 .

One tricky thing for me was getting my taxonomy terms to be recognized by an entity reference field. The only field option I had was "Content: All taxonomy terms," and entity reference taxonomy term fields will only recognize the taxonomy id in the url. So, I used views to rewrite the output of the content: all taxonomy terms field as \[term\_node\_tid-tid\].

Really effing love tokens, views, and entity reference prepopulate right now!

---
Tags: uri, nodes, entities
---


# Question
Title: Weird permissions problems for sites/default/files
I have this weird problem related to permissions on a VPS where I run 2 Drupal 7 websites.

I have an old site, which was migrated over several hosting providers and VPS setups. I also have a freshly installed website.

The new one works perfectly and I can set it to aggregate and compress CSS files plus JavaScript files. All is smooth and without errors.

The old one... each time I set it to do this, It gives me errors such as:

```
The specified file temporary://filepIYgt4 could not be copied to public://js/js_IaQHoIpFqzgiVl19GZEd2HEQg6iqLy6d1_xllBmEbqE.js.
The specified file temporary://fileTbJH3r could not be copied to public://css /css_Lnc8IK4qbp4ueX76wBYIBGAqVihLWtCHHNP7WBSphEM.css.

```

Both websites are configured the same way. The difference though seems to be in the permissions set for the sites/default/files folder. The new website (which works fine) has the permissions set to *0777* and the group and owner are set to *apache*.

The old website (which generates errors) has the permissions set to 0777, the group to *psacln* and the owner is the user I'm using to login to the website via SSH or FTP.

If I change the owner and the group to *apache* for the old website, things still don't work. I get warnings like these:

```
Warning: realpath(): SAFE MODE Restriction in effect. The script whose uid is 10002 is not allowed to access /var/www/vhosts/.../httpdocs/sites/default/files/css owned by uid 48 in DrupalLocalStreamWrapper->getLocalPath()

Warning: realpath(): SAFE MODE Restriction in effect. The script whose uid is 10002 is not allowed to access /var/www/vhosts/.../httpdocs/sites/default/files/js owned by uid 48 in DrupalLocalStreamWrapper->getLocalPath()

Warning: realpath(): SAFE MODE Restriction in effect. The script whose uid is 10002 is not allowed to access /var/www/vhosts/.../httpdocs/sites/default/files/ctools owned by uid 48 in DrupalLocalStreamWrapper->getLocalPath()

```

As you can see, Drupal still can't write to the same troublesome folder. :(

What am I doing wrong? Any advice how to fix this?

# Answer
> 4 votes
I managed to figure this out with the help of the company providing the hosting. So, I'm sharing the solution, in case others have similar issues.

The solution is to make PHP run as a "FastCGI application", instead of an "Apache module". This way, Drupal uses the same user I use to upload files via FTP, when it creates files, etc.

The new website worked fine because I used the one-click installer offered by the hosting provider, which ran everything using the apache user. The old website did not do this.

This solution & problem should apply to all hosting providers using Plesk.

# Answer
> 4 votes
As a website host provider we see this issue all the time. Most hosts that use cPanel will be running with suPHP which enables username.username on all files and directories. If you transfer a site in that doesn't use suPHP then all you need to do is chown -R yourcpanelname.yourcpanelname the sites/default/files directory.

Hope that helps.

# Answer
> -3 votes
What worked for me was to navigate first to the user roles: People --\> Permissions --\> Roles

and then select the 'edit permissions' link for the particular role I wanted to edit.

So: Going straight to the Permission page where all roles are listed in columns did not work. But opening the permission page only for the particular role worked.

Cheers,

Pimmy

---
Tags: 7, users, performance
---


# Question
Title: How do I properly pass taxonomy term from panels to the context filter in views?
I have a **Book Listing** content type and a **Series** content type. Both of these have a **Book Series** taxonomy term applied to them. What I want to do is override the **Series** page with panels and embed a view that will list every book with a matching **Book Series** tag.

What I've tried is creating a content pane view with a contextual filter of "Content: Book Series", Argument input set to "From context", and Required Context set to "Book Series". I've inserted the view and set the argument to the only one available: "Node being viewed". I've tried everything I could think of including creating contexts and relationships in the panel, creating relationships in the view, etc. I'm at my wit's end here. At the moment I'm relying on a separate view page to show what I want, but it's making the site navigation a pain to deal with. What am I doing wrong here and where can I find a good explanation of contexts?

# Answer
it depends how you are trying to get the taxonomy term, but here is one solution. In my example I'm using a node as my context, and a taxonomy field of that node as the contextual argument.

There are basically two things you need to get this to work. One, you need to use view panes, so you can get the arguments from the panels context.

How can I show a view in panel with argument in drupal 7

Second, if your trying to get the taxonomy term from a field you need to convert the term to a term id using validation.

Views contextual filters taxonomy name

For instance this would work if you were trying to create a panel that diplayed a node, and a view of content related by a certain taxonomy term that that node belongs to.
> 4 votes

# Answer
I just tried to do something similar with View Panes and Panelizer and was pretty confused for awhile.

1. Go to "Argument Input" and turn that to "No argument". You don't use Panels contexts for any of the next steps and supplying an argument (Such as a Panels context) will override the default value provided by the contextual filter.
2. Click you contextual filter, select "Provide default value", Type: "Taxonomy term from URL", all of the next three checkboxes, and then select your "Series" taxonomy. The rest is good.
3. Save it and continue wondering why Panels contexts exist.
> 0 votes

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


# Question
Title: COOKIE['session_api_session'] not working in drupal 7
I have a simple module to use the flag module base on the session api. This was working in drupal 6 (and another section working for logged in users), i changed the syntax for drupal 7 (remove db\_results wrapper), and am getting some error i dont understand.

This is my code.

```
  $cookieid = $_COOKIE['session_api_session'];
  $sid = db_query('SELECT sid FROM {session_api}  WHERE session_id = "' . $cookieid . '"')->fetchField();

    // Returns a value only if the anonymous user has at least one bookmark
   $result = db_query('SELECT fid FROM {flag_content}  WHERE sid = ' . $sid . '' )->fetchField();

```

This is the error I get:

> Notice: Undefined index: session\_api\_session in flag\_here\_preprocess\_html() (line 19 of /home/dev/drupal-7.x/sites/www.site.com/modules/flag\_here/flag\_here.module).
>
> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column '' in 'where clause': SELECT sid FROM {session\_api} WHERE session\_id = "";
>
> Array ( ) in tmc\_flag\_here\_preprocess\_html() (line 20 of /home/dev/drupal-7.x/sites/www.site.com/modules/flag\_here/tmc\_flag\_here.module).

All the data exist.

I really don't understand what is going on here.

I have a feeling it is something with `$_COOKIE`and the session\_api\_session, but I could be off.

# Answer
> 2 votes
Quoting value with `"` characters in MySQL is wrong. The MySQL string quote is `'`. The `"` character is the character used to quote table or columns names. With an empty value in $cookieid you have an SQL query searching session-id equals to a column named empty string, this is the

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column '' in 'where clause': SELECT sid FROM {session\_api} WHERE session\_id = "";

with 'foo' as session uid you would have a query searching for rows having session\_id columns equals to value of "foo" column. It would also be wrong.

Use Drupal helpers to write queries. Field and value escapes will be the right ones for the right engine:

```
$sid = db_query(
  'SELECT sid FROM {session_api}  WHERE session_id = %my_sid',
   array('%my_sid' => $cookieid
)->fetchField();

```

Or even more D7 (untested but it's something like that):

```
 $query= db_select('session_api','s');
 $query->fields('s','sid');
 $query->conditions('sid',$cookieid,'=');
 $sid = $query->fetchField();

```

now the 1st error message says there is nothing in `$_COOKIE['session_api_session']`. So you should enclose your code in a:

```
if (array_key_exists('session_api_session',$_COOKIE)
 && !empty($_COOKIE['session_api_session'])) {
   ...
}

```

At least you will avoid the warnings and errors.

About session api usage I would certainly better use session api functions to retrieve the current id, something like **session\_api\_get\_sid()**:

```
/**
 * Return a Session API ID corresponding to the current session.
 * The session id is a created using the same method as Drupal core
 * as defined in includes/session.inc.
 * @param boolean create set this to FALSE if you don't want to create a session
 * cookie if it doesn't already exist.
 */
function session_api_get_sid($create = TRUE) {

```

---
Tags: flags, sessions, cookies
---


# Question
Title: Lightbox/colorbox slideshow and trigger thumbnails
I a have problem getting a slideshow and colorbox to play together.

How would you go if you wanted to:

* have a set of images in a node (let's say it's a multi-value image field)
* display just a single thumbnail as a colorbox trigger
* open up a colorbox with a slideshow of all images in that field.

The thing I want to emphasize is the distinction between having a single thumbnail on a node display level, and the slideshow on a colorbox level. By saying 'colorbox' I mean not necessarily that particular plugin/module. I'm open to any working solution, however I must say I gave up Lightbox2 after I found it poorly configurable.

# Answer
I found my way of doing this. It's a litle bit tricky, but I hope it helps.

1) Get a View where you grab all node's fields, one of them is the "image" (multi-value).

2) To create a Custom Formatter with the Field API, put this code in a custom module (e.g. mymodule):

```
/**
* Implements hook_field_formatter_info().
*/
function mymodule_field_formatter_info() {
  return array(
    'mymodule_formatter' => array( //Machine name of the formatter
      'label' => t('Links to images'),
      'field types' => array('image'), //This will only be available to text fields
    ),
  );
}

/**
* Implements hook_field_formatter_view().
*/
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array(); // Initialize the var
  $settings = $display['settings']; // get the settings

  //get first image
  $firstimg = $items[0];
  $uri = file_create_url(file_load($firstimg['fid'])->uri);
  $html = '<img src="'. $uri. '" id="galeria1-button" class="btnSlideshow" href="#" />'. PHP_EOL;

  //get all images and put them as links but without being seen
  $options = array(
    'html' => TRUE, // This tells Drupal that we're sending HTML, not plain text, otherwise it would encode it
    'attributes' => array(
      'class' => 'galeria1',
    ),
  );
  foreach ($items as $delta => $item) {
    $uri = file_create_url(file_load($item['fid'])->uri);
    $html.= l(' ', $uri, $options);
  }

  //js will make that when you click on first image its as if you were clicking on first gallery image
  drupal_add_js('jQuery(document).ready(function(){jQuery("#galeria1-button").click(function(){jQuery(".galeria1").filter(":first").click();}); jQuery(".galeria1").colorbox({rel:\'galeria1\'});});', 'inline');

  $elements[0] = array('#markup' => $html);

  return $elements;
}

```
> 4 votes

# Answer
Since I haven't used Colorbox much, I will give a general answer, which is how I would start out trying to build this.

First, I would create a View, which filters on the multi-value image fields delta value. This would give me an easy overview of all galleries with their first image as a thumbnail.

Second, create another View that lists all images from the same field, taking a node-id as a contextual argument. This will produce a list of all images in any particular node.

Now the trick is to tie this together in a nice looking way. The primary problem, is to make the second View available in a way that colorbox can display. There is a very interesting Views integration patch in the issue queue that seems like it could be very useful for placing the second View inside a colorbox.

Some additional styling will be required to only show the right images in the colorbox. Semantic Views can help with adding useful CSS-classes on the images that can help hiding/showing the correct images.
> 1 votes

# Answer
One option would be by using the following code in your template.php file and modifying it where necessary:

```
function mytheme_preprocess_node(&$variables) {
  $variables['gallery'] = '';
  if (isset($variables['node']->field_images[$variables['node']->language][0])) {
    foreach ($variables['node']->field_images[$variables['node']->language] as $key => $val) {
      $full_img_url = file_create_url($val['uri']);
      if ($key == 0) {
        $thumbnail_url = image_style_url('thumbnail', $val['uri']);
        $variables['gallery'] .= '<a class="colorbox-load" rel="gallery" href="'. $full_img_url .'"><img src="'. $thumbnail_url .'" alt="Gallery image" /></a>';
      }
      else {
        $variables['gallery'] .= '<a class="colorbox-load" rel="gallery" href="'. $full_img_url .'"></a>';
      }
    }
  }
}

```

Then you could print the gallery in your node.tpl.php file with `<?php print $gallery; ?>`. This specific example should work when Colorbox module's colorbox load option is enabled, image field and theme names are set right and a image style named thumbnail exists.
> 1 votes

# Answer
I have a simple solution for colorbox:

I set up two image-fields in the content type, one for the thumbnail and one multi-value image-field for the slideshow.

In display-settings both fields are set to colorbox and "galery per page".

Via CSS the field for the slideshow is set to "display:none".

Thats it.
> 0 votes

---
Tags: javascript
---


title: Duplicate Website with different theme?

text:
# Question
Title: Duplicate Website with different theme?
I would like to create a duplicate of my existing website (includes all content) and apply a different theme.

So for example I would have www.widgets.com with one theme & products.widgets.com with the same content but a totally different theme.

Also, when I add/update/delete content in www.widgets.com I would like it to change in products.widgets.com.

What's the best way to accomplish this? I'm using Drupal 6.

Thanks-in-advance

# Answer
You could take a look at themekey module.

> ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.

One other property is "host", which would fit into your demands, although this wouldn't be actually a copy of your site. Instead you would just switch the theme on another domain. (On a side note you should consider avoiding "duplicate content" for better serach results.)
> 1 votes

---
Tags: theming
---


title: How do I do this "join"?

text:
# Question
Title: How do I do this "join"?
We have created a vocabulary with terms this way:

```
(main term A)
  |
  +-- subterm A1
  +-- subterm A2
  +-- ..
  \-- subterm A3

(main term B)
  |
  +-- subterm B1
  +-- subterm B2
  +-- ..
  \-- subterm B3

```

Easy right?

Then we've created "`main terms`" roles. Then we've used the taxonomy\_access for those "`main terms`" roles. I.e. The rôle called `main term A` will only be allowed to create subterms of the `main term A` term.

Easy right?

Now we need reviewers. So we've "split" "`main terms`" roles in two:

* "`main terms A contributors`"
* "`main terms A reviewers`"
* "`main terms B contributors`"
* "`main terms B reviewers`"
* ...

And we've used the workbench module to give rights to contribute / or / review. The problem is that the rights given are not detailed enough: if you give "`main terms reviewers`" the right to "review", he/she is allowed to review **all** the "needs-review" nodes. Example: "main terms A reviewers" have the "review" right, so (like it is now) they have the right to review **all** "needs-review" nodes. We'd like them only to see/review *only* the nodes based on their roles: "main terms A reviewers" should only be allowed to review "main terms A needs-review" nodes. We could have used the workbench\_access but this would implie create a section for each "`main terms`". This would kind of force us to duplicate all our "`main terms`" into "`sections`" then give "`sections`" right.

How would you do?

Maybe there's another possibility: the workbench tab is a view. So maybe it could be possible to add a filter based on the taxonomy access control, but it seems that taxonomy access control has no api, and we should have to create a manual join. Maybe there's a way to create a fully customized join based on the taxonomy access control? If so, may I ask how you would do this?

If you think I'm not on the right track, don't hesitate to give me your solution!

Thank you!

# Answer
> 0 votes
I think the easiest option is leave everything as you have it in terms of configuration and your taxonomy term values for `main terms`. The default Workbench (Moderation) logic isn't nested enough for you. So use it's supported hooks to extend the functionality to meet your needs.

Look at hook\_workbench\_moderation\_access\_filter()

```
/**
 * Allows modules to alter moderation access.
 *
 * @param &$access
 *   A boolean access declaration. Passed by reference.
 * @param $op
 *   The operation being performed. May be 'view', 'update', 'delete',
 *   'view revisions' or 'moderate'.
 * @param $node
 *   The node being acted upon.
 */
function hook_workbench_moderation_access_alter(&$access, $op, $node) {
  global $user;
  // If the node is marked private, only let its owner moderate it.
  if (empty($node->private) || $op != 'moderate') {
    return;
  }
  if ($user->uid != $node->uid) {
    $access = FALSE;
  }
}

```

By implementing this hook for the node access check, you can define the nested taxonomy check you're wishing Workbench\_Moderation did for you. In order to find if some node has a value of a certain parent term you may find the Taxonomy Edge API module useful. Then again you might not need Taxonomy Edge.

I believe the Views workbench uses will also support this runtime check.

---
Tags: taxonomy-terms, workbench
---


# Question
Title: views_get_view_result() how to retrieve a specific pager (pagination) page?
views\_get\_view\_result() returns the results of the first pagination page (views pager). Is there a way to retrieve a specific page pagination results?

I have tried `views_get_view_result('MYVIEW', 'MYDISPLAY', array('page' => 3));` but no juice.

If this function specifically does not do this trick, is there any that does?

# Answer
I think I have it figured out:

```
$myview = views_get_view('MYVIEW');
$myview->set_display('MYDISPLAY');
$myview->set_current_page(3); // Get the pagination page 3
$myview->pre_execute();
$myview->execute();

dpm($myview->result); // You need Devel module for using dpm()

```
> 3 votes

---
Tags: 7, views
---


# Question
Title: Checking whether or not an unpublished comment exists on node for current user
I'd like to be able to let a user know that their comment has been submitted and is awaiting approval on every view of that particular node, not just a notification printed in the message region immediately after a submission. I assume there's a way to cross-check the current node's unpublished comments and print something in the comment area if the user shows up as an author of an unpublished comment. I have a feeling I can write a simple function, something like below, but I'm missing something and I'm not sure where to run it (ie, in the .tpl or in an .inc):

```
function find_unpublished_comments_of_current_user(&$comment, &$user) {
    if ($comment->status == 0 && $user->id == $comment->uid){
      //something here
      }
}

```

Thanks for any help.

# Answer
I got around to doing this finally:

```
function comment_detection_node_view($node, $view_mode, $langcode) {

  $current_user_id = $GLOBALS['user']->uid;
  $node_id = $node->vid;

  $query = "SELECT COUNT(c.cid) FROM {comment} c WHERE c.uid = $current_user_id AND c.status = 0 AND c.nid = $node_id";
  $result = db_query($query);

  if ($result) {
    while ($row = $result->fetchAssoc()) {
      $comment_detector = $row['COUNT(c.cid)'];
    }
  }
  // $comment_detector is the number of comments on the current node by the user
  // logged in that are unpublished, i.e. 0 or 1.

}

```
> 0 votes

# Answer
You can achieve this in either of the following way,

1) If you are writing custom function as described in question, a) Write your function in a block by selecting text format as PHP code, and display the block in desired region. b) Otherwise define the function in your module and call it in your node template file node--type.tpl.php

2) Through view: Create a view to show un published comments of a node as follows,

## View

Create a view: Settings: Show: Comments Create block: select Click save & continue

Filter criteria Comment: Approved (No) Advanced-\>Add Contextual filters

1. Content: Nid

Under When the filter value is NOT available

Provide default value : Content ID from URL
2. Comment: Author uid Provide default value -\>choose user id from logged in user

Now assign your block to a region on the node display page, you will get unpublished comments of the particular user for that node,
> 0 votes

---
Tags: 7, nodes, users, comments
---


# Question
Title: Drupal Form API tableselect programmatically check or uncheck checkbox
I followed this code example and built up my own version of how I want to use the tableselect. I want to use the table select for configurations. To do this I need programmatically check or uncheck a checkbox. How would I go about doing this.

Here is the general idea of my code

```
function my_form($form, $form_state) {
  $users = array(
    array('uid' => 1, 'first_name' => 'Indy', 'last_name' => 'Jones'),
    array('uid' => 2, 'first_name' => 'Darth', 'last_name' => 'Vader'),
    array('uid' => 3, 'first_name' => 'Super', 'last_name' => 'Man'),
  );

  $header = array(
    'first_name' => t('First Name'),
    'last_name' => t('Last Name'),
  );
  $options = array();
  foreach ($users as $user) {
    $options[$user['uid']] =array(
      'first_name' => $user['first_name'],
      'last_name' => $user['last_name'],
    );
  }
  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No users found'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

```

I am hoping/guessing it something simple like setting something in the options array.

# Answer
> 4 votes
I fixed this I understand how `#default_value` works now. It has to be an array.

```
$values = array();

$values[1] = TRUE;
$values[2] = FALSE;
$values[3] = TRUE;

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => $values,
    '#empty' => t('No campground to claim'),
  );

```

---
Tags: 7, forms
---


title: 403 Error on AJAX Request

text:
# Question
Title: 403 Error on AJAX Request
I defined the following menu item on my module:

```
function visita_virtual_menu(){
$items = array();
$items['visita_virtual/marker_selected_handler'] = array(
        'title' => t('Marker Selected Handler'),
        'description' => t('Ajax handler for selected markers'),
        'type' => MENU_CALLBACK,
        'access arguments' => array('access panoramas'),
        'callback' => 'marker_selected_handler');
return $items;

```

}

And even created an special permission for my module:

```
function visita_virtual_permission(){
return array('access panoramas' => array(
        'title' => t('Configurar Panoramas'),
        'description' => t('Configurar la visita virtual'),
        )
);

```

}

Obviously the access panoramas permission appeared on the People Permissions configuration tab on Drupal. I assigned it for anonymous users, logged users, and administrator users (Just for testing purposes).

Now my javascript function does the following:

```
alert('Callback URL: '+url);

    $.ajax({
        type : "POST",
        url : url,
        data : {
          'marker_latitude' : location.lat,
          'marker_longitude' : location.lng,
        },
        success : function(data){
            alert('Entro a la funcion success');
        },
        error: function(xmlhttp) {
            alert('An error ocurred: '+xmlhttp.status);
        }
    });

```

The `alert('Callback URL: '+url);` line shows the following info:

/drupal/visita\_virtual/marker\_selected\_handler

However I'm always getting 403 access forbidden error. Why?? What I'm doing wrong???

I have been debugging the server's code, and the problem seems to be at this piece of code on menu.inc.

```
function menu_execute_active_handler($path = NULL, $deliver = TRUE) {
// Check if site is offline.
$page_callback_result = _menu_site_is_offline() ? MENU_SITE_OFFLINE : MENU_SITE_ONLINE;

// Allow other modules to change the site status but not the path because that
// would not change the global variable. hook_url_inbound_alter() can be used
// to change the path. Code later will not use the $read_only_path variable.
$read_only_path = !empty($path) ? $path : $_GET['q'];
drupal_alter('menu_site_status', $page_callback_result, $read_only_path);

// Only continue if the site status is not set.
if ($page_callback_result == MENU_SITE_ONLINE) {
if ($router_item = menu_get_item($path)) {
  if ($router_item['access']) {
    if ($router_item['include_file']) {
      require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
    }
    $page_callback_result = call_user_func_array($router_item['page_callback'],   $router_item['page_arguments']);
  }
  else {
    $page_callback_result = MENU_ACCESS_DENIED;
  }

```

The `$path` parameter is getting it's default value. NULL, and then the `$read_only_path` is obtained from the `q` `$_GET` value, for this case the $read\_only\_path has it's value set on: `visita_virtual/marker_selected_handler` Is that ok?? shouldn't it be `/drupal/visita_virtual/marker_selected_handler`?

At this point `$router_item = menu_get_item($path)` I'm getting a $router\_item that has an 'access' value of false. So that's the reason I'm receiving 403. Still I'm lost, I don't know what I'm configuring wrong for the menu...

# Answer
> 1 votes
The reason you get an *Access denied* is because your menu item doesn't have a `page callback` attribute specified. (You have used `callback` instead). You can check the documentation of `hook_menu()` here.

On the same page, you'd notice that it says - when the `page callback` attribute is omitted for a menu item, the `page callback` of its parent will be taken.

However, when a parent doesn't exist for the menu item in question, it returns an `Access denied`. This happens even before the current user's access to your menu item is resolved; so the `access callback` doesn't really matter. (explains why changing that hasn't helped)

# Answer
> 0 votes
I don't have much experience with Ajax, but try to add to

```
$items['visita_virtual/marker_selected_handler'] = array(
  // ...
  'access callback' => TRUE,
)

```

# Answer
> 0 votes
You need to add

```
'access callback' => 'user_access',

```

In the menu definition (then disable/enable the module)

---
Tags: ajax, users, javascript, routes
---


# Question
Title: How can I include a .inc file before hook_node_access runs?
I'm currently including a `.inc` file in `hook_init()`, but now need to call a function from that include inside of `hook_node_access()`. I've just discovered that, because `hook_node_access()` runs very early on, my file is not included. I then tried to do it inside of `hook_boot()` because the documentation suggests that it runs sooner, but it's still not available to me. I'm temporarily including the file in my .module outside of any function via a simple

`require_once DRUPAL_ROOT . '/sites/all/modules/...`

but would prefer not to do it this way.

# Answer
> 1 votes
First, using the `require` include to load your file is perfectly sound, I think. Alternatively, you could add the include to the `.info` file of your module and allow it to be loaded on every page.

However, to answer your question: We could implement `hook_hook_info()` from a custom module and add `node_access` as a group for `hook_node_access()`. Now, in our module itself, we can have our access callback in a `mymod.node_access.inc` file.

This is probably not recommended as we are dabbling with core (in a small yet unreliable way) with no real value at all but is a way by which you *could* do it.

Once you have done this, I'd suggest running the entire Drupal core test suite once (at least node module's) to make sure that we are okay.

---
Tags: 7, hooks
---


# Question
Title: How to allow users to unsubscribe from organic groups?
In D6, more often than not users change their mind and want to unsubscribe from groups that the have subscribed. How can they do so?

# Answer
> 2 votes
Use this link: http://sitename.com/og/unsubscribe/gid/uid
gid = group id
uid = user id

====== second option =======
Go to "Manage membership" or "My membership". click on "Leave this group"

---
Tags: organic-groups
---


# Question
Title: How to display the field in a joined table with hook_views_data()
I am trying to figure out how to display a field in a joined table, but documentation isn't that great or obvious.

I have my base custom table with a tid field that ties to the taxonomy\_term\_data table. I want to display the term name, based upon my tid field. How to I specify that name field for display in my view?

# Answer
> 1 votes
You'll need to add a relationship to that table, then add the field from that table to your view.

---
Tags: 7, views
---


# Question
Title: How can I better protect access to all site reports except 'Recent log messages' based on role?
How can I better protect access to all site reports within `/admin/reports/` (except for *Recent log messages*)? I know I can hide it through CSS or disable the menu in management menu, but is there a better way to disable it?

I have these role defined (apart from Anonymous and Authenticated):

* System Developer (can view all reports).
* Admin (can only view 'Recent log messages').

Is there any Drupal function or hook that I can use to reach my goal?

# Answer
> 1 votes
Remove the permission for "Admin" to "access site reports" at

`Admin > People > Permissions`.

Add hook\_menu\_alter to a custom module, this part changes the access permission for the `admin/reports/dblog` menu path

```
/**
 * Implements hook_menu_alter
 */
function MYMODULE_menu_alter(&$items){
  // Allow access for administrator role to recent log entries
  // Use suitable permission here, e.g editorial "administer nodes"
  $items['admin/reports/dblog']['access arguments'] => array('administer nodes'),
}

```

Clear menu cache, done.

---
Tags: users, log-messages
---


# Question
Title: How to construct a content type that would be useful for creating a "When is this store open" view
I would like to create an hours content type that could be attached to an individual location. The goal is to create a page that a customer could visit to find which of the stores are open today, along with the times that they are open. This would also reflect closures for holidays.

# Answer
Unless you've got a system managing alot of stores and open hours, it's probably easiest to just have a static "Page" with the store open hours on it. A basic page can be easily content managed.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to check whether content entered by a user in a custom form is valid HTML?
I am trying to write a custom form in Drupal 6 which will check whether the content submitted by a user is valid HTML.

If the content is valid I need to generate a txt file with HTML markup based on the content without a DTD.

# Answer
You can probably do that with PHPTidy (PHP Module) and tidy\_get\_error\_count
> 1 votes

---
Tags: 6, forms
---


# Question
Title: Variable saved as string, not as integer
I have a problem when updating a variable with `return system_settings_form($form)` \- Basically, I store a variable as an integer, but when I press **Save configuration**, it works very well except that it saves the variable as a string, not an integer.

Here's my function:

```
function my_module_settings() {
  $form['my_variable'] = array(
    '#type' => 'select',
    '#title' => t('My module variable'),
    '#description' => t('Update my module variable.'),
    '#options' => array(
       1 => t('Set it to 1'),
       2 => t('Set it to 2'),
       3 => t('Set it to 3'),
    ),
    '#default_value' => variable_get('my_variable', 3)
  );
  return system_settings_form($form);
}

```

So, if I select "Set it to 2" in the select list and hit save, I'll be getting number 2 surrounded by quotes ("2"). I've confirmed with PHP gettype that there's indeed a change of data type.

I wonder if it's related to the select list or something foolish I'm doing? I've tried using a checkbox instead and data type is correctly updated as an integer.

I've been scratching my head without finding a correct solution. Any idea what's going on?

# Answer
**It probably has to do with how php handles POST values.**

That is just generating a form element, which when the form is saved will get sent to the server as a string. Here's an attempt at phpfiddle to show you what's going on: http://phpfiddle.org/main/code/dmk-npy.

Basically you're either going to have to intercept the form submit and cast the variable to (int) there, or you'll need to cast it to an int when you're pulling the variable out.

Edit: Though I have no idea why your checkbox would be saving it as an integer.
> 7 votes

# Answer
As @Cthos said in his answer, you are not doing anything wrong. That is caused by how PHP handles POST values.

For a checkbox form element, that doesn't happen because the HTML output for that form element is similar to the following one.

```
<input type="checkbox" checked="checked" class="form-checkbox" />

```

It's then the form API that associates the numeric value to the checkbox. (See #return\_value.)

The fact a number is changed to a string should not make any difference for the code you write, if you don't use `===` as operator for comparing the value associated with a form element. Even `switch` would consider `'1'`, and 1 as equivalent; you can check that with the following code.

```
$value = '1';

switch ($value) {
  case 1:
    print "Number one!";
    break;

  case 2:
    print "Number two!";
    break;
}

```
> 2 votes

# Answer
The short story is, unless doing strict type checking, the string vs int data type generally doesn't matter all that much in PHP.

> When a string is evaluated in a numeric context, the resulting value and type are determined as follows.
>
> If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP\_INT\_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
>
> Source: http://php.net/manual/en/language.types.string.php#language.types.string.conversion

As you probably know, if really needed, you can cast as an int with:

```
$foo = (int)$bar;

```

However, for most intents and purposes, you can just use your string as an int, yay PHP ;)
> 1 votes

---
Tags: forms
---


# Question
Title: Should I stay with Poormanscron or is it worthwhile to set up an external cron?
In Drupal 7 `Poormanscron` has been made part of core and is the default. I understand that for this to work at all, the site must get regular page requests in order to trigger `Poormanscron` \- but that is not a concern with my site.

The Javascript it inserts in each page is insignificant and should not deteriorate overall performance much (if anything). However, when the cron task actually runs, it will do so when someone requests a page, which is exactly the time you *do not* want your site to appear busy. Is this a concern, or is this taken care of in some way (e.g. by running the cron task as a low priority subprocess)?

`Poormanscron` let you configure frequency, but not *when* to run. I would prefer to have cron run at night, when the site see very little traffic.

So far, I've made do with `Poormanscron`. The fact that it comes "built-in" can be viewed as some sort of recommendation. However, I am concerned about performance. To me, it looks as if setting up an external cron job (with Gnu/Linux/Unix `crontab`) is a *better* solution for a production site. Is this correct, or is there something I've overlooked? Are there other things one should factor into this comparison?

PS. I already know about the *Elysia cron* contributed module (basically a poor man's cron on steroids), and that it will let you set the time of day to run. However, to keep this focused I will prefer answers that only look at the core `Poormanscron` vs. external cron. (Adding contributed modules *also* carries a performance penalty.)

# Answer
> 8 votes
Unless I'm mistaken. Poormans cron significantly impacts page load performance when cron runs. I only use it on sites I'm quickly working with locally and have no intention of working on in the near future again.

Using crontab to run cron completely removes the detrimental performance of using poormans cron, apart from the subsequent page load having to re-build the necessary caches. Using crontab is the better option, it provides predictable behaviour, is more reliable, and has less of an effect on users.

You may also want to look into using drush to run cron.

As a side note, on the performance tab there is a setting for the 'Minimum cache lifetime' does not only affect the page cache but all caches. If a time is not set there then as far as I know all caches are dumped on each cron run. (There are one or two sensationalist blog posts which appear to say otherwise though, but if you look at the core code they are incorrect.) This is something else which comes into play with cron runs and performance.

Elysia cron: This is more cron on steroids, and is not a replacement for poormans cron, as the Elysia cron documentation suggests, you should have cron running every minute to get the most flexibility with it, which poormans cron is just not capable of.

---
Tags: 7, performance, cron
---


# Question
Title: Customizing filter criteria search of a view
I've got a view with an exposed to users filter criteria ajax search. I want to customize it somehow and **link a specific search phrase to a specific node**.

any idea on how to do that? any way around without getting my hands dirty with coding?

# Answer
1. use hook\_form\_views\_exposed\_form\_alter(&$form, &$form\_state, $form\_id)
2. if ($form\['#id'\] == 'views-exposed-form-search-page...'
3. $form\['my\_link\_element'\] = array('#markup' =\> l(t('Seacrh word taken from form\_state'),'node/5'));
> 0 votes

---
Tags: views
---


# Question
Title: Term reference on node edit to ALL vocabularies
I have about ten vocabularies and my content will be tagged with mostly one term of ANY of them.

It would be fine to let the editor choose the vocabulary on node edit form.

Is there yet a module or patch for that situation? It would be the core taxnonomy module, right?

A workaround would be to mount all the ten vocs into the "11th", the root one. (They have been created as mindmaps and splitted for sake of overview and because I want to use taxonomy menu and keep each one small)

# Answer
> 0 votes
The Vocabulary reference module might help you, but it doesn't even have a dev release.

A more involved solution would require adding a term reference field for each vocabulary, then placing a "controlling" list field on top of them, with an allowed value for each vocabulary.

You could then dynamically show and hide the right term reference field using the Conditional Fields module.

The module handles required fields, so you would be sure that one term is always selected.

---
Tags: taxonomy-terms
---


title: Rewrite output of view summary

text:
# Question
Title: Rewrite output of view summary
I'm trying to display a quick summary of the number of different types of products on our site.

The summary contextual filter does this... but it adds hyperlinks to the items and I can't turn that off, and I can't customise the HTML tags or rewrite the output. Is there any to do that?

Thanks

# Answer
You can override the default views templates for summaries in your own theme. There are two of them, which are located at:

* sites/all/modules/views/theme/views-view-summary.tpl.php
* sites/all/modules/views/theme/views-view-summary-unformatted.tpl.php

Which one you have to override depends on the type of summary.
> 2 votes

---
Tags: views
---


# Question
Title: Is it safe to remove database tables of removed modules?
I have disabled the 'mollom' module a long time ago but the tables ('mollom' and 'mollom\_form') still exit in database and it takes time to repair them when I try to optimize the database. So I am wondering whether it is safe to remove these tables altogether?

# Answer
> 6 votes
Disabling a module doesn't mean uninstalling it. To uninstall a module, once you disabled it, you need to go to admin/build/modules/uninstall (Drupal 6), or admin/modules/uninstall (Drupal 7, and Drupal 8), select one of the module listed, and click on the button to uninstall them.

Since Drupal 7, every database table declared with hook\_schema() is automatically deleted from Drupal. Modules still need to delete any Drupal variables they define, though. Since Drupal 8, a module can just be uninstalled. You cannot anymore first disable it, and then uninstall; you just go to admin/modules/uninstall and uninstall the modules you need. If the module cannot be uninstalled for any reason, Drupal will show in that page the reason why it cannot be uninstalled.

# Answer
> 2 votes
If you uninstall the module, it should take care of this for you. By implementing `hook_uninstall()` modules can define the actions to clean up when the module is not needed anymore, e.g. removing database tables, variables etc. If you only disable the module, these actions will not be performed, so you won't loose the configuration when you enable the module again. You have to uninstall it, when you don't need any of its data.

You can go to *admin/modules/uninstall*, see the list of the disabled modules and uninstall them.

If you use drush, check out the `pm-uninstall` command.

---
Tags: 7, database, advertising
---


# Question
Title: Associating Multiple Date/Location Pairs to Node
I'm attempting to create a custom content type in Drupal to represent concerts. Each concert has a title, description, and multiple dates and locations (the concert may be performed on more than one day at different locations).

Since dates and locations are dependent on each other, I thought that the Field Collection module would be ideal for me. This module allowed me to group the date and location field and add multiple values; however, when I try to display the concerts in a calendar in Views (I've tried both Calendar and FullCalendar), I can't find a way to display the title of the concert because it is now in a separate entity.

Is there any way I could make my current content type work, or is there a better way to do this?

# Answer
I was able to solve this by adding a relationship in the Views setup. Now, I have access to all the fields of the host entity.
> 1 votes

---
Tags: views, datetime, location, entities
---


# Question
Title: Creating static pages on production from a local module
This question could have multiple types of answers, so I'll take anything you guys have to offer.

I have to transform an XML feed into a set of Pages (content-wise). Currently, I have a module I'm developing locally using PHP and SimpleXML in order to dynamically simulate these pages (so, each page being rendered is a completely dynamic thing controlled by the module).

I need to take this output and create a set of static pages on a production server. One *painful* thought I had was to render each page, copy the generated HTML, and physically create a new node. As there are a lot of pages being generated, this would be a long and drawn out process.

What would be nice is for some method to render all these pages in one go, and then somehow push them to my production Drupal installation.

A caveat, which would be more in the *nice to have* category is that it is possible for the XML feed to change. So, it'd be nice to, for instance, mark the changed text in a different color, or produce a new revision, or something along those lines.

I am using Drupal 6 (with no plans to upgrade).

---

I'll add an extra specific on this question. At present, I am using SimpleXML to walk through my feed, and using PHP to dynamically create an HTML tags I need. Essentially, I'm building up a string of HTML that gets returned from the module (in a \_module\_generate() function), which is then displayed by Drupal. If there is an easy way to take this, perhaps turn it into a Cron job, and have it produce some kind of output for the Feeds module (thanks @Clive), then that may be the easiest thing for me to do.

# Answer
> 0 votes
Method I ended up using:

* Procedurally create nodes on local environment, parsing XML feed with SimpleXML
* Hardlink to production server when crosslinking nodes
* Use Node Export to export/import nodes from local to production server
* Use pathauto on production to create node aliases

---
Tags: 7, nodes
---


# Question
Title: using profile2 login information as billing information in commerce
I have a site where people able to buy anything are already loged in. How do I collect from profile2 and apply this information in commerce billing automatically?

# Answer
You're better to use Commerce Customer Profiles for that information.

Although "billing" is the default, you can add other groups of profile fields as types, e.g "Profile information" etc...

There's a module commerce\_customer\_profile\_type\_ui that helps creating new profile types, else you can do it in code via the API.
> 1 votes

---
Tags: commerce, users
---


title: Linking to another website procedurally

text:
# Question
Title: Linking to another website procedurally
Hopefully this is a straightforward question.

I'm procedurally building nodes as I walk an XML feed, and am importing them into a production server. I'm having issues importing node aliases, so I thought I could simply create links to the nodes as they will be on production (pathauto will take care of auto-aliasing them).

When I fill the href attribute of my link, instead of pointing to my website it points to my local server (it seems to be auto-changing my link).

I'm building my link like this:

```
$link = 'http://example.com/content/' . $current_node['name'];
$name = $current_node['name'];

```

and then assigning in my string

```
$output = "<a href='" . $link . "'>" . $name . "</a>":

```

However, as I mentioned, it ends up pointing local instead of direct to my outside node.

# Answer
> 2 votes
If you're creating links, use `l()`.

```
$url = 'http://example.com/content/' . $current_node['name'];
$output = l($current_node['name'], $url, array('external' => TRUE));

```

---
Tags: nodes, 6, navigation
---


# Question
Title: How do I compile Mustache.php to use with the Template Field module?
The Template Field module requires the Mastache Template Rendering Library.

> The Mustache Template Rendering Library can be found here. It must be installed at libraries/mustache/Mustache.php.

However, the Mustache.php file is not provided, and I'm not sure why. There is some discussion about using the composure.php library to compile it. What I'm supposed to do?

The Template Field module is looking for a file called Mustache.php which doesn't exist in the git repo.

```
  /**
   * Verify anything before rendering
   * @param Template
   * @param array $data the data to render in the template
   * @return boolean
   */
  public function valid(Template $template, $data) {
    // Does the mustache library exist?
    if (file_exists(self::mustache_path())) {
      return TRUE;
    }

    watchdog('template_api', t('Mustache Library was not found'));
    return FALSE;
  }

  public static function mustache_path() {
    return libraries_get_path('mustache') . '/Mustache.php';
  }

```

There is a mention for using Composer but I'm not sure what that does. I have tried adding the Drush Composer extension to build a file but I don't understand how the Composer extension works.

# Answer
> 4 votes
1. Open command line.
2. cd to your basedir/sites/all/libraries
3. mkdir mustache && cd mustache
4. git clone https://github.com/bobthecow/mustache.php.git

You now have /sites/all/libraries/mustache/mustache.php .

Mustache.php is actually the name of the folder, not an individual php file.

To get an earlier version, such as 1.0, try

1. Open command line.
2. cd to your basedir/sites/all/libraries
3. mkdir mustache && cd mustache
4. wget https://github.com/bobthecow/mustache.php/archive/v1.0.0.tar.gz
5. tar -zxvf v1.0.0.tar.gz
6. mv mustache.php-1.0.0 mustache.php

# Answer
> 2 votes
The Template Field Module requires a previous version of Mustache.php -- v.1.0 instead of the newer v.2.0. The download page for previous version of mustache.php is at https://github.com/bobthecow/mustache.php/tags

---
Tags: theming, composer
---


# Question
Title: Fields from different content types in a single page
Using field permissions i have set 10 fields from various content types (articles, page, etc) to private.

While the rest of the fields is filled by the user, the publisher needs verify and fill those 10 fields to publish the content.

Is it possible to get all these fields in a single page so the publisher don't have to go to the individual content types to fill those fields.

# Answer
If you can't restructure your publishing flow as kiamlaluno said (preferred method!), then another option would be to write a custom module to programmatically retrieve the info from each field and display them for the publisher's review in a form, then store the publisher's revisions in each field. See these pages for more info, Drupal API and another SO thread
> 0 votes

# Answer
My first thought would be to rethink your publishing workflow.

Having that said, I would try to create a view which takes content from all content types. Instead of showing the content, show the appropriate fields and create a filter so only unpublished content is shown...
> 0 votes

---
Tags: users, nodes
---


title: Change title of a content type

text:
# Question
Title: Change title of a content type
I have a custom content type named 'product'. Every content of type product has a serial number of the product as the title. But while displaying the title I want to override it from two of the CCK fields of the product. Please take a look at this page.

I want to concatenate Manufacturer and Chip and display it as the title. I am a beginner in Drupal.

# Answer
For altering the saved title, try auto\_nodetitle module, it can do what you want there.

1. Download and install the module
2. Enable the module in Drupal
3. Edit the relevant content type settings ( `Admin > Structure > Content types` )
4. Set the `Automatic title generation` option, using field tokens for the field values

If you want to update the *display* only, then you can use a node.tpl.php template preprocess function

e.g in your theme `template.php` file, replace THEMENAME with your theme name.

```
function THEMENAME_preprocess_node(&$vars){
  $node &= $vars['node'];
  if ($node->type == 'product') {
    $text = $node->field_manufacturer[LANGUAGE_NONE][0]['value'] . ' ' . $node->field_chip[LANGUAGE_NONE][0]['value'];
    $vars['title'] = check_plain($text);
  }
}

```

Clear theme registry cache after adding a new preprocess function
> 1 votes

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


# Question
Title: Getting Drupal to work with Mercury Mail Server on Local Machine
I've successfully set up Mercury Mail Server on my local machine using the XAMPP stack to send mail through a remote SMTP Server by following the configuration directions posted at: https://www.zoe.vc/2008/mercury-mail-transport-system-fur-externe-mail-konfigurieren/ If mail is sent to either local or external email addresses via a regular mail client, e.g. Thunderbird, Mercury Mail processes the mail appropriately and the mail arrives in the expected mail boxes.

However, sending mail through my local Drupal 7 site does not work.

* For example, the site includes a set of rules built with the Rules module that are configured to send mail to a set of email address when triggered.
* Drupal reports that it successfully sends mail to the targeted addresses when the rules are fired.
* But Mercury Mail doesn't show any evidence that the mail is being processed -- and the mail never shows up in at the addressed mailboxes.

In summary, mail from Drupal is not getting to the server, but Drupal thinks that it has been successfully sent. Note, as per the directions from zoe.vc, the \[mail function\] configuration in php.ini is setup as:

```
[mail function]
; XAMPP: Comment out this if you want to work with an SMTP Server like Mercury
SMTP = localhost
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = postmaster@localhost.com

; XAMPP IMPORTANT NOTE (1): If XAMPP is installed in a base directory with spaces (e.g. c:\program filesC:\xampp) fakemail and mailtodisk do not work correctly.
; XAMPP IMPORTANT NOTE (2): In this case please copy the sendmail or mailtodisk folder in your root folder (e.g. C:\sendmail) and use this for sendmail_path.

; XAMPP: Comment out this if you want to work with fakemail for forwarding to your mailbox (sendmail.exe in the sendmail folder)
;sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"

; XAMPP: Comment out this if you want to work with mailToDisk, It writes all mails in the C:\xampp\mailoutput folder
sendmail_path = "C:\xampp\mailtodisk\mailtodisk.exe"

; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =

; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header = Off

; Log all mail() calls including the full path of the script, line #, to address and headers
;mail.log = "C:\xampp\php\logs\php_mail.log"

```

I've spent countless hours trying to figure this one out. Any help getting this to work via drupal so that I can continue development will be greatly appreciated. Thanks in advance.

# Answer
When I used to test sending mail from a localhost (I don't remember the mail server program though), I used to use the SMTP Authentication Support module for its configuration.

> This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.
> 2 votes

---
Tags: emails
---


# Question
Title: Block feed importer to create a new term in taxonomy
I am using feed importer to bulk import the nodes in a drupal site. I have created a custom content type named Product. This content type has CCK fields which are linked with a taxonomy.

I am using CSV files to import the data. If I put a different(invalid) value in one of the field and that is not present in the vocabulary(term in the taxonomy), it creates a new term.

I want to block the creation of the new taxonomy term as it might create some invalid term in my site.

# Answer
I achieved it using Feeds Tamper. We can control the fields that we want to import.
> 0 votes

---
Tags: taxonomy-terms, feeds, importing-exporting
---


# Question
Title: Using "access callback" and "access arguments" provided with hook_permission
how can I check user's access first based on some permission and if user passed this check then execute `access callback` function with some parameters in path, some thing like this:

```
$items['order/add/%node'] = array(
  'title' => 'Place new order',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('order_add_form', 2),
  'access callback' => 'order_add_access',
  'access arguments' => array('place order', 2),
  'type' => MENU_LOCAL_TASK,
  'file path' => drupal_get_path('module', 'order'),
  'file' => 'order.page.inc',
);

```

# Answer
Not sure exactly what you mean there but your code already has a custom access callback specified as well as access arguments?

You could have an access callback like this:

```
/**
 * Add order access callback
 */
function order_add_access($op, $node){

 switch ($op) {
   case 'place order':
   // Return true, if logged in user has administer nodes permission
   // and node status is published.
   if (user_access('administer nodes') && $node->status == 1) {
     return TRUE;
   }
   break;
 }
 return FALSE; // default

}

```
> 7 votes

# Answer
If the first item of the access arguments is the string for the permission the user should have to access the menu item, you could use the following code.

```
function order_add_access($permission, $node) {
  if (user_access($permission)) {
    // Check any node property, and return TRUE when the user should access the menu item.
  }

  return FALSE;
}

```
> 2 votes

---
Tags: routes
---


# Question
Title: How should a custom module install a reference data dictionary?
I'm about to write a custom module dealing with chemical hazards symbols. It's basically a 300-item dictionary of simple objects: a symbol, its description (around 100 chars) and in some cases a supplementary short information.

I'm still undecided whether I'd make my module a text filter, field or entity, but regardless (I think) of the way I choose, I'm clueless about what would be the Drupal way to install this simple dictionary, a PHP variable, a persistent variable, or a database table?

My guess would be that storing it as PHP variable would not burden the memory too much, it would provide quick lookup access, and would save database queries. Would there be any benefit to choose the table option?

What is limiting me in using taxonomy here is that some terms would have to be supplemented by a piece of information on a binding/instance level. For example, there would be a symbol (term) `P0123: Store in temperatures below %1 C/ %2 F` or `P2345: Wash %1 thoroughly after handling`. For each node referencing that term there should be a possibility to add the precise values that might be different per node. That is the reason I have been thinking of making it a text filter that would parse line:

```
P0123,10,50 (<- term with supplementary contextual values, %1 and %2)
P2345,en:hands|de:Hande|es:manos (<- i18n-savvy contextual string)
P3456 (<- term without additional info)

```

I have already filed a feature request for the Relation module, to provide labelling of relationships on instance level. We'll see if the authors consider it as worth implementing for a wider public. For now I'm trying to find a swift workaround.

# Answer
> 0 votes
If you were to use a PHP variable, you would need code that (for example) in `hook_init()` initializes that global variable, and that code would be executed at every page request.

If you were to use a persistent variable, you could initialize it during the installation of your custom module (via `variable_set()`). You would still have the problem of having the content of those Drupal variables loaded in memory every time Drupal bootstraps, which includes also the case Drupal is answering to an AJAX request. This should be avoided, especially if those data are necessary just on specific pages. Also, a module should generally limit the number of calls to `variable_set()`, since each calls clears the cache used to contain persistent variables, and it would cause any successive call to `variable_get()` to query the database again.

The only alternative you have is creating a database table when your custom module is installed.
With Drupal 7, that means to just implement hook\_schema(), and put that function in the .install file of your module. With Drupal 6, that means to implement `hook_schema()`, but also `hook_install()` with code similar to the following one.

```
function mymodule_install() {
  // Create tables.
  drupal_install_schema('mymodule');
}

```

You can use a custom cache table to store the serialized form of the data more frequently loaded from the database; this is what Drupal core normally does.
In the case the data is requested more than once in the same page request, you could also store data in a global static variable created with `drupal_static()`. Then, the code for handling the data would be similar to the following one.

```
function archiver_get_info() {
  $archiver_info = &drupal_static(__FUNCTION__, array());

  if (empty($archiver_info)) {
    $cache = cache_get('archiver_info');
    if ($cache === FALSE) {
      // Rebuild the cache and save it.
      $archiver_info = module_invoke_all('archiver_info');
      drupal_alter('archiver_info', $archiver_info);
      uasort($archiver_info, 'drupal_sort_weight');
      cache_set('archiver_info', $archiver_info);
    }
    else {
      $archiver_info = $cache->data;
    }
  }

  return $archiver_info;
}

```

The function first check if the static PHP variable has been initialized; if it is empty, then it looks for the data in the cache. Only in the case the cache is empty, invokes the module hooks to built its data.

# Answer
> 1 votes
In D7 I would make a Taxonomy out of such data. Just create a new taxonomy called `Chemical Dictionary`. Taxonomies already have:

* a title
* a description field

You just need to add a custom field for the image(s) using the Field UI. You could easily import these things from CSV or a remote database table using the Migrate module if your comfortable with code.

Taxonomy terms are stored in a database table by default in drupal, they are already entities.

While typically used for tagging things, you dont have to use it that way.

# Answer
> 0 votes
I would go with a database table. This would allow you to easily integrate it with the views module too. The hook you want to do it is hook\_schema. http://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook\_schema/7

---
Tags: installation
---


# Question
Title: How to pre-generate image styles after image is uploaded
Is there a quick way in Drupal 7 to generate image styles straight after the image is added to the image field?

# Answer
> 2 votes
You can look into Image Style Pregenerate module to generate images.

---
Tags: media
---


title: multiple login destinations

text:
# Question
Title: multiple login destinations
I need to send users to the user/me/edit page to change their password when they log in the first time and also in cases of password reset. The rest of the time they need to go to an internal dashboard page.

What is the best combination or single module to accomplish this? I've tried numerous combinations of login destination and login toboggan as well as each on it's own but can't get it right.

Both my register and login forms are on my homepage.

# Answer
> 1 votes
I think the first code snippet on this post is what you are looking for:

```
<?php

function mymodule_user($op,&$edit,&$account,$category = NULL){
    if($op == 'login'){
        if($account->login == 0){ // check the last login
        //do stuff here
        }
    }
}

?>

```

It uses hook\_user() to check the user's last login time. If it's 0, meaning she haven't logged in before, you can redirect the user with a function like drupal\_goto.

You'll have to create a simple custom module and place your code in mymodule.module file.

If you are not comfortable writing a module for this, you can try creating a rule with the Rules module, I haven't been able to test this approach, but here are the basics:

Create a new rule:

1. Event: 'User has logged in'
2. Condition: 'Data comparison' - check the data called 'site:current-user:last-login' or 'account:last-login' for last login information.
3. Action:'Page redirect'

# Answer
> 0 votes
To make users to change their password on first time login you can use Password policy module. Just download and enable this module and goto 'admin/config/people/password\_policy/password\_change' page to configure force password change options.

And for redirecting users of different role to different page you can use Login Destination module. Login destination settings can be configured from 'admin/config/people/login-destination' page.

# Answer
> 0 votes
This is the behavior I experienced:

* User would create account and would copy & paste link onto homepage they already had open. (it worked fine if they clicked on the link in the email but you have to address multiple login scenarios)
* Would log in and stay stuck on the homepage without any navigation

What I ended up doing:

1. downloaded user\_stats module and wrote the rule with truth value code:
return (user\_stats\_get\_stats('login\_count', $account-\>uid) == 1) ? ’1′ : ”; with redirect to user/me/edit
2. login destination module to redirect from user/me/edit to user/me/personal\_dashboard (internal page). I had to do this because as soon as the user saved the password, they would go to the homepage due to the fact that the link had a destination parameter -\> user/me/edit?destination=homepage I had to override.
3. in order to force re-direction to the user/me/personal\_dashboard on all subsequent logins, I wrote this rule with php code: If (\[account:user-last-login-raw\]) { return TRUE; } else { return FALSE; }

This works. I couldn't get login toboggan to route to the right place and login destination doesn't allow for more than one case.

Thank you to those above for their input. I read this too late to try the password policy module but I'll check it out.

---
Tags: 6, users
---


title: Creating a form using a path argument

text:
# Question
Title: Creating a form using a path argument
I'm writing a simple module to handle newsletter subscriptions and I want to create a form which is based on information passed in as a url argument.

Example path: /subscribe/verify/eiurhgiergierugskdfadsf

I'd like to create a form for /subscribe/verify which takes "eiurhgiergierugskdfadsf" as a parameter so that I can lookup the user by that hash value and then populate the form with their subscriber id and other information.

I can't seem to figure out how to get url arguments available in my form function though.

```
$items['subscribe/verify'] = array(
    'title' => 'Verify Email',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('subscribe_terms_form_verify'),
    'access arguments' => array('access content'),
);

function subscribe_terms_form_verify($unique_id) {
   ...
}

```

How do I safely get access to the url parameter in my form callback?

# Answer
You need to introduce the argument as a 'wildcard', and pass it through to your function in the `page arguments` like so:

```
$items['subscribe/verify/%'] = array(
  'title' => 'Verify Email',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('subscribe_terms_form_verify', 2),
  'access arguments' => array('access content'),
);

```

The `hook_menu()` docs are worth read, they explain wildcards in good detail.

Your form function will have this signature:

```
function subscribe_terms_form_verify($form, &$form_state, $unique_id) {

}

```

`$form` and `$form_state` are provided as parameters to your form through `drupal_get_form()`, so the 3rd argument will contain the information passed from the URL.
> 4 votes

---
Tags: 7, forms
---


title: Drupal does not recognize GD and PDO

text:
# Question
Title: Drupal does not recognize GD and PDO
sorry if this has been answered already, but my searches brought me to nowhere.

I have just installed LAMP environment on Amazon EC2 instance. It runs on:

```
Ubuntu precise 12.04 amd64 server
PHP Version 5.3.10-1ubuntu3.4
MySQL 5.5.28
Apache/2.2.22 (Ubuntu)
Drupal 7-18

```

Drupal installation tells me that I have not GD enabled and PDO extension are disabled. However, looking at phpinfo() I have :

```
GD Support  enabled
GD Version  2.0
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.4.8
T1Lib Support   enabled
GIF Read Support    enabled
GIF Create Support  enabled
JPEG Support    enabled
libJPEG Version unknown
PNG Support enabled
libPNG Version  1.2.46
WBMP Support    enabled

Directive   Local Value Master Value
gd.jpeg_ignore_warning  0   0

```

and

```
PDO

PDO support enabled
PDO drivers mysql

pdo_mysql

PDO Driver for MySQL    enabled
Client API version  5.5.28

Directive   Local Value Master Value
pdo_mysql.default_socket    /var/run/mysqld/mysqld.sock /var/run/mysqld/mysqld.sock

```

So, in theory everything must work, why does Drupal not recognize them? I haven't changed anything at all from the clean install of LAMP. May I be missing something then?

Thanks in advance, maxim

# Answer
Just to be sure the install is all good, try

```
sudo apt-get install --reinstall php5-gd php5-mysql

```

Also, make sure you don't have any odd php.ini file in your drupal root.
> 4 votes

---
Tags: installation
---


# Question
Title: Field is not removed from 'field_config_instance'
> **Possible Duplicate:**
> Clean Deleted Field from Database

Why the record about deleted field still exists in 'field\_config\_instance' only status 'deleted' = 1 ? But from 'field\_config' records about field removed completely.

```
function mymodule_uninstall() {

  field_attach_delete_bundle('spproduct' , 'spproduct' );
  field_delete_field('field_spproduct_image');
  field_purge_batch(10);
}

```

I wont to remove field from all entity types wherevere it is used and from tables.

# Answer
> 0 votes
If you've got a fair amount of data, you'll need to allow cron to run a few times, or else do a larger batch purge

field\_purge\_batch(10)

Will only delete 10 records.

> $batch\_size: The maximum number of field data records to purge before returning.

---
Tags: entities
---