title: Multi Country and Language Site

text:
# Question
Title: Multi Country and Language Site
I'm trying to build a single global website that houses multiple countries, each with their own set of language translations. There is also a global overview site that also has its own language options. The global site will live on global.domain.com and function the same as a country site, and the countries will be at domain.com/langcode-countrycode/ (domain.com/en-us/). From anywhere on any site, the user will have a menu to navigate to another country/language. There will only be a dozen countries or so. There will also be company sites, but they are identical to the country sites. Each country/company will have its own management team that should only be able to edit their section. Each also needs the option to swap the logo and maybe some colors, but that's it.

From what I've found, Domain Access and Organic Groups, coupled with i18n, seems like the best option, but I just can't seem to get it set up in the right way. Is there a better approach to that?

Some countries want to be able to use another domain to access their country site, which I'm guessing would just be an alias to the main domain in Domain Access.

I can mostly picture how I would build this in WordPress, or even from scratch, but I'm new to Drupal, so I might be missing something obvious...

# Answer
> 1 votes
It sounds to me like you need a multi-site Drupal installation and each of those sites needs something like organic groups and also i18n.

Unless I am misunderstanding... what you're describing only makes sense if all the content across all sites is the exact same, just translated versions.

---
Tags: i18n-l10n, multi-sites
---


# Question
Title: field_image_cache missing from all content types
I've had a strange thing happen to a Drupal 6 site. All images are missing from the site. Looking at the Edit screen for a node shows that the ability to edit and upload an image for any node is missing.

Further checking the content types shows that under 'Manage Field' the 'Image' field \[field\_image\_cache\] has be removed for every content type.

As far as i can see all the correct modules are still enabled.

Anyone got any ideas?

# Answer
Just thought I would update this one, just in case anyone else has a similar problem.

Turns out that the database was erroring and running out of disk space. Which meant the queries couldn't be completed. This ended up corrupting the database and I had to restore from a backup.

Once the restore completed all images and ability to Edit them returned to the site.

Hope that helps.
> 0 votes

---
Tags: 6, entities
---


# Question
Title: How to disable Google fonts and other things like that?
How do I configure my theme or Drupal itself from fetching data such as Google fonts or anything like that? Also some JS files that get transferred as well.

# Answer
> 1 votes
Ex: if the theme is called "cooltheme"

You need to go to drupal/sites/all/themes/cooltheme

and edit the **cooltheme.info** file

you should see something like this inside:

`scripts[] = js/main.js` \<-- so just delete this so it won't load it.

Then go to drupal/sites/all/themes/cooltheme/js and delete the .js file from here too.

For the fetching data from google fonts, they might be inside the .css file of the theme.

---
Tags: theming
---


# Question
Title: How to convert Content Type Title into Term reference?
I would like to make a content type node title into a Term of reference. The titles need to be limited by some taxonomies.

How to convert Content Type Title into Term reference?

# Answer
Title Field UI might work for you. I haven't used this module, but apprently it allows you to modify title fields. Not sure if it will allow you the change the type from text to term reference. Although, you can always disable titles and use another term ref field as your title.
> 1 votes

---
Tags: nodes, taxonomy-terms
---


title: Check if a taxonomy term synonym exists

text:
# Question
Title: Check if a taxonomy term synonym exists
I have a $category variable containing country names separated by comma. So I use the following code to save them as taxonomy terms:

```
$tids = array(); $ctids = array();
$category = explode(',',$category);
foreach($category as $cat) {
  insert_term_if_not_exists($cat, 'countries');
  $term_country = taxonomy_get_term_by_name($cat);
  $tid_country = key($term_country);
  $lang_country = field_language('node', $node, 'field_country');
  array_push($ctids, $tid_country);
}
foreach ($ctids as $index => $ctid) {
 $node->field_country[$lang_country][$index]['tid'] = $ctid;
}

```

As you see the above code uses the `insert_term_if_not_exists()` function which works perfectly well to check if a taxonomy term exists and to create it programmatically if it doesn't:

```
function insert_term_if_not_exists($term_name, $vocabulary_name) {
   $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
   $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);
  if(empty($matched_terms)) {
    $term = new stdClass();
    $term->vid = $vocabulary->vid;
    $term->name = $term_name;
    taxonomy_term_save($term);
  } else {
    $term = array_shift($matched_terms);
  }
return $term;
}

```

However, I also need to check and avoid creating a new taxonomy term if it is a synonym of already existing another taxonomy term. So I modified the above code in the following way:

```
function insert_term_if_not_exists($term_name, $vocabulary_name) {
   $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
   $matched_terms = taxonomy_get_term_by_name($term_name, $vocabulary->machine_name);

    if(empty($matched_terms)) {
      $matched_synonym = synonyms_get_term_by_synonym($term_name, $vocabulary);
      if (empty($matched_synonym)) {
        $term = new stdClass();
        $term->vid = $vocabulary->vid;
        $term->name = $term_name;
        taxonomy_term_save($term);
      } else {
        /*
        * Here I need to do something, but don't know what exactly. Using
        * $term = taxonomy_term_load($matched_synonym);
        * here doesn't work.
        */
        }
    } else {
        $term = array_shift($matched_terms);
    }
  return $term;
}

```

Having troubles to make it work properly.

# Answer
> 0 votes
Edited my answer since my original answer referred to dev code.

The following simple module works with Drupal 7.34 and the current stable version of synonyms (7.x-1.2) and successfully matches a synonym to a taxonomy term.

synonyms\_test.module:

```
function synonyms_test_menu() {
  $menu['test-synonyms'] = array(
    'page callback' => 'synonyms_test_page',
    'access callback' => TRUE,
  );

  return $menu;
}

function synonyms_test_page() {
  $vocabulary_name = 'tags';
  $output = '<p>Assuming you have a taxonomy with machine name "tags" and that '
            . 'taxonomy has a term named "first term" and that term has a '
            . 'synonym "syn one", this test will produce these results:</p>';
  $test_terms = array('first term', 'bogus term', 'syn one');
  $vocabulary = taxonomy_vocabulary_machine_name_load($vocabulary_name);
  foreach($test_terms as $test_term) {
    $output .= 'Testing "' . $test_term . '"<br>';
    $matched_terms = taxonomy_get_term_by_name($test_term, $vocabulary->machine_name);
    if(empty($matched_terms)) {
      $output .= 'Not an existing taxonomy term.';
    } else {
      $output .= 'Is an existing taxonomy term.';
    }
    $output .= '<br><br>';
    $matched_synonym = synonyms_get_term_by_synonym($test_term, $vocabulary);
    if(empty($matched_synonym)) {
      $output .= 'Not an existing synonym.';
    }
    else {
      $output .= 'Is an existing synonym, for tid ' . $matched_synonym;
    }
    $output .= '<br>=========<br><br>';
  }
  return $output;
}

```

*** Original answer below ***

This is the function you're looking for (from synonyms.module):

```
/**
 * Returns the term objects that have the given string as a synonym.
 *
 * @param $synonym
 *  A string containing the synonym to search for.
 * @param $vocabulary
 *  (optional) The machine name of the vocabulary in which to search for.

 * @return
 *  An array of term objects containing that synonym.
 */
function synonyms_root_terms_get($synonym, $vocabulary = NULL) {
  $tids = synonyms_root_tids_get($synonym, $vocabulary);

  return taxonomy_term_load_multiple($tids);
}

```

So if your $matched\_terms is empty, try something like:

```
$matched_synonyms = synonyms_root_terms_get($term_name, $vocabulary->machine_name);
if(empty($matched_synonyms)) {
  // ...now create your new term
}
else {
  $term = array_shift($matched_synonyms);
}

```

---
Tags: taxonomy-terms
---


title: Backup and Migrate gives me a tar ball

text:
# Question
Title: Backup and Migrate gives me a tar ball
I have a local site and a development site. I want to replace my development site with my local site. I used the Backup and Migrate module to backup the development site into a `.gz` file. All good. But when I did the same again with the local environment, it came back as a `.tar` file, no matter which compression option I chose.

When I tried to restore onto the development site using the local site's tarball, it specified it needs a `.gz` or `.zip` file. So I ran:

> tar -cvzf 127.0.1.1-2015-01-12T17-23-50.sitearchive.tar.gz 127.0.1.1-2015-01-12T17-23-50.sitearchive.tar

This time, it came back with this error:

> Unable to restore from file /tmp/backup\_migrate\_vbDBRs.0.1.1-2015-01-12t17-23-50.sitearchive.tar because a tar file can't be restored to this database.

How can I correctly restore a backup from my local site onto the development site. Or is this method completely wrong and I should be doing something else, like creating a new site from scratch and restoring that?

# Answer
This is not an issue with the module.

The most likely cause of the problem is that your local system is missing gzip, so the backup and migrate module is unable to turn the tar-file into a gzipped tar file.

The command to do that is not `tar -cvzf` (which you've tried), but `gzip`. I.e.:

```
gzip 127.0.1.1-2015-01-12T17-23-50.sitearchive.tar

```

This should produce a valid `127.0.1.1-2015-01-12T17-23-50.sitearchive.tar.gz`, but if you try this on the local system, it will probably fail telling you that it can't locate *gzip*.

The best fix would be to install *gzip* on the local system.

Alternatively, you may export the file to some system that has *gzip*, and do the gizipping there.
> 1 votes

---
Tags: 7, migrations, backups
---


# Question
Title: Drupal 7 rewrite is removing get parameters from query string
I've recently upgraded a site to the latest release of Drupal 7. The site has a view that retrieves a url with query string parameters from the database and then uses the Drupal rewrite functionality to add a class to the link like so: `<a class="purple-button pull-right" href="[field_database_link-url]" target="_blank">View</a>`

The issue is, since the upgrade the rewrite now removes the query string parameters. If I modify the view to display a simple link the parameters are there and it works fine. However, the rewrite applies styling to present a button rather than a simple link. I can't find any settings to resolve the issue so I suspect the upgrade overwrote a modification to the Drupal core made by the original developer of the site. Any idea how I can address this issue?

# Answer
> 1 votes
It turns out that there was a bug in the latest release that in /modules/contrib/link/link.module that was causing the query strings to be stripped from the URL in the token. I replaced the code in this file with the code from the pre-upgrade version and it began behaving as expected again. This, of course, is not a resolution to the issue, but at least the source of the problem has been identified. For more info, see the original bug report.

I later found that there is a patch for this issue in the dev version (7.x-1.x-dev) of this module. Download this module and replace it in your install and you should be all set.

# Answer
> 0 votes
oh ugh that is UGLY. I wish everyone would know **DO *NOT* MODIFY** core files!

Unless you have a backup you are pretty much dead in the water. Well you can recreate functionality but that's annoying if it was working. If you don't have a backup use this experience as a boot to get you backing up properly - take weekly database backups (or daily or monthly depending on site change rate) and a full database and code backup before upgrading. I would suggest the Backup/Migrate module to make that easy and mostly automated.

If you do have a backup do a diff between the version it was and the backup to find what files were changed and then get those changes out and into a module if possible.

---
Tags: views
---


title: Creating a View with Distinct Results

text:
# Question
Title: Creating a View with Distinct Results
I've created a view called 'Browse'. I've set the 'Query Settings' to show only DISTINCT (but it doesn't work).

**Background:** I have a 'Resource' content type with a field list field called 'type'. Types may include 'blog', 'book', 'web article', etc. (there are only 8 types). I have about 80 resources in this content type, each with a 'type'.

When I create my view with DISTINCT set and content type=resource and 'type' as the only field it displays about 15 instances of each type, so it ends up looking something like this:

```
Blog
Blog
Blog
...
Book
Book
Book
Book
...
Web Article
Web Article
etc.

```

I only want each 'type' to display once and link to the views I've already setup that show all the resource content types with that particular type set (ie. if a user clicks 'blog', which should only appear once, it takes them to a page view listing all the blogs in the db.

Does anyone know how to ensure my View shows only distinct values for items in this field\_list?

# Answer
> 2 votes
It does not work because the rows are all unique to start of with. Switch on SQL preview in views settings, and you will see that it adds the node's nid to the result in the SQL. Now add nid to the fields, and you will see something like

```
Book, nid:5
Book, nid:7

```

`Book, nid:5` is not equal to `Book, nid:7`. For distinct to work, whole rows need to be equal.

What you need is aggregation.

To do that, switch on aggregation for the view in the advanced pane. Then set aggregation to COUNT on the nid.

Now your result will look something like this:

```
Blog, nid:6 // ie 6 rows with field value blog
Book, nid:2 // ie 2 rows with field value book

```

Then, finally, to get the output you want, just hide the nid from the views display.

In essence, what you have done is to group by the field 'type', and to count how many nids (rows) there are in each group. And then hide the count as you don't need to display it.

---
Tags: 7, views
---


# Question
Title: How to make submit button work in form themes
I am trying to create a form which calls an external template file to format the form but ended up into a typical issue. This is what I was doing. I created a hook menu and called a theme, in the theme declared the template, and in template called the form elements and rendered along with html code. Everything is working fine except the submit button. If I render form directly, submit is working, or if I use drupal\_get\_form in menu page callback, it works (again template is not getting applied). I'm confused what am I doing wrong. I am a newbie so excuse me if this is a repetitive or stupid question.

Here is my code. My module file named agents.module

```
<?php
function agents_menu(){
  $items=array();

  $items['myform']=array(
    'title'=>'Form',
    'description'=>'Submit Form into database',
    'page callback'=>'agents_form',
    'access callback'=>TRUE,
    'access arguments'=>array('access content'),
    'type'=>MENU_CALLBACK,
  );

  return $items;
}

function agents_form(){
  return theme('students');
}

function agents_theme(){
  return array(
    'students' => array(
        'render element' => 'form',
        'template' => 'customTemplate',
    ),
  );
}

function students_form($form, &$form_state){
  $form = array();
  $form['efname'] = array(
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#size' => 28,
    '#maxlength' => 10,
    '#required' => TRUE,
  );

  $form['elname'] = array(
    '#type' => 'textfield',
    '#title' => 'Last Name',
    '#size' => 28,
    '#maxlength' => 10,
    '#required' => TRUE,
  );
  $form['submit_btn'] = array(
    '#type'=>'submit',
    '#value'=>'Submit',
    '#submit' => 'agents_myForm_submit'
  );
  return $form;
}

function students_form_validate($form, &$form_state){
  dpm($form_state['ename']);
}

function students_form_submit(){
  dpm('into submit');
}

```

and my customTemplate.tpl.php code looks like this

```
<?php
  dpm(drupal_get_form('students_form'));
  $form = drupal_get_form('students_form');
?>
<div class="left_div">
  <?php print render($form['efname']); ?>
  <?php print render($form['elname']); ?>
</div>
<div class="right_div">
  <?php print render($form['submit_btn']); ?>
</div>
<?php
  dpm(render($form['form_build_id']));
  print render($form['form_build_id']);
  print render($form['form_token']);
  print render($form['form_id']);
?>
<?php print drupal_render_children($form);

```

I am a newbie to drupal, and I was not able to figure out what am I doing wrong. If I directly render the form without rendering submit individually, (i.e. print render($form) ) it works fine. It would be a great savior of the day if someone helps me cross this hurdle.

# Answer
You don't want to run your drupal\_get\_form from inside your template, you want to render it from your page callback. You'll instead declare the theme for your form with `$form['#theme'] = 'students'` in order to use your template.

```
function agents_form() {
  $form = drupal_get_form('students_form');
  return render($form);
}

function students_form($form, &$form_state){
  $form = array();
  $form['efname'] = array(
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#size' => 28,
    '#maxlength' => 10,
    '#required' => TRUE,
  );

  $form['elname'] = array(
    '#type' => 'textfield',
    '#title' => 'Last Name',
    '#size' => 28,
    '#maxlength' => 10,
    '#required' => TRUE,
  );
  $form['submit_btn'] = array(
    '#type'=>'submit',
    '#value'=>'Submit',
  );

  $form['#theme'] = 'students';

  return $form;
}

```

You also had a '#submit' attribute on your submit button element but it would need to be set as an array rather than a string `'#submit' => array('agents_myForm_submit'),` However I didn't see that submit function defined so I removed it.

Then your customTemplate.tpl.php can be as simple as:

```
<div class="left_div">
  <?php print render($form['efname']); ?>
  <?php print render($form['elname']); ?>
</div>
<div class="right_div">
  <?php print render($form['submit_btn']); ?>
</div>
<?php print drupal_render_children($form); ?>

```
> 0 votes

# Answer
Your page callback should reference the $form building function directly. In that case that means changing

```
'page callback'=>'agents_form',

```

to

```
'page callback'=>'students_form',

```

Don't worry about wrapping it in a `theme()` function, it is unnecessary.

Note that the key you use in `$items[KEY]` determines the path of the form. So once you make the first change suggested here, you should be able to view the form at `http://yoursite.com/myform`
> 0 votes

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


# Question
Title: How to create dependent exposed filters in a view
I have three drop-down boxes just like ex:

```
1. class list (ClassI, ClassII...)
2. subject list (Hindi, English...)
3. chapter list (H-ChapterI, H-ChapterII, E-ChapterI, E-ChapterII...)

```

When a user clicks on class list drop-down, there will be two option (ClassI, ClassII and so on...). When I select ClassI in a subject list (Hindi, English and so on...) will become as same. When I select on Hindi in chapter list related to Hindi (HChapterI, HChapterII) all chapter will come. This is what I want in my view filter.

# Answer
> 1 votes
I think you should use Simple Hierarchical Select, this also works with views and exposed filters out of the box.

---
Tags: views
---


title: drupal.js is loading before jquery.js

text:
# Question
Title: drupal.js is loading before jquery.js
I have face this problem often in my drupal site. The `drupal.js` file is loading before `jquery.js`, so i get the "uncaught jQuery is not defined" error.

I have been using memcached also in my site.

But I can fix the error by the following steps

1. Restart memcached
2. Restart Apache
3. Cache clear
4. Run the cron

After doing the steps the jQuery is loading properly.

Now, i want to know the reason why the `drupal.js` loading before `jquery.js`?

**FYI : This is happening, When I enable/disable any modules/features through UI**

# Answer
May be because of cache that might cause

1. Check if you installed `jquery_update` module
2. in themes info check if there you have declared jquery

3.check if in any module **`hook_init`**() you are adding your js with weight.

if you install jquery update module you dont need to add jquery plugin in info file

if you have any clarification regarding the js weight and so on read the following links will be helpful

https://www.drupal.org/node/756722

https://www.drupal.org/node/304255
> 2 votes

# Answer
Use `hook_js_alter` see the below example code.

```
function MODULENAME_js_alter(&$js) {
drupal_add_js('mise/drupal.js', 'external');
drupal_add_js('mise/jquery.js', 'external');
}

```
> 1 votes

# Answer
Thanks @Clive, you comment help more to find out the issue.

In my case, we have used the drupal\_add\_js outside of the functions/hooks without any conditions as the following code,

```
<?php

// Adds the custom css file into the module.
$module_path = drupal_get_path('module', 'kf_book_quiz');
drupal_add_js($module_path . '/kf_book_quiz.js');
drupal_add_css($module_path . '/kf_book_quiz.css');
drupal_add_css($module_path . '/kf_book_quiz_rwd.css');
module_load_include('inc','quiz','quiz.admin');

/**
 * Implements hook_init()
 */
function kf_book_quiz_init() {

}

```

It is not a proper way to add the js into module. This would break the js queue structure. We should add js only where it is needed, we could use hook\_preprocess\_page to add js for needed place with conditions.
> 1 votes

---
Tags: javascript
---


# Question
Title: How can I display existing node content in its node form?
I have several fields that need to be translated and it would be best if the translator sees the **to-be-translated** content right **beside** the **translation field**.

In a standard node form, it shows that field as an input text area field for updating purposes but I don't want the translator to touch that or be able to mess with that.

I want the translator to 'see' the rendered display of that "**to-be-translated**" field next, under or above the text area field for the translation on the node form. How to do that?

I'm not very strong in php so if you give advise with php, please be thorough. Thanks in advance!

# Answer
> 0 votes
One way that I recently found was by using panels where you can actually place different components in different places. These components would then be either the rendered to-be-translated field beside the translation field. So you could say that this is a solution but I'm not very sure if this is going to require me to do this for each and every role differently or if panels could only be used to kick in only when a specific condition is met i.e. user has 'translator' role.

---
Tags: i18n-l10n, nodes
---


title: Using theme_image_style()

text:
# Question
Title: Using theme_image_style()
I am trying to display thumbnails of uploaded images in a custom form. While I can see the images in my form array after uploading them to the tmp directory in Drupal, here is what I am trying to use to display them:

```
$url = file_create_url($form_object->uploads[$key]->uri);
$output .= '<div class="grid-3">'.theme_image_style(array('style' => 'form-preview', 'path' => $url)).'</div>';

```

While `$url` points to the file resource, I cannot show a resized image for the life of me. If I use an img tag and put `$url` as its source, the images do show up, but they are huge.

Can I not call `theme_image_style()` because these are just temp images and not permanent? I can make them appear with `theme_image()`.

# Answer
As suggested, use theme('image\_style', ...), from the docs - just change your code to this:

```
url = file_create_url($form_object->uploads[$key]->uri);
$output .= '<div class="grid-3">'.theme('image_style', array('style_name' => 'form-preview', 'path' => $url)).'</div>';

```
> 5 votes

# Answer
As always, the Drupal documentation has the answer. You need to move the file to the files directory. Also you should **never** call a theme function directly but instead call the wrapper `theme` function so:

```
theme_image_style(...) // Don't do this ever

theme('image_style', ...) // Do it like this and make themers happy.

```

From the API docs:

> $variables An associative array containing:
>
> * style\_name: The name of the style to be used to alter the original image.
> * path: The path of the image file relative to the Drupal files directory. **This function does not work with images outside the files directory nor with remotely hosted images**.
> * alt: The alternative text for text-based browsers.
> * title: The title text is displayed when the image is hovered in some popular browsers.
> * attributes: Associative array of attributes to be placed in the img tag.
> 10 votes

# Answer
is better add your class with `attributes` property something like

```
theme_image_style(array('style' => 'form-preview', 'path' => $url,'attributes'=>array('class'=>array('class1', 'class2')));

```
> 1 votes

# Answer
I had to resolve this for serving files from sites/all/modules and the answer can be seen in Theme Image Style for image located in module directory

Involves generating a custom theme callback that handles any file and creates the image derivatives during execution of the page request, so you link directly to the file rather than doing an async request that creates the image.

Better suggestions / workarounds welcome!
> 0 votes

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


# Question
Title: Difference between 2 methods of adding a CSS files in theme.info?
What is the different between these 2 methods of loading a CSS files?

```
; Method 1
css[typography.css][name] = Typography
css[typography.css][description] = Typography
css[typography.css][options][weight] = 99

; Method 2
stylesheets[all][] = css/typography.css

```

Method 1 means the CSS file is loaded further down the page head, which I need for my theme. However from looking at the documentation it seems Method 2 is more standard?

# Answer
> 2 votes
Method 2 is provided by core (probably why it seems more standard, it'll be used more often).

Method 1 is something specifically provided by the Omega theme.

I think the only reason to use Method 1 is if you want to be able to control the use of the stylesheet through the optional stylesheets setting in the UI.

---
Tags: theming
---


# Question
Title: Remove the language prefix from the file URL
We have a multilingual site on Drupal 6. which seems to work fine, we created a rotor view on the default language (en). This views looks great on default language which loads without any language prefix on url.

But when we switch to any other language (example fr) the views images doesn't load because the file path it queries for is prefixed with language code. I have tried the same on drupal 7 it works outof the box. But not sure if we can do this in drupal 6. I have tried couple of module like pathologic, redirect module but doesn't seem to help in my case.

```
File path for default language: example.com/sites/all/files/test.jpg

File path for other language:  example.com/fr/sites/all/files/test.jpg  [which doesn't exists on server]

```

# Answer
> 0 votes
I have fixed this issue now, since the site was on **nginx**, I have written the redirect rule which removes language prefix while fetching files.

Insert this line in your server configuration:

```
rewrite ^/fr(/.*)$ $1 last;

```

If your site is on **Apache** you can add redirect rule on your server configuration or on `.htaccess` file.

```
RewriteEngine on
RewriteRule ^fr/(.*)$ $1

```

---
Tags: views, 6, files, i18n-l10n
---


# Question
Title: overriding submit functions with content types
I have created some content types, some are created programmatically, others (including the one I am interested in are where created using the front end GUI.

And this is where my issue starts, I would like to format some of the text that is returned on the form submit.

And to be honest i am unsure how to do this.

in this example I have created a custom content type called 'show\_date'

I would think that when the subnit function is caled I can pass the data to a custom fucntion, I would imagine this to being called show\_date\_submit thus:

```
function show_date_submit(&$form, &$form_state)
{
    /*
     my custom code would go here
    */

}

```

Is this right? any help given is as always appreciated and given Thanks for.

Al the best,

Jim

# Answer
> 1 votes
One way to do it is by using hook\_form\_alter, we can able to define a custom submit handler.

Find the form\_id of that form and define a custom submit handler.

```
hook_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'custom_add_user_form'){
        $form['actions']['submit']['#submit'][] = 'show_date_submit_handler';
        //for submit $form['actions']['submit']
        //for preview $form['actions']['preview']
    }
}

function show_date_submit_handler(&$form, &$form_state){
    // manipulate the form submitted values over here
   }

```

---
Tags: nodes, forms
---


title: Using Boolean Module as filter in Views

text:
# Question
Title: Using Boolean Module as filter in Views
We are trying to use Boolean module inside Drupal 7 to define a boolean field for a custom content type , `news` .

the module seems to be enabled without any visible issues . the issue comes when we wish to use that boolean field's data for Filtering in a view.

e.g The boolean field is called `editor-choice` , in the View we wish to get all `news` content type that is published and has Editor's choice value to true. please see below screenshots of the three steps being performed.

kindly assist what can be the possible issue, or if possible, suggest some other plugin that may be used foe this purpose.

# Answer
> 1 votes
If you are using Drupal latest version, boolean field is available by default in core.

Goto your content type =\> Manage field =\> Add new field =\> Select field type

In the manage field configuration, give 'on' value and 'off' value. Here I have given, Yes and No.

In the views filter, select the option you wish to filter. Thats it.

---
Tags: 7, views
---


# Question
Title: Use CAPTCHA module on a custom HTML form? (no use of Drupal Form API)
Is it possible to use the CAPTCHA module on a custom HTML form created in a content page of a Drupal 7 site? I am not using the Drupal Form API or webform modules. The form has the following code:

```
<form id="signup_form" action="[form action]" method="post" enctype="application/x-www-form-urlencoded">
<div>
<input id="firstName" tabindex="1" type="text" name="firstName" placeholder="First Name" value="" required />
<label for="firstName">First Name* </label>
</div>

<div>
<input id="lastName" tabindex="2" type="text" name="lastName" placeholder="Last Name" value="" required />
<label for="lastName">Last Name* </label>
</div>

<div>
<input id="email" tabindex="3" type="text" name="email" placeholder="Email" />
<label for="email">Email* </label>
</div>

<input type="hidden" name="form_id" value="signup_form" />
<div>
<input id="btn-submit" tabindex="6" class="submit" type="submit" name="submitButton" value="SIGN UP" />
</div>
</form>

```

I'm trying to have reCAPTCHA displayed at the bottom of the page when there has been an X number of form submissions from the same IP address in a given amount of time. I was hoping CAPTCHA After could work for my custom form -- I tested it on our site's Admin Login page (/user) and it worked great, of course.

I can't seem to get any CAPTCHA displaying on my custom HTML form page. In the General Settings, I selected "Add CAPTCHA administration links to forms" and a drop-down with "CAPTCHA: CHALLENGE "RECAPTCHA" ENABLED" displayed in the content page where the form is coded.

Since the HTML id has nothing to do with $form\_id... I referenced this Drupal Stack Exchange page, and haven't been able to generate the form ID...I'm wondering maybe my custom HTML form doesn't have a $form\_id because it doesn't use any drupal form modules? If that's the case, then I probably can't use the CAPTCHA module. Could someone please confirm?

Perhaps I can't use any Drupal modules and may need to:

1. grab the user's IP address from the header via PHP:

$ip\_address = $\_SERVER\["REMOTE\_ADDR"\];
2. store this IP address in some sort of database and add a timestamp
3. delete any IP address entities in that are over an hour old
4. count the number of data store entities via loop and if the same IP address appears a certain # of times in a given amount of time, then display reCAPTCHA

Any guidance would be great. Thank you!

# Answer
> 2 votes
> I'm wondering maybe my custom HTML form doesn't have a $form\_id because it doesn't use any drupal form modules? If that's the case, then I probably can't use the CAPTCHA module. Could someone please confirm?

Correct - the Captcha module has been written exclusively for integration with forms built by the core form API. Without a lot of changes, it's not possible to use any of its functionality on a form that hasn't been built by Drupal.

# Answer
> 0 votes
Your form id is **signup\_form** have you tried putting that in the captcha configuration so that it knows to add the captcha your custom form.

---
Tags: webforms, forms, captcha
---


title: Disabling the form field on submit

text:
# Question
Title: Disabling the form field on submit
I have a webform where I've used form alter to do some functionality and validation.

Now in my validation I want to disable a field for a purpose. How can I do so? Is it possible in form validation?

# Answer
I think what are looking for is hook\_node\_validate()

> Perform node validation before a node is created or updated.
>
> This hook is invoked from node\_validate(), after a user has has finished editing the node and is previewing or submitting it. It is invoked at the end of all the standard validation steps, and after the type-specific hook\_validate() is invoked.
> 0 votes

---
Tags: webforms
---


# Question
Title: Moving the a view Contextual Filter default value("PHP Code") to a module code
I am really wondered to know how I can move my designed view's Contextual Filter **default value** which is being provided by my written code as **PHP Code**, to a module code or a hook.

Is there any possibilities?

Moreover, I am not really interested in exporting view and putting it inside some hooks and ... (as it's again using eval for that **PHP Code**). I really like to move the Contextual Filter **default value** which is being provided by my written code as **PHP Code**, to a module code or a hook.

Even if you can provide me a way to access&manipulate the designed view inside the Drupal, by a module hook/code, it can be really helpful for me.

# Answer
This tutorial shows goes through exactly what you're wanting to do http://www.undpaul.de/en/blog/2013/04/04/contextual-content-flag-module-and-custom-views-default-argument-handler

You're definitely going to want to look at the module code in its entirety on his github linked in the article because in the blog post he left out some crucial code (like how to define the `views_argument_default_flag` handler as class that extends from `views_plugin_argument_default`.

In my own experience, I needed a custom argument validator instead of a default argument handler, so I followed this tutorial http://www.joetsuihk.com/en/en/custom\_views\_argument\_validator\_views\_plugin\_argument\_validate and came up with the following working result.

The need for this custom argument validator arose from needing nested or hierarchical taxonomy term names in the URL instead of the taxonomy term IDs, like `/parent-category/child-category/grandchild-category`. I tried to use the contextual filter validation method of converting the term name in the URL into its corresponding term id and replace spaces with dashes, but my category names have special characters like `/`, `&`, `+`, and `-`, which meant decoding the URL didn't always match the original term name.

So, the following custom views contextual filter (argument) validator correctly parses the term name out of the URL and figures out the corresponding term id by querying the `url_alias` table. After querying a particular path once, the result is cached for better performance. To get these hierarchical paths stored in the `url_alias` table, I set up a pathauto pattern for my taxonomy vocabulary, like `store/[term:parents:join-path]/[term:name]`

**The info file:**

```
name = Example Module
package = "Example"
description = Example Module custom views argument validator
core = 7.x

files[] = plugins/example_module_plugin_argument_validate_url.inc

```

**The module:**

```
/**
 * @file example_module/example_module.module
 * Implement hook_views_api - load up the custom views include files
 */
function example_module_views_api() {
  return array(
    'api' => 3.0,
    'path' => drupal_get_path('module', 'example_module'),
  );
}

```

**The views include file:**

```
/**
 * @file example_module/example_module.views.inc
 * Defines a custom contextual filter validator
 */
function example_module_views_plugins() {
  return array(
    'argument validator' => array(
      'taxonomy_url_alias' => array(
        'title' => t('Taxonomy URL Alias'),
        'handler' => 'example_module_plugin_argument_validate_url',
        'path' => drupal_get_path('module', 'example_module') . '/plugins',
      ),
    ),
  );
}

```

**The contextual filter handler:**

```
/**
 * @file example_module/plugins/example_module_plugin_argument_validate_url.inc
 * Contains the taxonomy url alias contextual filter validation plugin.
 */

/**
 * Validate whether an argument (contextual filter) is a valid
 * @ingroup views_argument_validate_plugins
 */
class example_module_plugin_argument_validate_url extends views_plugin_argument_validate {

  private $intAddUnixTime = 604800;
  private $error = FALSE;

  function validate_argument($argument) {
    $view = &$this->view;
    $handler = &$this->argument;

    if (!empty($view->args)) {
      //reconstruct the url from the views argument array
      $strPath = implode("/", $view->args);

      //get the taxonomy term id based on the url, not the term name
      $objAlias = $this->getTermId($strPath);

      //split the url_alias's source column up into an array.
      //the source column contains the term id at the end of a path like 'taxonomy/term/123'.
      $arrTermData = explode("/", $objAlias->source);
      $tid = end($arrTermData);
      $term = taxonomy_term_load($tid);

      //manually assign the term id to be the view's argument
      $handler->argument = $term->tid;
      return true;
    }
    else {
      return false;
    }
  }

  /**
   * Get the taxonomy term id from either the url_alias table or from persistent cache
   * @param string $strPath like 'parent-category/child-category/grandchild-category'
   * @return object containing the result of the url_alias table or persistent cache lookup
   */
  private function getTermId($strPath) {
    $objReturn = NULL;
    //attempt to get the taxonomy term id from cached url_alias table result object
    $objReturn = $this->getCache($strPath);

    //if cache is not set, do a select query
    if ($objReturn == NULL) {
      try {
        if(!$this->error) {
          $objReturn = $this->_dbSelect($strPath);
          //cache the response
          $this->setCache($strPath, $objReturn);
        }
        else {
          //log some error because $this->error was true
        }
      }
      catch (Exception $ex) {
        $this->error = TRUE;
        //log an exception
      }
    }

    return $objReturn;
  }

  /**
   * Run a query to look up the taxonomy term id based on the url alias path
   * @param string $strPath url alias like 'parent-category/child-category/grandchild-category'
   * @return object results of the query
   */
  private function _dbSelect($strPath) {
    $result = NULL;
    try {
      //The alias stored in the url_alias table is going to be prepended with 'store/' because of my pathauto taxonomy pattern
      $result = db_select("url_alias", "ua")
        ->fields('ua', array('pid','source','alias'))
        ->condition('alias', 'store/'.$strPath, '=')
        ->condition('source', 'taxonomy/term%', 'LIKE')
        ->range(0,1)
        ->execute()
        ->fetchObject();
    }
    catch(Exception $ex) {
      //log an exception
    }

    //$result is an object like:
    //$result->pid //'12345'
    //$result->source //'taxonomy/term/123'
    //$result->alias //'store/parent-category/child-category/grandchild-category'
    //$result->uid //1
    return $result;
  }

   /**
   * Get an object from cache
   * @param  string $strPath used as part of the cache id
   * 'cache_taxonomy_url_alias' is a custom cache bin
   * @return object data from the persistent cache
   */
  private function getCache($strPath) {
    $objCache = cache_get('example_module_plugin_argument_validate_url' . '::' . 'store/'.$strPath, 'cache_taxonomy_url_alias');
    if (isset($objCache->data)) {
      return $objCache->data;
    }
    else {
      return NULL;
    }
  }

  /**
   * Store an object in cache
   * @param  string $strPath used as part of the cache id
   * @param  object $objData contains the url alias table results
   * @return void
   */
  private function setCache($strPath, $objData) {
    cache_set('example_module_plugin_argument_validate_url' . '::' . 'store/'.$strPath, $objData, 'cache_taxonomy_url_alias', time() + $this->intAddUnixTime);
  }
}

```

After that I selected my custom contextual filter validator:
> 2 votes

---
Tags: views, input-formats
---


# Question
Title: Modifying a views organic groups exposed filter
I have a view with an exposed filter of organic group id's (ie: gid). I wanted to convert it to be a dropdown with the actual group name. I did so with a form alter. The filter works fine, however I'm having an issue with the filter when trying to view all groups. I tried adding 'ALL' to the dropdown, but that doesn't match a particular gid, so it doesn't work. How can I fix my code to allow content of all groups to show?

```
/**
 *  Implements hook_form_alter().
 */
function tma_views_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] === 'views-exposed-form-event-list-page') {
    $form['field_event_type_tid']['#type'] = 'hidden';
  }
  elseif ($form['#id'] === 'views-exposed-form-page-event-calendar-page') {
    $form['og_group_ref_target_id'] = array(
      '#type' => 'select',
      '#options' => tma_views_get_chapters_list(),
      '#default_value' => 'ALL',
    );
  }
}

/*
 * Retrieves an associated array list of all Chapter nodes
 * return - a list of nids
 */
function tma_views_get_chapters_list() {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'chapter');
  $results = $query->execute();
  foreach ($results['node'] as $node) {
    $nids[] = $node->nid;
  }
  $nodes = node_load_multiple($nids);
  $options['ALL'] = 'Select Chapter';
  foreach ($nodes as $node) {
    $options[$node->nid] = $node->title;
  }
  return $options;
}

```

EDIT: One more thing to note: when no filter is set at all (for the organic group filter), I get a drupal error message on the screen:

```
An illegal choice has been detected. Please contact the site administrator.

```

I obviously would like to be able to fix that as well.

# Answer
> 0 votes
It would seem to me that you would want to modify that filter in the Views UI. Is **required** checked? Also, a standard practice that I've seen for Drupal select is having all actually keyed with **\_none** rather than **ALL**.

---
Tags: views, organic-groups
---


# Question
Title: Feeds importer. Only imports a certain amount then stops
I have been attempting to import 5,000+ pieces of content from a CSV file using the feeds module. I have it set up to import 130 items every cron run and i have cron running every hour.

All is good for the first few hours. I go to sleep and then wake up, and it is no longer running.

I have my cache clearing every 6 hours. is it possible that clearing cache kills the communication with feeds and stops the import record?

Is it a simple setting change within feeds?

I cannot monitor it completely to see when this issue stops exactly since my imports are suppose to be spread over 48 hours on each hour.

Update: If I run cron manually over and over again, it will reach 100%.

# Answer
> 0 votes
you can check your php config php\_memory\_limit must be at least 128M and max\_execution\_time 120

also check the error logs go to admin/reports/dblog and check for the errors logged by the server, maybe you can find the problem there

Also make sure you are getting all the errors so you can make a better debug in your issue

Change settings in your site

You can show all errors by adding a few lines to your local testing site's settings.php:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
//Note:  Do not include the opening and closing PHP tags when you copy this code

```

In addition, navigate to Administration→ Configuration→ Development → logging and errors and select "All messages". (This sets $conf\['error\_level'\] = 2; .)

# Answer
> 0 votes
Try adding this to setting.php

**$conf\['feeds\_process\_limit'\] = 2000;**

---
Tags: caching, feeds, cron
---


# Question
Title: Webform2pdf and CiviCRM fields: pdf empty
I have a Drupal website with CiviCRM. I created a webform and installed webform2pdf to create a pdf and CiviCRM integration module to add CiviCRM fields to my webform. After submission the webform fields are correctly added to the pdf but the CiviCRM fields are not.

Any idea? You think you could fix it or give me any advise?

# Answer
> 0 votes
In a Webform, CiviCRM fields *are* webform fields. There is no difference as far as Drupal is concerned. The only exception is CiviCRM credit card fields (which you really don't want to store in the webform submission). The "existing contact" field is another special case, but although it gets processed a bit differently it is still a "real" webform field and ought to work fine. So aside from the above I can think of no reason why any CiviCRM-related fields would not appear on a PDF.

---
Tags: webforms, civicrm
---


# Question
Title: Commerce Shipping - arbitrary calculations
I'm using Drupal Commerce to create a simple shop and I wish to add shipping cost calculations based on the weight (in grams) of items in the cart. I have set a weight field on each product so I can work out what the total is, but the client has specified arbitrary prices depending on weight and destination:

```
UK
weight = 0 price = 0.00
weight < 250 price = 1.00
weight < 500 price = 1.50
weight < 750 price = 2.00
weight < 1000 price = 3.00
weight < 2000 price = 5.00

Europe
weight = 0 price = 0.00
weight < 250 price = 2.50
weight < 500 price = 4.00
weight < 750 price = 5.00
weight < 1000 price = 6.25
weight < 1250 price = 7.50
weight < 1500 price = 8.75
weight < 1750 price = 10.00
weight < 2000 price = 11.25

Other
weight = 0 price = 0.00
weight < 250 price = 4.00
weight < 500 price = 6.50
weight < 750 price = 8.75
weight < 1000 price = 11.25
weight < 1250 price = 13.75
weight < 1500 price = 16.25
weight < 1750 price = 18.75
weight < 2000 price = 21.25

```

Would I need to add a shipping calculation rule for each possible scenario or is there a way to configure rules to look up a table?

# Answer
I found a module that does exactly what I want: Commerce Shipping Weight Tariff. I set up three services, one for each destination, and used rules based on the shipping address to work out which service to use. Then I added the weight tariffs for each service.
> 1 votes

# Answer
It wouldn't be a bad idea to create a lookup table with a single Rules action that knows how to read the data from the table and set the shipping rate accordingly. However, if you aren't a developer, you can configure this entirely through Rules.

Shipping rates are passed through Rules similarly to product prices, so you can work with 1 or multiple flat rates (from https://drupal.org/project/commerce\_flat\_rate) and use multiple rate calculation rules per flat rate to adjust the price based on the destination and the total order weight. I can't recall if we got Rules integration for total order weight into Commerce Physical Products or not, so you might start by looking there.
> 0 votes

---
Tags: rules, commerce
---


# Question
Title: Debugging Migrate: how to print what data's mapped to a field
I have a migration module that imports data from a CSV. I've steadily been adding code to the module and fields to the CSV, and it's always worked, albeit sometimes only after some work. But now there's one profile2 profile among the many I'm importing to in which the *text* fields don't get any data successfully imported to them. This happens even when I just put '1' or '0' for them in the CSV. Oddly, the non-text fields in the profile2 profile import fine, even though they're later in the CSV and the module code.

My question is how I go about debugging this. I couldn't find a 'how to debug Migrate' page in the documentation or on the web. I've found Migration::displayMessage, but what can I print via this to show what data's been mapped to these fields from the CSV? I just get the abstract mapping structure without any data from my CSV when I run `Migration::displayMessage('<pre>'.print_r($this, TRUE).'</pre>', 'debug');`

# Answer
> 2 votes
Answer from Mike Ryan: I usually run migrations in drush and, when not stepping through in a debugger, use drush\_print\_r(). The key points you want to instrument are prepareRow() (dump $row to make sure the source data is being pulled correctly in the first place) and prepare() (dump $node to make sure the source values are getting properly mapped into the node object that's about to be saved).

---
Tags: migrations, debugging
---


title: Ajax Submitted forms with ENTER

text:
# Question
Title: Ajax Submitted forms with ENTER
I have this code:

```
function THEME_form_user_login_alter (&$form, &$form_state){
  $form['actions']['submit']['#ajax'] = array(
        'callback' => 'ajax_process_form',
        'wrapper' => 'user-login',
        'effect' => 'fade',
        'speed' => 'fast',
        'method' => 'replace'
    );

};

```

It work when i click on the submit button, but when i press ENTER Ajax doesn't get triggered.. Is there a way around that?

Edit: I tried to enable ajax on all fields and set keystroke to True, but then only one field is sent so i get an error as the form process script is expecting two fields.

# Answer
> 7 votes
I realize this is an old thread but it shows up high in the Google search results.

Just set your submit button's Ajax event to 'click'. I believe its default value is actually 'mousedown' which won't make it trigger when the enter key is pressed within a field of the form.

If you set it to 'click', that event will trigger when the submit button is clicked as well as when the enter button is pressed within a form field.

# Answer
> 2 votes
Just make sure you explicitly set ajax event to `click` and it'll work:

```
$form['actions']['submit']['#ajax'] = array(
    'callback' => 'ajax_process_form',
    'wrapper' => 'user-login',
    'effect' => 'fade',
    'speed' => 'fast',
    'method' => 'replace',
    // This is what you need:
    'event' => 'click'
);

```

# Answer
> 1 votes
I haven't tried this, but you should be able to set the event on ajax to include keydown:

```
function THEME_form_user_login_alter (&$form, &$form_state){
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'ajax_process_form',
    'wrapper' => 'user-login',
    'effect' => 'fade',
    'speed' => 'fast',
    'method' => 'replace'
    'event' => array('click', 'keydown'),
  );
}

```

I'm not sure how well `keydown` will work on a submit button, usually you want something more complex that makes sure that the matched key is `Enter`. Alternatively you could catch the `Enter` submit yourself and prevent default (form submit) and the click the button yourself. That would trigger the ajax call like it was clicked and would keep the Drupal powered AJAX intact, which makes things easier to handle server side.

---
Tags: forms, ajax
---


# Question
Title: How can I send an email to Administrator when Users change their name?
We are using LoginToboggan. How can I send an email to Administrator when Users change their name?

I looked at Rules, but the only Rule action which seems close is

"After updating an existing user account"

Is there a (simple) way to program a custom action which sees that the Name field has been changed?

TIA

`{ "rules_notify_sales_on_username_change" : {
 "LABEL" : "Notify Sales/Administrator On Username Change",
 "PLUGIN" : "reaction rule",
 "OWNER" : "rules",
 "TAGS" : [ "email" ],
 "REQUIRES" : [ "rules", "mimemail" ],
 "ON" : { "user_update" : [] },
 "IF" : [
 { "user_has_role" : {
 "account" : [ "account" ],
 "roles" : { "value" : { "11" : "11", "7" : "7", "2" : "2" } },
 "operation" : "OR"
 }
 }
 ],
 "DO" : [
 { "mimemail_to_users_of_role" : {
 "key" : "userupdate-sales",
 "roles" : { "value" : { "6" : "6", "3" : "3", "20" : "20" } },
 "active" : 1,
 "from_name" : "User Update",
 "subject" : "User updated their account information",
 "body" : "An existing user has updated their account. \r\n[account:name] \r\n[account:mail] ",
 "plaintext" : "An existing user has updated their account. ",
 "language_user" : 0,
 "language" : [ "account:language" ]
 }
 }
 ]
 }
}`

# Answer
yes in Rules you can achieve it

**Step 1 :** In Events Event add "**After updating an existing user account**"

**Step 2 :** Conditions Elements "**Execute custom PHP code** "

**return \[account-unchanged:name\] != \[account:name\]**

or add **data comparison** and add

**Data to compare** Selected data: account-unchanged:name

**Operator** : equals

**Data value** : account:name

**Step 3:** In action send mail

refer this for same kind of problem with role. but you have is name

How do I create a Rule "When role is removed, send email to the user"?
> 1 votes

---
Tags: rules, users, emails
---


# Question
Title: Custom Entity Not Showing in View Creation UI
I started learning Drupal 8 this week. I followed this guide to create a new entity, which I then made available through REST using the following tutorial: https://drupalize.me/blog/201401/introduction-restful-web-services-drupal-8

CRUD operations on my entity work just fine. I can also issue my REST requests without any issues. What I'm trying to do now is fetch a list of all my entities via REST. From my understanding, I should create a view for that, but my entity doesn't show up in the view creation UI, so I can't. What do I have to do to make my entity show up there?

I'm not sure what code I should post, so don't hesitate to tell me what code you need to see.

# Answer
You need to add a views\_data handler, like this:

```
"views_data" = "Drupal\views\EntityViewsData"

```

That exposes your entity as views data.

That is the default implementation, which does a lot, but you might need to subclass that and extend the definitions if you need additional filters/fields/...
> 5 votes

---
Tags: views, entities, 8
---


# Question
Title: Ubercart alter product price when product added to cart
I need to alter Ubercart product price on Ubercart 3, Drupal 7, when product is added to cart. I need to check some conditions, and if met, change the price. I thought i can go with

```
function MYMODULE_uc_cart_item($op, &$item) {
  switch ($op) {
    case 'load':
      drupal_set_message(t('It works!'), 'status');
      break;
  }
}

```

but not sure am i targeting right hook.

It seems that it does not work (it is not invoked).

Thanks for clues

# Answer
> 2 votes
Here is another hook you can play with hook\_uc\_add\_to\_cart

```
Parameters:
$nid - the node ID of the product
$qty - the quantity being added
$data - the data array, including attributes and model number adjustments

```

Here is how to work with hooks

> Drupal's module system is based on the concept of "hooks". A hook is a PHP function that is named foo\_bar(), where "foo" is the name of the module (whose filename is thus foo.module) and "bar" is the name of the hook. Each hook has a defined set of parameters and a specified result type.

`function hook_uc_cart_item($op, &$item) {` the work hook should be replaced with your modules name like

`function YOURMODULENAME_uc_cart_item($op, &$item)`

See Hooks

# Answer
> 2 votes
The problem was in clearing cache. For some reason, clearing cache from Drush does not completely work. (I need to clear it from interface). It might be also APC i implemented at some point. I have issues when clearing cache for modules/other code.

**EDIT:**

I can't get hook\_uc\_cart\_item to work so far. (even as hook\_cart\_item) hook\_add\_to\_cart works, and hook\_uc\_cart\_alter also works (for me)

I think i might take **hook\_cart\_alter** approach, as it gets items every time cart is viewed, in fact, they say it gets loaded all the time, and they have warned of performance issue, but as i need to watch on cart all the time as i have some dynamic calculations depending what is in cart, i think, if devel and kcachegrind dont complain, i will not, too :)

I see **uc\_coupon module** also uses hook\_cart\_alter without fear :)

# Answer
> 2 votes
This is how I solved it:

```
function mymodule_uc_cart_alter(&$items)
{
    $items[45]->price = 29393;
}

```

In this example I'm just hardcoding the change to demonstrate how to change the value. Obviously you would apply your own logic here based on whatever your requirements are.

---
Tags: ubercart
---


title: Redirect for specific path links

text:
# Question
Title: Redirect for specific path links
I have to make redirect for links:
http://example.com/file/file1.pdf
http://example.com/file/file2.pdf
...
to links:
http://example.com/sites/default/files/file1.pdf
http://example.com/sites/default/files/file2.pdf
...
I've tried .htaccess changing, but fail. (it's too Voodoo for me)
Redirect project has no such function (afaik).
I don't know what hook can I use in my module for such redirect.

How can I make such redirect?

**UPDATE:**

I've created simple .htaccess file:

```
  RewriteEngine on
  RewriteRule ^file/(.*)$ sites/default/files/$1 [L]

```

And it works.

But when I insert in original Drupal .htaccess
line `RewriteRule ^file/(.*)$ sites/default/files/$1 [L]` after `RewriteEngine on`
\- there is no successful redirect.

Why?

**SOLUTION:**

```
  RewriteEngine on
  RewriteRule ^file/(.*)$ sites/default/files/$1 [L, R=301]

```

# Answer
As you seem to have learned the Redirect module is really for *page-specific* redirects (this single URL redirects to that URL), not *patterns*, as your case seems to require. For this a server-side redirect is really the way to go. Not only is it a standard solution to this kind of problem, but it can happen independent of Drupal, so there is no need to bootstrap Drupal just to process the redirect.

I think the specifics of setting-up a server-side redirect a a bit are a bit beyond the scope of this space (as it's not a Drupal-specific concept), but there are **lots** of resources out there on the topic, and I think you'll find that it's not too hard. You mentioned that it feels like "Voodo", but I think it will prove far more straightforward than a module-based solution implemented in php. Here's one example stackexchange post that might be relevant to your case.

All that said, because your question does ask for a moudle-specific way to do it, here are some notes on that too. This is much less ideal, as noted above, but it's worth referencing. For this I think you would want to trigger a drupal\_goto() inside of hook\_init(). A very simple-case example of this pattern can be referenced in this post, and interpolated for your example:

```
/**
 * Implements hook_init().
 */
function mymodule_init() {
  $path = current_path();
  // preg_match() could also work instead of drupal_match_path()
  if (drupal_match_path($path, 'file/*')) {
    drupal_goto('sites/default/' . $path);
  }
}

```

I suppose there may be real use cases for this kind of module-based approach, but as I noted above, I really don't think your case is one of them. You would probably be best-served with a service-side redirect (in Apache/.htaccess).
> 2 votes

# Answer
Redirecting from one url to another You can try

https://www.drupal.org/project/path\_redirect module to redirect from one URl to another

This module allows you to specify a redirect from one path to another path or an external URL, using any HTTP redirect status.

# D7CX: I pledge that Path redirect will have a full Drupal 7 release on the day that Drupal 7 is released. Note that the project has moved to http://drupal.org/project/redirect for Drupal 7.
> 0 votes

---
Tags: 7, redirection
---


# Question
Title: How to add css class to a table created using views
I want to add a css class to a table which is created using views. I tried to override "views-view-table.php" in my custom theme but that doesn't seems to work. In "views-view-table.php" I replaced the line "`<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>`" with "`<table class="responsive">`" and then cleared the cache, yet it didn't work. Can any one help. Thanks in advance.

# Answer
> 3 votes
This is an old post, but I'd like to chime in with a couple of solutions.

First, and this may not answer your question directly, but you can change the CSS selectors you are using to target the table.

So, rather than using `table.yourclass` you could use `.yourclass table`. This can be accomplished by setting a custom class for the entire view under the *advanced* section.

Of course, this won't work if you are trying to add classes directly to the element as you might need to do with Bootstrap, i.e. `table.table.table-striped`.

The second solution will allow you to add the same classes to all your tables. In your `template.php` file, add the following:

```
function THEME_preprocess_views_view_table(&$vars)
{
    $vars['classes_array'][] = 'table table-striped';
}

```

If you need to target a specific table, you can also check the `$vars` variable first to find the name of the view and display being called and only apply your classes to the ones you want to target. I haven't checked, but it's probably found in something like `$vars['view']->current_display`.

Finally, it's worth noting that Views does actually support custom classes on the table. The variables are called in the template files, there just isn't an option for it in the views GUI. This is an oversight in my opinion, but the module's devs don't seem to plan on fixing it. That said, a patch for it *does* exist (direct link).

# Answer
> 2 votes
You should not need a template file for this. Under the Advanced \> Other tab in your view there is a CSS class option. You can add it there and then use the appropriate selectors to your CSS. You can also use `hook_preprocess_views_view()` to add the class to the `$classes` variable used in the template.

# Answer
> 0 votes
The file you try to override should be "views-view-table.tpl.php". You forgot the ".tpl". To view all the available files that you can override, use the option "Advanced -\> Theme:Information" from the view config page.

# Answer
> 0 votes
You are theming the view incorrectly. Follow the below steps for view theming :

1. Go to Advanced tab in your view.
2. Click Theme:Information.
3. Create the file in your theme template directory with the name eg. "views-view-table--abc.tpl.php" if your view name is 'abc' i.e. Replace 'abc' with desired view name.
4. Click on "Rescan Template File" button and see if name of file you created become bold or not.If yes then your view has been themed, if not then file name might not be correct. For more details https://drupal.org/node/352970

---
Tags: 7, views, theming
---


# Question
Title: What is causing Views to consistently but intermittently not find a view provided by the Advanced Forum module?
I'm getting a frequent, intermittent error from the Advanced Forum module that causes a 500 error when it occurs (WSOD). On production, it's happening about 20 times per hour, on probably 2-3% of all forum page loads per hour. It is *consistently intermittent*. Locally, I cannot consistently reproduce the error, but it does occur.

The error is on

> Line 232 o f sites/all/modules/contrib/advanced\_forum/includes/core-overrides.inc\`:
>
> Call to undefined method stdClass::preview()

The problem lies with the advanced\_forum\_get\_topics() function:

```
function advanced_forum_get_topics($tid, $sortby, $forum_per_page, $sort_form = TRUE) {
  $term = taxonomy_term_load($tid);
  drupal_add_feed('taxonomy/term/' . $tid . '/feed', 'RSS - ' . check_plain($term->name));

  // Views handles this page
  $view = views_get_view('advanced_forum_topic_list');
  $view->sort_form = $sort_form;

  return $view->preview('default', array($tid));

}

```

Essentially views\_get\_view() fails to find the view and the object isn't created as expected on the return line. So the problem seems to lie with Views occasionally not knowing the view exists. This makes me think it's a hook problem.

Where it starts to get odd are the implementations of hook\_views\_default\_views() and hook\_views\_plugins(). According to views.api.php hook\_views\_default\_views() should be in a file called MODULENAME.views\_default.inc and hook\_views\_plugins() should be in a file called MODULENAME.views.inc. However, both files are in the MODULENAME.views.inc file.

From views.api.php:

* `hook_views_plugins()`
This hook should be placed in MODULENAME.views.inc and it will be auto-loaded.
MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.
* `hook_views_default_views()`
This hook should be placed in MODULENAME.views\_default.inc and it will be auto-loaded. MODULENAME.views\_default.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.

I tried splitting up these routines into the seemingly correct files. This caused Views to consistently find the Advanced Forum view (as indicated that it appeared in the Views GUI list) but not see the plug-in. The pages in Advanced Forum ran fine, but the views were blank because they referenced a style plugin provided by Advanced Forum that Views was no longer seeing.

I assume I'm missing something about Views hooks, but I'm totally stumped.

* Stack: Drupal 7, Views (7.x-3.3), CTools (7.x-1.0), Advanced Forum (7.x-2.0)
* PHP FPM, APC, nginx, Redis
* I didn't find anything helpful in this d.o issue

**UPDATE 1**: While I have not solved the root cause, it does appear that disabling Redis and reverting to Drupal's default database-based cache storage mechanism stops the problem from occuring.

**UPDATE 2**: I can reliably replicate the issue on local by doing a `flushall` in Redis. The first page load of looking at a forum listing will fatal out. ~~The second page load (and all subsequent) work fine~~. UPDATE: I have to hit the admin Views listing page to clear the error.

**UPDATE 3**: On further troubleshooting the issue appears to be caused by the Views cache not properly being rebuilt after a cache clear, only when using Redis. The issue does not occur when reverting to standard Drupal cache. When the issue occurs only 2-4 cache entries exists for Views, as opposed 100+ when the cache is properly built. Visiting the admin views list page causes the cache to be fully built and the issue does not occur. I need to verify if hitting any View view page causing the issue, or just the advanced forum view.

**UPDATE 4**: A helpful user on IRC has suggested this might be a problem related to Views cache race condition issues: 853864, 1102252

# Answer
> 1 votes
It sounds like you found the right answer from the IRC. "Consistently intermittent" in my experience is when there are two sources filling the cache. Most common is when you have a development site and a staging/production site on different code bases but same database. The drupal-provided caches that I have read code for connect to the database, so routing/function information that is cached will cross contaminate. Hitting the admin/modules page will refresh the module cache and locations, hitting the admin/views listing page clears your error because it refreshes the site's understanding of views from the perspective of your site instead of the perspective of whatever is conflicting with you.

If you have server admin ability, change the password to your site's database and the password in your settings.php, and see what breaks. Your listings should stop being corrupted and what is tampering with them should break ... unless it is directly connected to your site and using your settings.php file.

Also, check to make sure there are not multiple installations of the views module in your docroot.

---
Tags: 7, views
---


# Question
Title: How to modify display of image form metadata after upload on node edit form?
After uploading an image, how do I hook in and change the display so that Title appears above Alternate text?

# Answer
> 0 votes
Here's the answer, which I discovered after some further research:

```
/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  // If this is an an image on a slideshow
  if (isset($context['form']['type']['#value']) && $context['form']['type']['#value'] == 'slideshow') {
    // Loop through the element children (there will always be at least one).
    foreach (element_children($element) as $key => $child) {
      // Add the new process function to the element
      $element[$key]['#process'][] = '_MYMODULE_image_field_widget_process';
    }
  }
}

function _MYMODULE_image_field_widget_process($element, &$form_state, $form) {
  // Change the way metadata form fields are displayed;
  unset($element['title']['#description']);
  unset($element['alt']['#description']);
  $element['title']['#weight'] = '-4';
  $element['alt']['#title'] = 'Description';
  // Return the altered element
  return $element;
}

```

---
Tags: media
---


title: Redirect anonymous users to custom URL

text:
# Question
Title: Redirect anonymous users to custom URL
I would like to implement a custom redirect for anonymous users that try to access a form built with FAPI. user\_is\_logged\_in is used in access callback to provide true or false.

However, I couldn't find documentation on how to hook into access callback functionality e.g. what happens when it returns FALSE? Now it automatically redirects to default user login page but I need change this.

# Answer
Try the Rules module and generate a new rule for the form page being viewed by the anonymous users, to redirect to the page as you wish.
> 0 votes

# Answer
You can make the page available for all users, also anonymous, and in the page callback redirect the anonymous user to your custom page.
> 0 votes

# Answer
I think you can also try hook\_init. Try this one, may be it'll work.

```
function mymodule_init() {
  global $user;
  // Getting path
  $path = url($_GET['q'], array('absolute' => true));
  // Redirect from the path
  if ($path == "http://localhost/sitename/node/1") {
    // Check anonymous user
    if ($user->uid == 0) {
      // Redirect to path
      drupal_goto("http://localhost/sitename/node/2");
    }
  }
}

```
> 0 votes

# Answer
For now I just used user\_is\_logged\_in() in page callback to get desired functionality.

It shows a login button on page if function returns false and by clicking it user is redirected to 3rd party site and back. Otherwise it shows content which is in this case a custom form.
> 0 votes

---
Tags: forms, redirection, users
---


title: Auto-suggest products based on tags

text:
# Question
Title: Auto-suggest products based on tags
I am interested in autosuggesting products based on the tags an article contains which is read by a user. How can I accomplish this with Drupal/Drupal Commerce? thanks

# Answer
I'm not entirely sure which one better fits your use case: This blog post has an excellent way to accomplish product suggestions using the Radioactivity module. http://www.wunderkraut.com/blog/drupal-commerce-product-suggestions-with-radioactivity/2013-08-22

There is also the Commerce Recommender module: https://www.drupal.org/project/commerce\_rec. Again, I'm not sure if that is precisely what you're after.

A really straightforward way I could see is create a commerce product view that filters down to only products with the same taxonomy terms on the current article, create a block to hold that view, and display those products with/without their Add to Cart buttons.
> 1 votes

---
Tags: commerce
---


title: how to change language

text:
# Question
Title: how to change language
After a full day of searching, I can't find a way to make the multilingual to work on my site.

I want to create a temporary site to host privacy policies in many different languages (6) but with the skin of our corporate site which is only in English and French. In fact we could have created those pages in the corporate site but we don't want to translate the site in all those languages for now.

I created a new folder to host my new site in multisite mode. I also copy pasted many modules and a theme that was made (by an external firm and where the multilingual works) in my new site's folder to customize/handle them seperatly.

I tried to match all the modules of the original site with my new sites.

I didn't work... All my aliases answers with a

> ```
> "The requested page "/fr/myalias" could not be found.".
>
> ```

Only the English aliases seems to work.

I followed the solutions found on these web site. Nothing worked.

https://www.drupal.org/node/1069310 https://stackoverflow.com/questions/13648789/drupal-7-url-alias-is-getting-ignored-on-pages-when-provide-a-menu-link-is-un https://www.drupal.org/taxonomy/term/34344?page=7 https://www.drupal.org/node/1216132

At the beginning I though that it was the path alias that wasn't working but after a few hours I realized that the site never quit the English language (default).

I added 5 more languages (fr, nl, es, pt, de).

For a start, I just don't know why/how to change the language. I try calling "/fr" but that also answers with

> "The requested page "/fr"

could not be found."

Edit: also I realize that all the (working) pages are called with "/?q=node/somthing" instead of "/node/something"... if that helps...

# Answer
About

> I realize that all the (working) pages are called with "/?q=node/somthing" instead of "/node/something"

To make your path aliases be human readable, pls check if **Path** module is enabled and then go to *Administration » Configuration » Search and metadata » Clean URLs* and check "Enable clean URLs" checkbox. If it is not editable, you should ensure that PHP Rewrite mod is enabled.

**To have your content displayed in diffrerent languages correctly you need:**
1) Have **Locale** and **Content** transpation modules enabled. Both of them are Core modules.
2) Goto *Home » Administration » Configuration » Regional and language » Languages* and add the languages you need. Ensure that all required langs have ENABLE checkbox chacked. Also ensure that you have the correct *Path prefix language codes* (can change is edit Language) for each lanf, like "en" (without quotes) for English, "fr" for French etc.
3) Goto *Administration » Structure » Content types » Your\_content\_type* (that one you're using for creatinf translatable content) and ensure that in \*Publishing options" tab "Multilingual support" is set for "Enabled, with translation".
4) Now create your piece of content and in creating content form set Language select box as "English" and set the *URL alias* as "policy-1" for example. Save it. Now you should see a "Translate" tab (near View/Edit tabs). Press it, select the lang you need and follow add translation link.

**Tip:** I don't know how your theme looks, so i'm not sure if you have a lang switcher for users or lang links displayed when viewing transled content. But if you use the same alias for all your translation, you can easily check if it works or not. For example if you set "policy-test" as Path alias for all transleted versions of your test node, you should be able to visit it via *\[yoursite\]/\[lang-prefix\]/policy-test*, i.e. via *\[yoursite\]/en/policy-test* or *\[yoursite\]/fr/policy-test* etc.

P.S. you don't need to use your lang prefix in path aliases for any language. Drupal will do it itself.
> 0 votes

# Answer
When I was looking for another thing I found why by adding "/fr" to the url it was not changing the site in French.

you have to go to Configuration \> Regional and language \> Languages \> Detection and selection

Then you have to check URL in both section (User interface text language detection and Content language detection)

It basically solve all my other problems including the broken alias urls.
> 0 votes

---
Tags: i18n-l10n, multi-sites, path-aliases
---


# Question
Title: Creating a responsive menu system for a site with a lot of content
I am currently creating a website which has a lot of content - text. For this I need a serious menu structure with 5-10 menu items per menu and at least 15 menu-blocks per main menu item.

Further it has to be accessible via mobile.

Till now I have used panels and added menus inside the panels. But mobile isn't to happy about that and the list-names in the menus overlap the content.

How would you go about solving this issue? I trust you experts here! :-)

# Answer
for creating responsive menu you have lots of projects

below are some

https://www.drupal.org/project/responsive\_menus

https://www.drupal.org/project/responsive\_navigation

https://www.drupal.org/project/responsive\_dropdown\_menus

https://www.drupal.org/project/responsive\_menu

try any one will help you out.
> 4 votes

# Answer
I recommend looking into a couple of third-party javascript and/or jquery plugins you can integrate with Drupal to provide a more unified menu experience for both desktop and mobile users.

**Big Slide Menu - Mobile Push Menu**

The first, more tested option is to utilize the Big Slide Menu plugin, which creates a mobile push-menu, which can account for several layers of depth, without demanding too much screen real-estate.

https://github.com/adgsm/multi-level-push-menu

This option may be difficult to integrate the with Drupal Menu system, but it would certainly give you a robust solution, which can accomodate you needs for a large more complex menu system.

**Snap.js - Mobile Shelf Menu**

The second, but perhaps more complicated option is to integrate Snap.js, which provides a mobile-shelf "type" menu.

https://github.com/jakiestfu/Snap.js/

To my knowledge it's not a module for Drupal, but that being said you don't have to do much to combine the plugin with drupal.

First, you have to be able to edit the page.tpl.php, which is where you want to add the snap-content selector to page container.

Second, you have to add the Snap content container, which will contain the responsive-ready menu system. I recommend adding this below the page container. You will either want to add a new region in this location ( so you can add blocks from admin/structure/blocks) or create a function to add the appropriate menu to the location. I definitely don't recommend hard-coding the menu in, but it may be a consideration in your case if the menu is static and you want to make the design process a little easier.
> 3 votes

---
Tags: routes, theming
---


title: Do drupal themes require CSS3?

text:
# Question
Title: Do drupal themes require CSS3?
Do drupal themes require CSS3 or can they just be HTML5?

# Answer
Theoretically, they can "require" neither.

CSS3 is a version of CSS, and while it can incorporate CSS3 in a theme, CSS2 or CSS1 elements (except those deprecated) would still function in a Drupal site and theme. Be aware however, that without CSS of any type, you will not have colour, size, position, fonts or other similar customization of layout outside the browsers default, which will differ from user to user. Take note that most modules and themes will use CSS3 elements.

HTML5 likewise, is a version of the HTML "standard", which really isn't a standard. HTML5 in particular is still under construction by the industry and subject to change at any time, for any reason. Drupal 8 core while technically sets its document type as HTML5, it uses more HTML 4.xx, xhtml than HTML5. Drupal 7 core primarily uses xhtml, yet another variant on the standard. Therefore, you can use 4.xx, xhtml or earlier elements, without using any HTML5 (especially for browser specific elements) to maximize compatibility. Take note however, that most modules and themes now heavily use the new options provided by HTML5 in Drupal 7 or 8, even back ports of Drupal 6.
> 6 votes

# Answer
I do not think you quite grasp the meaning of what those are. A Drupal them doesn't technically require ANY CSS, and really only the simplest of HTML.
> 2 votes

# Answer
Neither CSS3 or HTML5\* are necessarily required.

\*Drupal incorporates HTML5, but you would be perfectly fine creating a majority if your

In fact most websites are still built using normal'ol CSS and HTML

When you hear people talking about CSS3 and HTML5 (if they are talking about it correctly) they're really referring to all the amazing stuff like transitions, animations, tags and data="" attributes.

A modern website doesn't necessarily require all of those features provided by CSS3. I develop themes using the Omega4 framework and I rarely use even 5%-10% of the power provided by those languages and I consider my themes relatively modern.
> 2 votes

# Answer
> CSS3 and HTML5 is basically dependent on browser not on Drupal. You can use any CSS3 or HTML5 code considering browser support it.

https://www.drupal.org/node/1516366#comment-5832208

To Answer your question **NO** does not need CSS3 and it can only be run by using a HTML5.
> 1 votes

---
Tags: theming
---


title: Don't know how to add title_suffix

text:
# Question
Title: Don't know how to add title_suffix
I am working on existing Drupal project. I am begineer at Drupal and I need a help with something. In one node I've got title with title\_suffix. This node is a view. I want to edit this title\_suffix, but I don't know how and where to look at it. Could anyone help me please? Where do I have to looking for? UI or template files or where? Thanks.

# Answer
> 0 votes
Use a preprocess function to populate `$title_suffix`. It belongs in a file called template.php in your theme folder.

Here's a primer: Setting up variables for use in a template.

A basic example that populates the variable `$foo` and makes it available to page.tpl.php (Drupal 7.x):

```
<?php
function THEMENAME_preprocess_page(&$variables) {
  $variables['foo'] = 'bar';
}
?>

```

The core module **Contextual links** populates `$title_suffix` in its implementation of hook\_preprocess(). View source at modules/contextual/contextual.module for an example of how it is done.

---
Tags: nodes
---


# Question
Title: Making sticky results in Search API Solr
We want to be able to promote some nodes on the search results. I thought about using the "Sticky" option, so if a node is sticky, it should be on top of the results.

I've tried using the "Boost" option in the index field settings but it doesn't work.

Is there any way of achieving that?

(Using Drupal 7, Apache Solr 4.6.1 and Search API)

# Answer
> 1 votes
Could you perhaps?:

1. Put a boolean field on your content (or make use of the 'promote to front page' field)
2. Make a view to arrange your search results
3. Group by that boolean (or 'promoted')

I don't know if 'promoted' is indexed by default, you might need to set that.

---
Tags: 7, search
---


# Question
Title: Feeds importer incremental URL parameter
I am trying to achieve incremental URL changing to avoid creating thousands of importers. For example if the feed URL contains the param ID=1, i need to loop until ID=1000 and import the provided JSON with the same rules. For example..

1. https://domain.com/api/v2/bios.json?bio\_id=**15**&with\_faces=true
2. https://domain.com/api/v2/bios.json?bio\_id=**16**&with\_faces=true

...and so on...

Is there ANYTHING to allow me do that? Thanks in advance.

# Answer
You want to take a look at the Web Scraper Example.

https://www.drupal.org/project/example\_web\_scraper

In Feeds Importer you want to look into the Robots spider setup, which will follow links and patterns, so a single importer can create 10's, 100's or even 1000's of new Nodes.

The example scrapes the Stanford Events website - spidering the page, following the links and creating a new node for each item. You can also run the importer on single event pages.
> 5 votes

---
Tags: importing-exporting, feeds
---


title: 5 second delay caused by itok

text:
# Question
Title: 5 second delay caused by itok
I recently noticed a 5 second delay on my Drupal 7.34 website which I think is being caused by itok (a new security token used for files, like images, that are modified by Drupal). How do I remove this delay? Do I have to disable itok?

For instance this image takes 5 seconds to load.

# Answer
If you can, look instead at serving the image as a public file, so that your webserver can return it directly without loading Drupal at all for that request. Instead of seeing `system/files` in the path, you'd see a path to the actual image file on your server - eg `sites/default/files/`.

Review whether it's necessary to serve images using the Private download method, which introduces a Drupal bootstrap and access controls on all static file requests. The default for this is configurable at `admin/config/media/file-system`.

It may be you're seeing a delay across all requests handled by Drupal, and have noticed it because you'd expect serving a static file to be quicker than that? Note that requests for static files (eg your logo) are not similarly affected, but for me I see ~6s response time checking the more basic pages on your site (eg `curl --head` against your donate page).

Is your server overloaded, or do you have modules enabled which might be performing time-consuming operations (eg network activity, DNS lookup, ...) for every request?

A patch in d.o#2089789 gives you a means to remove the `itok` token if you do need to serve that image after checking Drupal's access controls.

The reasons for introducing itok are discussed in the Drupal 7.20 release notes.
> 2 votes

---
Tags: media
---


# Question
Title: How can I sort a View's exposed filter options alphabetically?
I have a custom module which uses `hook_form_views_exposed_form_alter()` to sort the options of a select list into alphabetical order.

This appears to work because `dmp($form)` shows `$form['field_keywords_tid']['#options']` to be in alphabetical order, but when checking the select list the order is different.

You can see the view and the dpm() output on the dev site.

My code so far is:

```
function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {
    foreach ($form_state['view']->filter as $field => $filter) {
      if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
        $field_id = $form['#info']['filter-field_keywords_tid']['value'];
        asort($form[$field_id]['#options']);
      }
    }
    dpm($form);
  }
}

```

I thought I needed to replace `$form['filter-field_keywords_tid']['#options']` with the sorted array so I tried the following code after the foreach above, but this didn't work either.

```
$options = array('All' => '- Any -');
foreach ($form[$field_id]['#options'] as $key => $val) {
  $options[$key] = $val;
}
$form['field_keywords_tid']['#options'] = $options;

```

I also tried the code below found in this Drupal Answers post with the same result. dpm() output sorted but select list not.

```
foreach ($form_state['view']->filter as $filter) {
  if($fid = $filter->options['expose']['identifier']) {
    asort($form[$fid]['#options']);
  }
}

```

I'd appreciate any suggestions.

# Answer
J. Reynolds suggestion was the answer.

Creating a new function for the sort code and using $form\['#after\_build'\] to call it resulted in the select box being sorted alphabetically.

```
function dependant_keyword_filter_form_views_exposed_form_alter(&$form, &$form_state){
if ($form['#id'] == 'views-exposed-form-annotated-bibliography-page') {
    $form['#after_build'][] = '_sort_alphabetically';
  }
}
function _sort_alphabetically($form, $form_state) {
        foreach ($form_state['view']->filter as $field => $filter) {
            if ($filter->options['exposed']  && $filter->options['id'] == 'field_keywords_tid' ) {
                $field_id = $form['#info']["filter-field_keywords_tid"]['value'];
                asort($form[$field_id]['#options']);
            }
        }
        return $form;
}

```
> 2 votes

---
Tags: 7, views, forms
---


title: Facebook style url fetching

text:
# Question
Title: Facebook style url fetching
Does anybody have an idea, how to do a facebook url or link fetcher just link the one on facebook.

I have tried and have got a script but how to convert that into a drupal module for it to work.

Let me try to be more clear.

If you type a link on facebook it will go and get the image, meta description and other info from that link.

This is what i want to achieve.

If a user enters a link, what or how can i pull the data like image, meta description, etc etc from the link provided by the user.

Facebook-style link module is the perfect example of what i need but it is only for drupal 6 and i need it for drupal 7.

# Answer
You can do this by using any of these below modules :

1. Facebook Connect
2. Simple FB Connect
3. Drupal For Facebook
> 0 votes

---
Tags: social-network
---


# Question
Title: How do I correctly display OG content using Views?
I have an Organic Group page, inside I have a view which lists out news items specific to this OG. However it is showing **'There is no content in this group'** when I am not logged in. And shows up fine when I am logged in.

I have checked that the new article is published, the permission of the View is set to 'Permission' | 'View published content', and I also ensured that the 'View published content' permission is checked for anonymous user.

It's obviously a permissions issue, but I cannot see where else I can set permissions. I am using Workbench OG but there are no relevant settings on there.

**How do I correctly display OG content using Views?**

# Answer
> 1 votes
It could be that you use a relationship in the view that is restricted to only authenticated users. Or it could be that you have set group content visibility to hidden.

But let's start from the beginning..check if it works with a simple view like this:

Create view of nodes, filter it by node type, Add relationship: OG membership: OG membership from Node Add contextual filter: OG membership: Group ID, and use the relationship you just created, and set default value: content ID from URL.

If the problem you describe still appears, you can check if it is a permission issue by selecting "Disable SQL Rewriting" in the views settings. But this will disable views permissions and is not wise apart from testing purposes.

---
Tags: views, users, organic-groups
---


title: Structuring groupcontent with taxonomy

text:
# Question
Title: Structuring groupcontent with taxonomy
I have a site with three grouptypes (organic groups). I am still sort of finding out the right structure as i want each group type to have their own (predefined) taxonomyterms. (og vocab will not work as this is per group)

Should i give each grouptype a different groupcontenttype. This way i can divide my vocabularies over each groupcontentype. This way i will have a clear distinction per grouptype. However it results in more maintenance as i need to make views (filtering taxonomy) and panelpages per grouptype.

Is there some other way that i am not aware of using just one groupcontenttype for all my grouptypes and being able to set the proper vocabulary on them?

# Answer
If the number of group types is relatively small and consistent, you might consider adding several taxonomy term fields to the base *groupcontenttype*, each referencing the relevant grouptype specific vocabulary, and then hiding the fields that are not relevant to a group's type.

If you hid the field on the node edit page using a switch statement (on group type) in hook\_form\_alter, then ensured that empty fields were not displayed on the node, then both visitor and admin would not see irrelevant fields.
> 0 votes

# Answer
I have several OG sites in which the groups structure group content using either taxonomy terms or nodes as categories. In my experience, working with nodes is easier than taxonomy in OG sites, but it depends on your specific purpose. Out of the box non-admin user can't create terms via admin-interface, while they can create nodes, thus also category-like nodes.

In short, using nodes: create a content type 'category' and set it as being group content. Use a entity reference field in all content types, referencing that content type. Create a view that lists only category nodes part of currently viewed group. In the category content type ER field settings, entity selection, set your view you just created.

The same applies to terms:

I quote https://www.drupal.org/node/1507608#comment-8178015

Create a group audience for your vocabulary Edit the created field and within "GROUPS AUDIENCE FIELD OPTIONS", set "Node", "Organic groups"

Go to Views and create a "Term View" Set "Format" to "Entity Reference list" Set "Format options" to the field you need (Taxonomy name for example) Add a "Filter Criteria" "Vocabulary name" to filter terms Add a "Contextual Filter" "OG membership: Group ID". There is no context since we are creating a node, so tick "Provide default value" \> "The OG groups of the logged in user". Leave the other two settings "Group type" and "Concatenator". Go to your content type and create an "Entity Reference" field In "Field options" set "Target type" to "Taxonomy Term" In "Entity selection" set "mode" and select your View. I leave arguments empty Create your node and check how taxonomies are filtered Hope it helps someone :) If your user can't create the term via admin-interface, perhaps rules can help to set the group audience. It's only a thought...
> 0 votes

---
Tags: taxonomy-terms, organic-groups
---


title: Organic groups, audience filter issue

text:
# Question
Title: Organic groups, audience filter issue
When adding groups under the 'audience' list box for Organic Groups, i can see ALL groups created by everyone. How can this be limited so the user only see's his/her groups created in the audience list box? Help is much appreciated!

# Answer
The groups audience field is an entity reference field, which includes a setting to filter the groups using a view. So first create a view that lists the logged in users groups, and use that in the groups audience field setting.
> 0 votes

---
Tags: 7, organic-groups, views
---


# Question
Title: Organic group module- teacher student layout dashbord
drupal7- Organic group. Each teacher manages a class composed of several groups. Teachers only have access to their own groups. By connecting each teacher is directed to a page (or dashboard homebox) containing: its student groups with each group their latest posts, a link to their blogs , a place to send (create) a post to all groups or a specific group. Each group of students connect with the user name and password of the administrator of the group (one group member has the right to connect) and are directed to a page that contains: All posts sent by the group, members of the group, a place to send (create) a post (blog entry) only to the teacher, and a page explaining the course. How much do I create roles (teachers and students only?) which modules should I use? og, og\_menu, og-audience ...

# Answer
> 0 votes
Thats possible out of the box.. see http://nodeone.se/en/permissions-and-roles-for-groups

---
Tags: 7
---


# Question
Title: How do I get the user name of the user profile page that is being visited?
I created a module and I need to use the user name of the user's profile being viewed.

How do I call/get it?

# Answer
You can load a user object like this :

```
$current_user = menu_get_object('user', 1);
$username = $current_user->name;

```

Reference of menu\_get\_object function.
> 4 votes

# Answer
If it's the user that's currently visiting your website that your looking to display then this code can be used.

```
 global $user;
 print $user->name;

```
> 1 votes

---
Tags: 7, users
---