title: form with ajax dosen't send values

text:
# Question
Title: form with ajax dosen't send values
I have a custom form built that generates some fields based on a select box, the form works ok on user side. it loads new rooms when select changes. the problem is that the globallink\_ui\_search\_hotels in form\[values\]\['hotels'\]\['rooms'\] it will only show room\_0 even if you select 2 or more rooms.

update: from what i can see the after number of rooms changes, the generated select boxes dose not have a name attribute

```
  function globallink_ui_search_form($form, &$form_submit){ // the form creation function
  //........
  $form['hotels']['nrrooms'] = array(
      '#multiple_toggle' => '1',
      '#type' => 'select',
      '#title'=>t('Number of rooms'),
      '#options' => array(
        1=>1,
        2=>2,
        3=>3,
        4=>4,
        5=>5,
        6=>6,
        ),
      '#default_value'=>1,
      '#ajax'=>array(
        'callback'=>'globallink_ui_rooms_change_callback',
        'wrapper'=>'globallink-ui-rooms-change-wrapper',
        'effect' => 'slide',
        ),
      // '#title' => t('select departing time'),
    );

    globallink_ui_rooms_change_callback($form,$form_state);

  //....
    $form['hotels']['submit'] = array(
      '#weight' => '7',
      '#type' => 'submit',
      '#value' => t('FIND HOTELS'),
      '#submit' => array('globallink_ui_search_hotels')
    );

  }

  function globallink_ui_rooms_change_callback(&$form,&$form_state){

    $nradults=array();
    for ($i=1; $i < 10; $i++) {
      $nradults[$i] = $i;
    }

     $form['hotels']['rooms'] = array(
        '#collapsed' => '0',
        '#type' => 'fieldset',
        '#collapsible' => '0',
        '#prefix' => '<div id="globallink-ui-rooms-change-wrapper">',
        '#suffix' => '</div>',
    );

    $nrrooms=!empty($form_state['values']) ? $form_state['values']['hotels']['nrrooms'] : 1;

    for($i = 0 ; $i<$nrrooms;$i++){

      $form['hotels']['rooms']['room_'.$i] = array(
          '#weight' => $i,
          '#title'=>'Room '.($i+1),
          '#collapsed' => '0',
          '#type' => 'fieldset',
          '#collapsible' => '0',
      );

      $form['hotels']['rooms']['room_'.$i]['adults'] = array(
        '#required' => '1',
        '#default_value' => 1,
        '#type' => 'select',
        '#title'=>'Adults',
        '#options' => $nradults,
      );

      $form['hotels']['rooms']['room_'.$i]['infants'] = array(
        '#required' => '1',
        '#default_value' => 1,
        '#type' => 'select',
        '#title'=>'Infants',
        '#options' => $nradults,
      );
    }

    return $form['hotels']['rooms'];
  }

  function globallink_ui_search_hotels($form, &$form_state){
    dpm($form_state['values'],'search hotels');
  }

```

# Answer
You need to place

```
 $form['hotels']['rooms'] = array(
    '#collapsed' => '0',
    '#type' => 'fieldset',
    '#collapsible' => '0',
    '#prefix' => '<div id="globallink-ui-rooms-change-wrapper">',
    '#suffix' => '</div>',
);

```

in globallink\_ui\_search\_form function. The wrapper tag must be loaded before callback send.
> 1 votes

---
Tags: forms, ajax
---


# Question
Title: Drupal7 | Time shows differently in Frontend and Backend
The front end time shows as 3 hours behind the backend time of the same page. The correct time is the one on the backend. I set the time-zone correctly for the user and also the time show correctly in the "Administration » Configuration » Regional and language » date and Time"

Here is the time that the page shows on the Backend (the correct time):

And here is the time showing on the front-end (3 hours behind)

And here is the code that I am using in the page template file:

```
`<?php print "Last Updated: " . format_date($node->changed, $type = 'medium'); ?>`

```

I am developing this Website locally on my machine (localhost). Any Ideas to get the time correct on the front end? Thanks.

# Answer
**Problem solved:**

Just in case someone else got the same problem over this. Here is what I was doing wrong (Thanks to Jay from Princeton University for pointing it out):

I set up the Date & Time for the administrator account under "/admin/people", but not the system-wide setting, which is at "/admin/config/regional/settings"

'Administration -\> Regional & Language -\> Date And Time' will show the date/time formats I have set up while respecting the user-chosen timezone (not the system-wide default time zone) so everything looks deceptively like it's how I want it until I log out.

So in short there is another time setting in .../admin/config/regional/settings
that I wasn't aware off.
> 0 votes

---
Tags: datetime
---


# Question
Title: How to create Dummy Content with certain data restrictions (specific date ranges, users, values, ...)
I know about the Devel Module's capability to generate random content (BUT almost no control over the data entered) and also about the D7 Devel script which is a possibility, but i'd like to have a module and not a script. The Dummy Content Module creates the content only upon installation, thats why it does not help me either cause i want to create it via a menu option like it is with the Devel Module.

I searched high and low but could not find a module that gives me that option, can anybody give me a hand here?

**Problem**

Creat *Dummy Content* with specific ranges for

* **date** fields: e.g. between "now" and "now +10 day"
* **number** fields: e.g. between 10 and 20 step 2
* ...

# Answer
> 3 votes
**Quick solution that worked best for me in the end:**

The solution i gave before was indeed the best one to have a general solution and use the mechanisms that were used in the devel module, but what worked best for me in the end was to just use the HOOK\_node\_presave to validate the nodes that were created by the devel module.

```
function MY_MODULE_node_presave($node) {
  // only do this for my_type, and only for nodes created by the devel module
  if ($node->type == 'MY_TYPE' && isset($node->devel_generate)) {
    // apply the limitations, e.g. use values between 2 and 8 in our field
    $node->field_my_field["und"][0]["value"] = mt_rand(2, 8);
  }
}

```

In case a node of the type MY\_TYPE is generated by the devel module (verified by checking the devel\_generate property) we give the field field\_my\_field a value between 2 and 8. This is not possible with the devel module, but we can apply this custom restrictions here and modify the node before it is saved.

So the devel module will create the node as usual, but the function above will modify its values to our needs before it is being saved to the DB.

This has the desired effect although it is hard coded in our custom module, it does the trick.

# Answer
> 0 votes
As noone seems to be able to answer this one, i'll tell the tale of what i finally did:

**WHAT DIDN'T WORK**

I tried to get the **hook\_content\_generate** that is mentioned on a few webpages to work as it seems to be the best way to do it without writing a full fledged module, but it seems that this does just not exist (anymore?). So this was a cul de sac.

Then i saw mentioning of **hook\_devel\_generate** which seems to be kind of a semi-hook (not a real Drupal hook, but these functions get called by the devel\_generate Module to actually create the data), but browsing through the module i saw that before calling the HOOK\_devel\_generate function, it looks for module include files of the type 'FIELDTYPE.devel\_generate.inc' in its own folder, and then in the folder of the FIELDTYPE module to include them via module\_load\_include.
It has generation functions for 'file', 'image', 'taxonomy', 'number', 'text', 'comment', 'list'. So any function that one might create of the form FIELDTYPE\_devel\_generate will be overwritten by the functions included in those files. This is not very flexible and can't really be extended/overwritten, but thats how it is. When i find some time after finishing this project i will bring it up in their forum maybe they will agree to implement sth. more extendable in the future.

**SOME POSSIBLE SOLUTIONS**

So there were two options that looked feasible albeit a bit "hacky"

1. Implement our own version of the devel\_generate
2. Modify the current devel\_generate to our needs

1. Just customize the included functions
    2. Modify devel\_generate to look for custom functions in other modules before loading its own

None of these aproaches are optimal, the best would be if devel\_generate were to implement some hooks to call the generation functions, and not just this brute force inclusion of files.

**MY WORKAROUND**

I went with option 2.2 and patched my "devel\_generate.fields.inc" and **replaced** this code i found at line 41.

```
// Include any support file that might exist for this field.
if (in_array($module, array('file', 'image', 'taxonomy', 'number', 'text', 'comment', 'list'))) {
  // devel_generate implements on behalf of core and special friends.
    module_load_include('inc', 'devel_generate', "$module.devel_generate");
  }
else {
  module_load_include('inc', $module, "$module.devel_generate");
}
$function = $module . '_devel_generate';

```

with this one:

```
$function = $module . '_devel_generate';
// only load the devel_generate or the FILEDTYPES functions if no FIELDTYPE_devel_generate
// function has been defined elsewhere ($module is actually the name of the FIELDTYPE)
if (!function_exists($function)) { // ONLY if the function doesn't yet exist load the files
  // --- ORIGINAL code
  if (in_array($module, array('file', 'image', 'taxonomy', 'number', 'text', 'comment', 'list'))) {
    module_load_include('inc', 'devel_generate', "$module.devel_generate");
  }
  else {
    module_load_include('inc', $module, "$module.devel_generate");
  }
  // --- END ORIGINAL code
}
// We already initialized $function, so remove here..
// $function = $module . '_devel_generate';

```

So with this i can now define my own **FIELDTYPE\_devel\_generate** functions and they will have priority over the ones defined in the fieldtype itself and the ones of the devel\_generate module. This way i could even control the content of each unique field by identifying it through its name ($field\["field\_name"\]), to use field specific settings in my generation function;

I hope this will help others looking for sth. similar, so that they don't have to waste a whole day with research as i did.

---
Tags: 7, nodes
---


# Question
Title: SQL query to count comments for node type
I am looking for a SQL query to count all comments for a specific node type. What code should I use to achieve it?

# Answer
You can use this helper function

```
function mymodule_get_comment_count_by_node_type($node_type) {
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', $node_type, '=')
      ->execute();
  $nids = array_keys($result['node']);

  $comments = db_select('comment', 'c')
      ->fields('c', array('cid'))
      ->condition('nid', $nids, 'IN')
      ->execute();
  $comments_count = $comments->rowCount();
  return $comments_count;
}

```
> 1 votes

---
Tags: 7, comments
---


# Question
Title: Where to place php code snippets in Drupal?
Whereabouts are you meant to place a snippet of php code? I am guessing the root of site? Don't you need to have something point to it?

I am wanting to place this snippet I found to encode email http://shamsphp.blogspot.com.au/2012/11/how-to-encode-email-address.html

# Answer
> 1 votes
Looks like a theme-based snippet, you can put that in your `/sites/all/themes/THEME/template.php` file at the end, or even one of the `.tpl.php` files. The preferred method for stuff like this is to keep it centralized and easy to manage/fix/alter in the future.

At the bottom of that file just paste the code in and reload your cache. To take advantage of it in specific spots, you can utilize Drupal's theme preprocess and form\_alter hook functions.

# Answer
> 3 votes
You should place this helper function in your custom module, so once the module get enabled the you can call this function anywhere across drupal environment.

---
Tags: emails
---


# Question
Title: Redirect a Users Name (Link) to a User Homepage in Panels Using Rules
How does one create the said Redirect a Users Name (Link) to a User Homepage in Panels Using Rules.

Here is my scenerio:

I have a Panels set which will show a subject posted content page in the left panel and the right panel will show a Dynamic list of users in a View, ultimately related to the subject page (ie by ZIP/Postcode, but thats for later).

I wish the View of usernames to then allow the reader to click the said users name (maybe pulled from Profile2 field name link) and take it to a Users (from the said Views) 'about' Homepage. I have pre-designed as a Content (custom) Node template page in the backend Structure for displaying the Users 'homepage'. (the said user will have priviledges to edit/amend via their DB, but that's for later). I'm thinking that this can be done via Views and presumed that a custom Rules Component needs to be created, but I'm stumbling at the next stage hurdle as to "what/where". I'm not sure if I would need to create a dedicated 'node' or whether it can simply be done via a View and if the Relationship elements come into for it to show dynamically to the end browsing user. Later, the Views will also incorporate Location map nodes (ala Google M), but for now I'm happy with an end result showing a static homepage which would have the normal 'about us' text, photo image, 'Contact Us' etc, ala the old Myspace type page.

I have viewed many of Johan Falks' tutorials at http://vimeo.com/nodeone but am still stumped about my approach or whether I'm missing a further module component?

I'm sure this is very basic stuff, but any clarificiation on this process for a learning novice is appreciated. Thanks.

# Answer
> 0 votes
The answer for my issues here was in the said Views block I previously created. Using the field in question (in my case the User Name to link to a Users Public Profile page), I selected "Rewrite Results" then "Output this field as a link" and added the path and \[name\] (\[name\] == User: Name) in the replacement pattern. For example if the path to a Panel page was to be "soccer-player" then I entered /soccer-player/\[name\] this would result in website/soccer-player/sammy (if the user to be clicked was called Sammy and it's URL was shown on a page).

Easy now I come to think of it, but a previous tutorial would have worked wonders when I need it. I hope the above helps someone in future.

# Answer
> 0 votes
So, you want to make the username link to a different page?

You can do that by overriding theme\_username e.g, in template.php

You could also use hook\_preprocess\_username for the theme preprocess function and also change the entity\_uri for the user entity, though the first option is probably simplest.

---
Tags: panels, entities, views
---


# Question
Title: Is there a module that can display items in database?
after a few rounds of research, seems like Drupal is the way to go to manage data, but I'm fairly new to this...

I want to build a website that displays entries in the form of a table from a database.

For example, 1. User type in words of interest in the search bar 2. Data will be retrieved and displayed, which they can use for comparison (ie between data 1 and data 2)

One very similar example is like, http://www.eigenfactor.org/

Your help is greatly appreciated

# Answer
You can use views module to display list of content.

> Views module provide functionality to admin to display list of content in any format without using code.

If you want to implement `autocomplete` functionality with views, then you can use views autocomplete filters module.

> Views autocomplete filters module provide functionality to set autocomplete to node title or any fields.
> 1 votes

---
Tags: database
---


# Question
Title: How can I filter for the UID of the node on a view?
I want to have a relationship between the the author of the node ($uid) and the view results, seems straightforward but I'm not getting it. On the view, I've added the relationship to content:author and then used a contextual filter for the nid. Since this is a block view, I've provided the default argument from the url. It seems like I've done the very same thing before, but I'm going crazy with this case. I have noticed this time that the contextual filter doesn't ask whether to use a relationship, which seems odd.

# Answer
Hope this will help you, To display all content created by author who created the current node loaded, No need to make any relationship, Just add a `Configure contextual filter: Content: Author uid` check the bellow options,
> 2 votes

# Answer
For this you need 2 relationships.

You have a node view with the relationships:
Content: Author
User: Content authored (this one uses the previous relationship)

The contextual filter will use no relationship and your fields and filters will probably all all use the second relationship.
> 1 votes

---
Tags: views
---


# Question
Title: How to use Facebook Connect's user picture in Views?
I'm using the Facebook Connect Module on my Drupal 7 site. If a user logs onto my site via Facebook, his Facebook user picture gets imported to his account on my site. But now I am wondering whether or not there is any way to show this Facebook user picture in Views. This picture is only shown on the user profile page, not in any view that references the user picture field.

Does anybody know how to do this or is there any way to automatically import the Facebook picture to be the standard user picture?

# Answer
> 2 votes
I found a solution: You can use the following hook to copy facebook's user image and save it as drupal user image. Make sure to ask your users to allow this!

```
/* Copy facebook image if no user image is present.
   See: http://drupal.org/node/1764176 */
function custom_api_user_login (&$edit, $account) {
  $fbuid = fbconnect_get_fbuid();
  if(is_null($account->picture) && $fbuid && isset($account->data['fb_avatar']) && $account->data['fb_avatar']){
    #$test = fbconnect_user_picture_override(array('fbuid' => $fbuid, 'account' => $account, 'size' => '25'));
    #drupal_set_message(print_r($test, true), 'status', true);

    if(copy("http://graph.facebook.com/".$fbuid."/picture?type=normal", '/tmp/'.$fbuid.'.jpg')) {
      $path = '/tmp/'.$fbuid.'.jpg';
      $file = new StdClass();
      $file->uid = $account->uid;
      $file->uri = $path;
      $file->filename = $fbuid;
      $file->filemime = file_get_mimetype($file->uri);
      $file->filesize = filesize($path);
      $file->status = FILE_STATUS_PERMANENT;
      $dest = "public://" . $fbuid.'.jpg';
      $file = file_copy($file, $dest);
      file_save($file);
      $edit['picture'] = $file;
      user_save($account, $edit);
      #drupal_set_message(print_r('<img typeof="foaf:Image" src="'.$path.'" alt="Naomi Yoshida">', true), 'status', true);
    } else {
      drupal_set_message(print_r('Kopieren schlug fehl', true), 'status', true);
    }
   }
}

```

# Answer
> 0 votes
other best place to hook

```
/**
 * hook_fboauth_user_save()
 * @param type $edit
 * @param type $fbuser
 *
 */
function sapbrw_registration_fboauth_user_save($account, $fbuser) {

  // Check if the logged in user has a picture saved & has linked their FB     account through fboauth
  if (empty($account->picture)) {
if (copy("http://graph.facebook.com/" . $fbuid . "/picture?type=normal", '/tmp/' . $fbuser->id . '.jpg')) {
  $path = '/tmp/' . $fbuser->id . '.jpg';
  $file = new StdClass();
  $file->uid = $account->uid;
  $file->uri = $path;
  $file->filename = $fbuser->id;
  $file->filemime = file_get_mimetype($file->uri);
  $file->filesize = filesize($path);
  $file->status = FILE_STATUS_PERMANENT;
  $dest = "public://" . $fbuser->id . '.jpg';
  $file = file_copy($file, $dest);
  file_save($file);
  $edit['picture'] = $file;
  user_save($account, $edit);
}
}

}

```

---
Tags: users, social-network
---


# Question
Title: Adding a class to current taxonomy term link
Hi I wrote a SQl query to generate a list of taxonomy terms, I want to add a class to each taxonomy term when its clicked, like when I click any term it goes to its term page, on that page I want some class should be be added to this taxonomy term.

I tried with jquery when I click any term, the class gets added but the page refreshes as it goes to this term page, the class is removed. I can do with cookie procedure, but I think there might be any other way in drupal.

# Answer
> 2 votes
The only thing to think about here is the page you end up on (the term page), so don't worry about links that appear on any other pages.

So what you want to do is on taxonomy/term/% pages, add a class to links that match that page.

Seeing as we are adding a class to an a tag, we want to be altering/overriding the markup output of an a tag.

So then you just have to find the best way to do that.

There are a lot of places that a link might come from in drupal, so to try to cover the most you possibly can, you want to be as general as possible, which in this case means theme\_link(), which as the name indicates, handles the themeing of a link.

For more information on overriding themeable output see About overriding themable output. There are also many other examples across the internet.

In this case you will want to do something like this...

In your theme's template.php file add this:

```
/**
 * Theme a link tag.
 */
function YOURTHEMENAME_link($variables) {
  // If we are on a term page.
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2)) {
    // The easiest way to check all possibilities, like absolute & relative
    // paths and path aliases and real paths is to compare via the url function,
    // which will normalise all this stuff.
    if (url($variables['path'], array('absolute' => TRUE)) == url($_GET['q'], array('absolute' => TRUE)) {
      // Add the class to the link definition so that it will be
      // added to the rendered link.
      $variables['options']['attributes']['class'][] = 'your-class-goes-here';
    }
  }

  // Print the link as usual.
  return '<a href="' . check_plain(url($variables['path'], $variables['options'])) . '"' . drupal_attributes($variables['options']['attributes']) . '>' . ($variables['options']['html'] ? $variables['text'] : check_plain($variables['text'])) . '</a>';
}

```

After adding this function to your template.php you will have to clear the drupal cache for it to take effect.

Note that if your theme or any modules print links without using the l() function or theme('link') or similar then it won't be affected by this.

If you have user entered content that has these links in them then they will also not be affected by default. The easiest way to make it so they are also handled is to enable and configure the pathologic module.

The other option is javascript, but that is not ideal as it isn't really necessary in this case and doesn't work for users that don't have javascript.

In that case you need to include your script on the taxonomy/term/% pages only (see drupal\_add\_js()), then in the script check for the current page matching any link hrefs and add the class.

# Answer
> 0 votes
Thanks Rooby, I did it with jquery.

`$('li').each(function(){
 if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
 {`

````
    $(this).addClass('activelink').siblings().removeClass('activelink');

    }
});

````

---
Tags: taxonomy-terms
---


# Question
Title: How to integrate a custom one page php app into drupal 7?
I am trying to integrate a custom website into the drupal 7 system. On this website there is a lot of user interaction with buttons, database queries, ajax loaded elements, … . I need to get the the global user variable on this page.

My first question: What is the best way to integrate the webpage?

My first attempt was to create a content type (node—myPage.tpl.php): I got permission problems using ajax, so I separated the code into two files (node—myPage.tpl.php and myPage.php). In the node—myPage.tpl.php I only included myPage.php. But now I have the next problem using ajax (for myPage.php). I cannot get my global user variable.

My second attempt was to create a custom module. So I created a callback page. But I think I have to make a renderable array. I want to avoid this because myPage.php has over 3000 lines of code. And I don’t think jquery ajax will work as it should.

Is there an easy way to integrate a custom website into the drupal 7 system with access to the drupal api (user variable, functions)? I also prefer to keep the custom page in a php file, not into database.

# Answer
The way you are supposed to do it, is to create a module, with proper `hook_menu` and all that. That's the only way to really plug your script into Drupal routing system. And you don't need renderable arrays, if you are OK with quick and dirty job, your functions may return strings, too. If in doubt, just see Examples for Developers project, it has it all documented pretty well.

**You may do the other way around.** Drupal's standard .htaccess is set up the way that makes Apache execute any php file that is there, and only if there is no file it makes Apache to call Drupal's index.php. So instead of integrating your one-page app into Drupal, you may bootstrap Drupal into your one-page app. It was already asked and answered here, so I don't think it's worth to repeat all of it. Key point is, that with this code:

```
/**
 * Initialize Drupal
 */
define('DRUPAL_ROOT', '/var/www/clients/client1/web15/web');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
require_once DRUPAL_ROOT . '...'; // include required module files to work with here

drupal_override_server_variables(array('url' => 'http://www.example.com/batch.php')); // trick drupal to do bootstrap
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

set_time_limit(4600); // adjust for your needs
ini_set('memory_limit', '3524M'); // adjust for your needs

```

at the beginning of your one-page php file, you can assess Drupal data and functions all you want, but avoid Drupal routing and render flow.
> 1 votes

# Answer
A custom module with a menu callback is the way to go. In general, themes and tpl.php files should only control what your site looks like. Modules should control what your site does.

I understand that you don't want to refactor your code completely and turn everything into render arrays. Fortunately, you don't have to. You can create a string of html and put it in a render array like this:

```
// Generate your html.
$html = '<p>Hello world!</p>';
// Wrap it in a render array.
$output = array (
  '#markup' => $html,
);

```

Now, this is the really simple version. I do recommend that you take advantage of some of Drupal's features.

First of all, if you didn't already do so, I would create separate menu callbacks for the ajax requests. If both the rendering of the page and the ajax requests are handled by the same menu router, you might get in trouble when Drupal starts caching things.

Second, I would take add all javascript (and possible css) to the page using the `#attached` property of your render array. This also allows Drupal to cache (parts of) your page without breaking things. Assuming that your module is called "mymodule" and your javascript is stored in mymodule.js, your render array could look like this:

```
$output = array (
  '#markup' => '<p>Hello world!</p>',
  '#attached' => array(
    'js'      => array(
      drupal_get_path('module', 'mymodule') . '/mymodule.js',
    ),
    // If your output requires certain CSS rules, regardless of the theme
    // that is used, add a CSS file like this.
    //'css'      => array(
    //  drupal_get_path('module', 'mymodule') . '/mymodule.css',
    //),
  ),
);

```
> 5 votes

---
Tags: ajax, 7
---


# Question
Title: Using hook_user submit and after_update in the same module
Extending from this question (I am now using devel, and know that I need to compare r.rid in my logic), I am trying to place a query into my drupal 6 module, that checks that a certain role has been selected prior to save. if `after_update` will push these details to an external database. `else` the normal drupal functionality will be the only function.

My code looks like the below, with the bottom hook\_user working correctly. If I place the first hook\_user (submit) into my module I start getting internal server errors.

Any suggestios?

```
 function assigncoordinator_user($op, &$edit, &$account){
 switch($op){
 case 'submit':
       drupal_set_message(t('Legend worked'), 'error');
    }
   }

function assigncoordinator_user($op, &$edit, &$account, $category = NULL){
 switch($op){
 case 'after_update':
  //The rest of my code.......................

```

**Extra info**

```
If (r.rid = 25) { //How to I check this

function assigncoordinator_user($op, &$edit, &$account, $category = NULL){
 switch($op){
 case 'after_update':
  //The rest of my code.......................
 }
 }
 } else {
 //do nothing
 }

```

# Answer
PHP does not allow multiple functions with same name. That's the point of the `case` statement there. Instead of

```
 function assigncoordinator_user($op, &$edit, &$account){
 switch($op){
 case 'submit':
       drupal_set_message(t('Legend worked'), 'error');
    }
   }

function assigncoordinator_user($op, &$edit, &$account, $category = NULL){
 switch($op){
 case 'after_update':

```

you should:

```
function assigncoordinator_user($op, &$edit, &$account){
  switch($op){
    case 'submit':
      drupal_set_message(t('Legend worked'), 'error');
      break;
    case 'after_update':
      // Your other code
      break;
  }
}

```
> 3 votes

---
Tags: 6, hooks
---


# Question
Title: Using taxonomy hierarchy in Views arguments
I'm building a store with products organized with a hierarchal taxonomy. I'd like the paths for Views showing products to reflect the taxonomy hierarchy. For example, `products/category-a/subcategory-a`, `products/category-b`, etc. (In this case, products will only be a member of one category/term at a time, and terms will either have child terms or products associated with them, but not both - with the example paths above, `products/category-a` would list the child terms of the Category A term, but no products.)

I can build a view with a path like `products/%`, and that works just fine with `products/category-b`, but I can't figure out how to get that working with `products/category-a/subcategory-a` \- it throws a 404. I've thought of implementing a Views alter hook to alter `$args` to only use the last argument, but the 404 is happening from a failure in `menu_get_item()` \- before any Views code has a chance to run (and call alter hooks).

I can't think of any other pleasant ways to work around this, but surely I'm not the first one to want to try to implement a catalog like this… What's the most correct way to do it? (Ugh, I feel like such a site-builder n00b.)

# Answer
2 ways to approach this:

## Option 1: Custom module (preferred)

If you don't mind coding:

First, you'll need to create a view with a term contextual filter. It is also important to add "Has taxonomy term ID depth modifier" filter. This will ensure that if you pass the parent term ID, all items that are tagged in any of the parent's child terms will be included in the result.

Your custom module will have to do a few things to make this work:

1. Define menu items using the top-level terms. The menus will also accept child terms (sub-category) as **optional** parameters. In essence, you are defining menu items to be in this pattern - `products/<category_id>/<[sub_category_id]>`. Where `sub_category_id` is an optional parameter.
2. Define a menu callback which programmatically embeds the view. If the sub-category is not available, use the parent in generating the view. If the sub-category is available, use that instead.

*Sample code:*

```
<?php

/**
 * Implements hook_menu().
 */
function example_menu() {
  $items = array();

  // Define the menu for each top-level category. Each menu will have an
  // optional parameter that can contain the sub-category (a term under
  // the parent category).
  foreach (example_product_categories() as $tid => $term) {
    $items['catalog/'.$tid.'/%'] = array(
      'type' => MENU_CALLBACK,
      'page callback' => 'example_product_catalog_page',
      'access callback' => TRUE,
      'page arguments' => array($tid, 2),
    );
  }

  return $items;
}

/**
 * Page callback to generate the product catalog view.
 *
 * @param $parent
 *   The tid of a top-level product category.
 * @param $child
 *   A n-tier level of a product category.
 */
function example_product_catalog_page($parent, $child = NULL) {
  // @todo: Optional. Check that $child is a term under $parent.

  // If $child is defined, we use that to generate the product catalog.
  if ($child) {
    return views_embed_view('product_catalog', 'product_catalog_page', $child);
  }
  else {
    // If $child is not defined, we use the $parent to generate the product
    // catalog. This will also show all records tag in any of the parent's
    // child terms.
    return views_embed_view('product_catalog', 'product_catalog_page', $parent);
  }
}

/**
 * Returns an array of top-level product categories (terms) keyed by the tid.
 */
function example_product_categories() {
  $product_vocabulary = '<VOCABULARY_NAME>'; // The name of the vocabulary
                                             // that contains the categories.
  $categories = array();

  // Load the vocabulary using the name to get the vocabulary ID.
  // If you know the vocabulary ID, you can skip the loading of the vocabulary
  // object and proceed directly to the loading of the taxonomy tree.
  if ($vocabulary = taxonomy_vocabulary_machine_name_load($product_vocabulary)) {
    // Load a taxonomy tree with only the top-level terms.
    $categories = taxonomy_get_tree($vocabulary->vid, 0, 1);
  }

  return $categories;
}

```

## Option 2: 2 Views

This would involve creating:

* 2 views, each with a page, or
* 1 view with 2 pages

The trick is to define 1 page that will accept 1 parameter only and another page that will accept 2 parameters. For the page that will accept 2 parameters, you can choose to ignore the 1st parameter or put in some validation (e.g. taxonomy validation).

## Another option: Combination of modules

Although I haven't tried this, you might want to look at a combination of the following modules:

I would imagine that this will take some custom codes particularly in creating a custom taxonomy path, which would involve implementing hook\_taxonomy\_menu\_path(). The end-goal is to create a custom taxonomy path which would take the form of `products/<parent-tid>/<[child-tid]>` if the term has a parent or `products/<parent-tid>` if the term doesn't have a parent. The custom menus will then point to a custom view or views.
> 2 votes

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


# Question
Title: Should I use content-types or database abstraction layer?
I am building an admin site for my brother's property management company. The design seems pretty straight forward.

I need a database with tables to store:

Estates. Each estate has a number or properties (flats or houses). Each property has a number of charges (service charge, water bills, maintenance ect.)

Then I have: Owners. Each Owner must have ONE or MORE properties. Owners make payments. Each payment is allocated to ONE or MORE charges.

From there I add CRUD functionality and the ability to produce reports by estate, property and/or owner.

Being new to Drupal I originally thought that the way to do this is create a content-type for each of the tables (e.g Estate, property, charge, owner, payment) and then use the relations module to enforce any foreign keys and automatic additions and update.

However, I have spent this week reading pro drupal development 7 and now I see I can build the database using the schema module and add functionality through the database abstraction layer with the functions declared in `database.inc`.

Does anyone have an opinion on which is the best way forward? Or am I missing the point a bit? Do I use them both?

Thanks for any advice and Merry Christmas (or Happy Holidays, whichever you prefer)

# Answer
Reasons you should go with content type.

* Its is what you get out of box from drupal, content type are built on drupal entity concept,lot of api's are exposed to alter the default workflow in case needed,internally it does the same that you can do with custom tables,a lot of contributed modules are there to extend the functionality.
* If you are planning to have custom tables then you have to write codes at each point of three layers -tables creation, data insertion/updation, data view,while using content type you can get it done by drupal core and by using some of contributed modules for example to show different data you can use views.

Following modules can be helpfull for the functionalities listed above.

1. views.
2. entityreference

Things you need to plan Try to categorize the listed (Estate, property, charge, owner, payment) into entities and their properties for example charge might not be a separate entity instead it might be a property(field) of property(content type). So roughly you can have Estate,property as content type. Once you install entityreference module, it will allow you to setup reference from property to estate using reference field(provided by entity reference module).So setting up reference you can establish relationship of what property nodes belong to what estate nodes.Charge can simply a field on property content type, so it will show charge/cost for a property node.Owner can be nodes or if you allow login to owner you can make theme drupal users as well.Again you can setup by relationship between property and owner using reference field in both ways keeping it as users or as node.

I hope this might be helpful in starting,Merry Christmas :)
> 2 votes

# Answer
Here is a link to a comment that answers the question I asked. It backs up what arpitr outlined in their answer above.

https://drupal.org/comment/7848011#comment-7848011

I will implement my system using node entities until the need arises to build a custom entity (if it ever does).

The top answer in this forum give a good way to evaluate whether to use nodes or custom build an entity:

When is it appropriate to create an Entity versus just adding a new content type?
> 1 votes

---
Tags: nodes, database
---


title: Views: get image-field with global php

text:
# Question
Title: Views: get image-field with global php
im using Drupal 7 and views 3.

in a global-php-field i tried to show the image from field\_artengalerie\_term\_bild. But

`print $row->field_artengalerie_term_bild;` shows the nid only. then i tried this:

```
print $data->field_field_artengalerie_term_bild[0]['rendered'];

```

but it doesnt output the image.

With `print_r($data);` i get this:

```
 [vocabulary_machine_name] => artengalerie [field_artengalerie_term_bild] => Array ( ) ) ) ) [field_field_artengalerie_term_bild] => Array ( [0] => Array ( [rendered] => Array ( [#theme] => image_formatter [#item] => Array ( [fid] => 648 [uid] => 1 [filename] => standardbild.jpg [uri] => public://default_images/standardbild_7.jpg [filemime] => image/jpeg [filesize] => 19607 [status] => 1 [timestamp] => 1369566211 [type] => image [field_file_image_alt_text] => Array ( [und] => Array ( [0] => Array ( [value] => standardbild_7.jpg [format] => [safe_value] => standardbild_7.jpg ) ) ) [field_file_image_title_text] => Array ( ) [image_dimensions] => Array ( [width] => 400 [height] => 266 ) [is_default] => 1 [alt] => [title] => ) [#image_style] => thumbnail [#path] => Array ( [path] => taxonomy/term/118 [options] => Array ( [entity_type] => taxonomy_term [entity] => stdClass Object ( [tid] => 118 [vid] => 10 [name] => hjgjhghg [description] => [format] => [weight] => 0 [vocabulary_machine_name] => artengalerie [field_artengalerie_term_bild] => Array ( [und] => Array ( [0] => Array ( [fid] => 648 [uid] => 1 [filename] => standardbild.jpg [uri] => public://default_images/standardbild_7.jpg [filemime] => image/jpeg [filesize] => 19607 [status] => 1 [timestamp] => 1369566211 [type] => image [field_file_image_alt_text] => Array ( [und] => Array ( [0] => Array ( [value] => standardbild_7.jpg [format] => [safe_value] => standardbild_7.jpg ) ) ) [field_file_image_title_text] => Array ( ) [image_dimensions] => Array ( [width] => 400 [height] => 266 ) [is_default] => 1 [alt] => [title] => ) ) ) ) ) ) [#access] => 1 ) [raw] => Array ( [fid] => 648 [uid] => 1 [filename] => standardbild.jpg [uri] => public://default_images/standardbild_7.jpg [filemime] => image/jpeg [filesize] => 19607 [status] => 1 [timestamp] => 1369566211 [type] => image [field_file_image_alt_text] => Array ( [und] => Array ( [0] => Array ( [value] => standardbild_7.jpg [format] => [safe_value] => standardbild_7.jpg ) ) ) [field_file_image_title_text] => Array ( ) [image_dimensions] => Array ( [width] => 400 [height] => 266 ) [is_default] => 1 [alt] => [title] => ) ) ) )

```

how i have to write my code `print $data->field_field_artengalerie_term_bild[0]['rendered'];`to get the image.

regards

# Answer
> 2 votes
I had the same problem and very simple solution for it I found just need in output write

```
 print render($data->field_field_artengalerie_term_bild);

```

always my solutions is shortest ;)

---
Tags: views
---


title: conflict with search module

text:
# Question
Title: conflict with search module
I have a problem about conflict a custom search form with search module. in custom form custom search interface provided ,the codes of form and submit show in below, when the search module is disable this form work correctly but when the search module this is not work and only just redirect to /search/node. I don't find out where is the problem,any body can help me about this problem ?

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

    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'taxonomy_term')
                            ->propertyCondition('vid', 2)
                            ->propertyOrderBy('weight', 'ASC');
    $result = $query->execute();
    $cats = entity_load('taxonomy_term', array_keys($result['taxonomy_term']));
    $flower_types['All'] = t('Choose by Category');
    foreach($cats as $index => $cat)
        $flower_types[$index] = t($cat->name);
    $form['field_flower_type_cat_tid'] = array(
        '#type' => 'select',
        '#options' => $flower_types,
        '#default_value' => $_GET['field_flower_type_cat_tid'],
    );

    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'taxonomy_term')
                            ->propertyCondition('vid', 3)
                            ->propertyOrderBy('weight', 'ASC');
    $result = $query->execute();
    $cats = entity_load('taxonomy_term', array_keys($result['taxonomy_term']));
    $ocassion['All'] = t('Choose by Occasion');
    foreach($cats as $index => $cat)
        $ocassion[$index] = t($cat->name);
    $form['field_ocassion_tid'] = array(
        '#type' => 'select',
        '#options' => $ocassion,
    '#default_value' => $_GET['field_ocassion_tid'],
    );

    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'taxonomy_term')
                            ->propertyCondition('vid', 6)
                            ->propertyOrderBy('weight', 'ASC');
    $result = $query->execute();
    $cats = entity_load('taxonomy_term', array_keys($result['taxonomy_term']));
    $colors['All'] = t('Choose by Color');
    foreach($cats as $index => $cat)
        $colors[$index] = t($cat->name);
    $form['field_color_tid'] = array(
        '#type' => 'select',
        '#options' => $colors,
    '#default_value' => $_GET['field_color_tid'],
    );

    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'taxonomy_term')
                            ->propertyCondition('vid', 4)
                            ->propertyOrderBy('weight', 'ASC');
    $result = $query->execute();
    $cats = entity_load('taxonomy_term', array_keys($result['taxonomy_term']));
    $flower_names['All'] = t('Choose by Flower');
    foreach($cats as $index => $cat)
        $flower_names[$index] = t($cat->name);
    $form['field_flower_name_cat_tid'] = array(
        '#type' => 'select',
        '#options' => $flower_names,
        '#default_value' => $_GET['field_flower_name_cat_tid'],
    );

    $form['price_range'] = array(
        '#type' => 'select',
        '#options' => array(
            'All' => t('Choose by price'),
            '1' => t('Less than $25.00'),
            '2' => t('$25.00 to $50.00'),
            '3' => t('$50.00 to $75.00'),
            '4' => t('$75.00 to $100.00'),
            '5' => t('$100.00 to $150.00'),
            '6' => t('Over $150.00'),
        ),
    '#default_value' => $_GET['price_range'],
    );

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

    return $form;
}

function floristdev_search_filter_form_submit($form, &$form_state) {
    $query = array(
            'field_flower_type_cat_tid'=> $form_state['values']['field_flower_type_cat_tid'],
            'field_ocassion_tid'=> $form_state['values']['field_ocassion_tid'],
            'field_color_tid'=> $form_state['values']['field_color_tid'],
            'field_flower_name_cat_tid'=> $form_state['values']['field_flower_name_cat_tid'],
            'price_range'=> $form_state['values']['price_range'],
            );

    $form_state['redirect'] = url('search',
        array('absolute' => true,
        'query' => $query,
        )
    );
}

```

# Answer
> 3 votes
As you are redirecting `form` submission to `search` page and same url `search` exist in `search` module, so both module are conflicting with each other.

You should use a different URL for your module or you should alter `menu callback` for `search` page with your function.

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


title: Specific URL routing

text:
# Question
Title: Specific URL routing
I have a custom taxonomy for my posts called "Continents" and they could be:

Europe, Africa, Antarctica etc...

Then I have standard categories like: News, Reviews, Interviews etc.

And 1 subcategory for some categories e.g. for News I have subcategories like (entertainment, politics, sport, science etc.)

My question is how to set up URL permalinks in Drupal, so I have these types of links for "categories":

```
http://example.com/africa/news/politics
http://example.com/europe/reviews
http://example.com/antarctica

```

but at the same time I need to access things like:

```
http://example.com/news/politics

```

that will include everything from these categories and not taking care of the Continents taxonomy item.

And at that same time I need to access the posts (details) like:

```
http://example.com/2013/12/17/conflict-in-kongo-continues

```

Could that be done via Drupal or not?

# Answer
# Summary

I think you just need a couple of different views to create most of the functionality, but because the continent paths do not leave space for a path argument to call the view (eg example.com/viewname/africa/...), you might need to either duplicate the view with several displays or use some .htaccess mod\_rewrites to point continent names at the view.

I have inserted a + into the first path (I hope that is alright?)

# Suggestions

## view: terms\_by\_continent

> http://example.com/africa/news+politics
>
> http://example.com/europe/reviews
>
> http://example.com/antarctica

are presented by a view called *terms\_by\_continent*, with a contextual filter on **term:name**, accepting multiple arguments and defaulting to 'show all'. Create a different 'page' display for each continent so you can change the path to simply, for example, `africa`

## view: terms\_by\_category

> http://example.com/news/politics

would be a view called terms\_by\_category. The namespace is a bit difficult here because, unlike continents, I would guess this vocabulary might be subject to change, so creating multiple views displays would be tiresome and prone to error. If you are able to insert another path component then this becomes easy, ie `category/news/politics` would be served by a view of nodes with a contextual filter as above.

Multiple terms would normally be seperated with a `+` or similar, but if you needed to use `/` (ie news/politics) you could do a mod\_rewrite on `category/*` to make this presentable

If you could not afford to add the category path component then I would guess you are stuck with using views displays as in *term\_by\_continent* to claim the paths that match each of your terms, accepting arguments for additional terms.

## node: custom path

Finally:

> http://example.com/2013/12/17/conflict-in-kongo-continues

This is the actual path to a specific article (node), so path auto is definitely the way to go. It will allow you to use *tokens* to construct your path for the appropriate content type, using date components and title.

## Other solutions

I had a couple of other suggestions:

1. look at page manager, which might allow you to have greater control over paths for your views
2. you could try using pathauto for terms as well as nodes, and then replacing the term display with a view that accepted term:name as argument (as above), You could do this using term display or tvi

For option 2, I believe that (assuming there is not an existing page with this path), `africa/news/politics` for example, would not find a match, so would look for `africa/news`. Because that path also does not exist, it would fallback to `africa`, which (thanks to pathauto) takes you to the africa taxonomy term.

The term page contains a view, which accepts arguments (ie news/politics) and therefore you should get the appropriate listing. The view might need several displays which accept increasing numbers of arguments in order to allow the '/' seperated arguments, ie `view/%`,`view/%/%`, `view/%/%/%`
> 1 votes

# Answer
I don't have the exact answer but I think Organic Groups might be included in said answer. Using Views and filtering on the Taxonomy Term might work as well.
> 0 votes

# Answer
You should be able to do something like this just using views, tags and possibly panels (although I'm not really sure if its needed, but it will make things easier.)

Firsts off you could use tags for your continents. Also for your categories (although really anything you can filter off of in views should work, but the tags for continents could make it organic).

Then, create a view with contextual filters for the continent tag. If you create a pannel page at /%continents, then you can out put the view as content pane. That will give you pane settings in the view, and you can set the argument input (for your contextual filters) to come from the panel. If you have it use the /%wildcard as the argument, that should give you a list of nodes from tagged with North America, for instance.

You could then add another view with 2 contextual filters, one for the continent tag, and the other for the category type. You could then create a panel variant based off of the /%continents page, only with /%continents/%categories as your wildcards, and set things up similarly to how the first one was set up, that should allow ether /%continents to work or /%continents/categories to work.

http://www.webbykat.com/2012/02/creating-monthly-archive-block-drupal-7-views Here's a blog post I found which goes over how to create a block and views blog monthly archives, which really isn't too far off of what your trying to do (months/years will always increase, so they need to be created as needed, similar to your continents, it's just another way to filter posts)
> 0 votes

---
Tags: uri
---


# Question
Title: Commerce - How do you setup conditional shipping options that relate to a specific taxonomy term?
My store sells heavy and lightweight widget items. I currently have 1 product type and have 1 term reference field that designates it as either **light weight** or **heavy weight**

Now in my flat rate shipping setup. I have 2 flat rate prices. One for light and heavy. I add a condition to each of these shipping methods to check if its either a **light** or **heavy** object, but I'm not sure how I can retrieve these taxonomy references in the rules setup of the component. I would imagine i would have to do a commerce\_order:line-item, but after that im stuck and not sure where to go to grab the taxonomy terms.

# Answer
In addition to Nigel's answer, the modules we would need to use is this:

https://drupal.org/project/commerce\_rules\_extra

Its a more upto date and maintained module than extra\_rules\_condition

Here's a screen shot of what gets added on the **add component** option in the rules dropdown. From this:

**To this:**
> 2 votes

# Answer
Use the Commerce Extra Rules Condition module:

The module adds additional Rules conditions related to Drupal Commerce.

It currently adds:

> - A condition for checking if a line item references a product with a specified Taxonomy term applied to it.
> - A condition for checking if a line item references a product with specified Taxonomy terms applied to it.
> - A condition for comparing the quantity of products in an order with a specified Taxonomy term applied to them against a specified value.
> - A condition for comparing the quantity of products in an order of a specified product type or checking the quantity of products in an order excluding a specified product type.
> 2 votes

# Answer
A friend of mine had the same problem half year ago. I created a simple module that allowed you to select terms out of taxonomy vocabs and use them for conditions.

The module checks the taxonomy terms in both the commerce product and the node attached to the commerce product.

commerce taxonomy conditions
> 0 votes

---
Tags: 7, rules, commerce, database
---


# Question
Title: Displaying a list of all the content types
I need to display a list of all the content types which links to their respective page, displaying the contents of that type.

I tried a bunch of wild guesses like $row-\>content and couldn't manage.

How should I achieve this?

# Answer
I have done something similar using *Views* and the *Summary* option for *Contextual filters*. I added the Content Type as a contextual filter with the following options:

The end result was a view that displays the following, if you have not specified a Content Type in the URL as an argument:

The only issue I found is that I won't display *Content Types* that have no content.
> 1 votes

# Answer
You can probably extract the content types from the node entities (in code they are called bundles). But then you'll never know if there is a dedicated page for them. Therefor I'd recommend taking the following approach:

I'd create a new menu for this. Then make views pages for all the content types and in the views settings add the page to the menu. A little bit more work, but more control.

The menu can then be displayed in a sidebar, or other place.
> 0 votes

# Answer
create a view for every content type that lists all the contents of that type. now create a web page and make a link for every view.
> -1 votes

---
Tags: views
---


# Question
Title: Set a token as the default value of a new field
In Drupal 7, you can set defaults values for most fields. Is it possible to set a token as the default value.

I remember this being possible in Drupal 6, but it doesn't seem possible in Drupal 7.

There is a thread here that discuss the possibility, but its not clear if it was solved.

# Answer
> 1 votes
What information do you try to get??

In one of my Content Type, I need to retrieve the node ID. I found that the token for the current node ID is this:

```
[current-page:url:args:last]

```

Tested and working for me!!

# Answer
> 0 votes
It is working for me:

```
/**
 * Implements hook_field_widget_form_alter().
 */
function MODULE_hook_field_widget_form_alter(&$element, &$form_state, $context) {
  // Prevent replace tokens on field admin ui form.
  if (!is_null($element['#entity'])) {
    // Determine the $user. If entity has uid, try to load. If can't, use the
    // global $user.
    if (isset($element['#entity']->uid)) {
      if (!$user = user_load($element['#entity']->uid)) {
        global $user;
      }
    }

    // Build data for token replacement.
    $data = array(
      $element['#entity_type'] => $element['#entity'],
      'user' => $user,
    );
    // Eg. the body field, the default value is stored in
    // $element['#default_value']
    if (isset($element['#default_value']) && !is_array($element['#default_value'])) {
      $element['#default_value'] = token_replace($element['#default_value'], $data);
    }
    // Eg. the link field, the default value is stored in
    // $element['#default_value']['url']
    else if (is_array($element['#default_value'])) {
      foreach ($element['#default_value'] as $key => $value) {
        if (is_string($value)) {
          $element['#default_value'][$key] = token_replace($value, $data);
        }
      }
    }
    // Eg. the text field, the default value is stored in
    // $element['value']['#default_value']
    else if (isset($element['value'])) {
      if (isset($element['value']['#default_value']) && !is_array($element['value']['#default_value'])) {
        $element['value']['#default_value'] = token_replace($element['value']['#default_value'], $data);
      }
    }
  }
}

```

# Answer
> -2 votes
Install the Field default token module.

> This module enables to use tokens as field default values. The main discussion: #1070878: Allow tokens to be used in the default value of a field.

---
Tags: 7, entities, tokens
---


# Question
Title: How can I see full server request to track suspicious requests?
I have very bad luck with spammers. Even though I employ both reCAPTCHA, Spamicide and BOTCHA, I get about one spammer per day, though 300 are blocked. I guess that's a pretty good ratio, but it still justifies me having to manually authorize new user accounts.

My website gets about 30K requests per day (as per access logs) of which 500 are POST requests. It runs on Drupal 6, though we are soon moving to 7.

I want to be able to see what the spammer sends when they make the request. Ideally, I would like to see the reCAPTCHA challenge they saw and what they wrote down. I'll be good with only the postdata, though.

Is there a way to achieve this using triggered rules? Is there a module which will allow me to do so (i.e. send the full request to log/email?)

# Answer
> 1 votes
I can't think of a module that would do this for all the different anti-spam modules. I know that the CAPTCHA module implements this for its own fields.

An alternative is a simple custom module that implements hook\_form\_alter to target the the desired form, adds a new submit handler to the form and store the submitted information using watchdog.

# Answer
> 0 votes
This is not a general solution, but it works under the configuration specified.

BOTCHA has a logging option which also logs server variables (under /admin/user/botcha, 'Log Level'). What's more, it will log the post data, so you can get both the reCAPTCHA challenge code and response.

---
Tags: rules
---


# Question
Title: Is the Drush backend API a web-accessible API? How does one install it?
I've successfully configured Drush 4.5 to work agains my Drupal 6 site from the command line using site aliases. I am doing things like sql-sync and rsync successfully from the command line. What I'd like to do now is expose these functions over the web, through an API. The Drush documentation leads me to believe I can do this, however it is somewhat lacking in details on how to accomplish this, or indeed whether it's even part of the intended design.

There is a very high chance that I have completely misunderstood the documentation and have assumed a CLI-only API was designed to be available through the web. However, the backend.inc file talks about a REST API accessible over HTTP and is ambiguous about what this API actually does.

> This is nearly a RESTful API. @see htp://en.wikipedia.org/wiki/REST
> Instead of "http://\[server\]/\[apipath\]/\[command\]?\[arg1\]=\[value1\],\[arg2\]=\[value2\]" it will call "\[apipath\] \[command\] --\[arg1\]=\[value1\] --\[arg2\]=\[value2\] --backend"

It's not clear to me what this actually means, because it says "instead of" the web call, but then goes on to describe how GET and POST arguments differ and how they are passed in from a web call.

> If the Drush API is meant to be called over the web, e.g. http://server.com/drush/drush.php/drupal-directory?argv1=@staging how do I enable this, given that Drush is in a separate PHP source tree? Do I symlink to it from my Drupal directory? Do I copy or symlink an include file and expect Drupal to pick it up?

# Answer
> 4 votes
As the previous respondents said, drush is a cli tool. If you would like to invoke Drupal functions via web services, try the services module. If you would like to manage multiple Drupal sites via a web ui, try aegir.

If you would like to call drush functions remotely from php: `$values = drush_invoke_process('@alias', 'drush-command', $args_array, $options_array);`

See `examples/example.aliases.drushrc.php` for examples on how to make an alias record. Instead of '@alias', you can also pass in an array containing the site record definition, or you can use `username@myserver.com/path/to/drupal#mysite.com`. See the source code comments in drush for an explanation of drush\_invoke\_process, and the contents of the $values array.

# Answer
> 3 votes
According to the comments/functions at the top of drush.php it's a CLI only tool. It evens goes so far as to kill the script if it's not accessed specifically via the command line.

```
if (!drush_verify_cli()) {
  die('drush is designed to run via the command line.');
}

...

function drush_verify_cli() {
  return (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0));
}

```

# Answer
> 3 votes
My understanding of the documentation in Drush's `backend.php` is that it compares Drush `--backend` with a REST server to explain its behavior. Drush is not a web application or a REST server and is CLI only.

Since version 3, Drush support direct execution of commands on remote host over SSH:

```
drush username@myserver.com/path/to/drupal#mysite.com status

```

# Answer
> 1 votes
This module could provide a web-accessible API for Drush, though it does not use the backend API: https://drupal.org/project/drushweb

---
Tags: drush
---


title: How to use Drush in remote server?

text:
# Question
Title: How to use Drush in remote server?
I'd like to use drush methods in the remote server. As far as I know I have to install Drush in the remote server. But my server provider tell me that Drush has many conflicts with other modules that the server is already running. How do you manage to use Drush in remote server? Is my server provider answer acceptable?

# Answer
> 4 votes
If you've any SSH access you can install Drush by yourself. Simply download the tar.gz from drupal.org and untar it into a folder on your server. Then you may add execution rights to `drush/drush` and you will able to use Drush perfectly (simply you just need to add all path before the command, for example `/var/www/drush/drush updb`).

Like others said, you should ask more informations about the conflicts and tell them that it's totally absurd that Drush create conflicts with other modules as it's require only php-cli.

I already installed `drush` on some servers and even on shared server and it works perfectly as you've SSH access.

# Answer
> 7 votes
It is possible to use Drush with a Drupal site that is running on a remote server that does not have Drush installed. This is possible because the Drush commands `drush rsync` and `drush sql-sync` work by composing ssh commands; if you set up your site alias configuration carefully, then you can copy your site to a local machine to operate on it.

In order for sql-sync to work without Drush on the remote system, you must define the 'databases' and '%dump-dir' variables in your site alias. Otherwise, Drush will try to use Drush on the remote system to look up these values. See example.aliases.drushrc.php for more information.

Note that it is really useful to be able to at least run `drush updatedb` on the remote server, so that you can update your database after you rsync new code over. Of course you can do this through the GUI too, but Drush is faster. The Resources page on drush.org lists some hosting providers that are Drush-friendly.

# Answer
> 0 votes
Alternatively this module may allow you to use Drush on a remote server without asking your host provider to install it: https://drupal.org/project/drushweb

Some details from the module's project page:

> This module allows to run Drush without being granted access to the machine it relies on. It may be useful on shared hosts that do not provide SSH access to servers.

---
Tags: drush
---


title: add a menu in a field

text:
# Question
Title: add a menu in a field
Does anyone know if there is a custom field type that allows you to assign a menu inside of the field? What I would like to do is add a list menu inside of the body field. I know I could do it manually through html but I would rather add it as a menu type.

# Answer
> 0 votes
My suggestion to you is use `list` as type and select list as widget then in select list value add something like below :

```
<a  href="#">link1</a>|<a  href="#">link1</a>
<a  href="#">link2</a>|<a  href="#">link2</a>
<a  href="#">link3</a>|<a  href="#">link3</a>

```

and after node saved it is completely link .

# Answer
> 0 votes
Assuming you are using Drupal 7.

You could try to embed the menu field module. Add it to a content type and then to a piece of content. Finally clear the cache (or you won't see anything).

---
Tags: routes
---


# Question
Title: Issues with a trigger module ("beep"). Module is not updating or changing labels in the hook_action_Info() hook
i'm learning Drupal and was going through this text book to do so: "Pro Drupal 7 Development by Todd Tomlinson".

Chapter 3 of the book teaches readers about hooks actions and triggers. It does this by taking you through the steps of creating a module called beep that involves making a function that implements hook\_action\_info() to write the word Beep! to log when an event takes place.

The issue I am having is that I can enable the module in the module page and once I do it works and i see the label 'Beep annoyingly' as a selectable option but when I change the label to something else like 'Beep elegantly' it doesn't change. Nothing is updating and it just stays as Beep annoyingly every time. Am I missing something? I've cleared the caches and everything too. I was thinking it might be a simple PHP syntax error but i cannot find it and have been struggling over this for some time now.

I've provided the code below. You should be able to make a module yourself with this. I'd provide the files themselves but I don't see a way to do that in this forum. Can anyone else get the labels to change? If your awesome enough to try this. make sure you have the triggers module enabled first. Thanks!

For the beep.module file:

```
<?php
/**
 * @file
 * Provide a simulated beep.
 */
function beep_beep() {
  watchdog('beep','Beep!');
 }
/**
 *Implementation of hook_action_info().
 */
function beep_action_info() {
  return array(
    'beep_beep_action' => array(
      'type' => 'system',
      'label' => t('Beep annoyingly'),
      'configurable' => FALSE,
      'triggers' => array('node_view', 'node_insert', 'node_update', 'node_delete'),
    ),
  );
}
/**
 * Simulate a beep. A Drupal action.
 */
function beep_beep_action() {
  beep_beep();
}

```

HERE IS THE CODE FOR THE beep.info FILE.

```
name = Beep
description = "Simulates a system beep."
package = Pro Drupal Development
core = 7.x
files[] = beep.module

```

# Answer
> 0 votes
The thing is that the system registers an action with the system name `beep_beep_action` and probably stores that in a cache. That way it's easier and faster to access the right function in your files. I've however not found that cache, nor a way to clear it.

There are three things you can do:

* Accept that all others who install your module will see it right.
* Rename `beep_beep_action` and `beep_beep_action()` to something else and you will register a fresh action.
* Open the database and find and remove the stored action. (But only if you know what you are doing.)

I'd go for the second approach.

---
Tags: hooks, rules
---


# Question
Title: 7: Form API: managed_file: AJAX upload error "Undefined index ... in file_ajax_upload()"
I have a problem with "AJAX: add more file fields". The Problem: i create new managed\_file field and add AJAX function "add more file fields". When i try to upload a file with first static file field, it works fine. But when use function "add more fields" and try to upload a file with AJAX created field, get error "Notice: Undefined index: ... in file\_ajax\_upload() (Line 262 in .../modules/file/file.module)."

All Answers for Similar Questions here don't solve this Problem.

The code:

```
<?php
/**
* implimentation of hook_form_alter()
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {

}

/**
* implimentation of hook_form_FORM_ID_alter()
*/

function mymodule_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
 // Since the form builder is called after every AJAX request, we rebuild
  // the form based on $form_state.
  $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;
  $form['howmany_select'] = array(
    '#title' => t('How many checkboxes do you want?'),
    '#type' => 'select',
    '#options' => array(
      1 => 1,
      2 => 2,
      3 => 3,
      4 => 4,
    ),
    '#default_value' => $num_checkboxes,
    '#ajax' => array(
      'callback' => 'ajax_example_autocheckboxes_callback',
      'wrapper' => 'checkboxes-div',
      // See ajax_example_autotextfields for an example of 'fade'.
      'effect' => 'fade',
      // Don't show any throbber...
      'progress' => array('type' => 'none'),
    ),
  );

  $form['checkboxes_fieldset'] = array(
    '#title' => t("Generated Checkboxes"),
    // The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
    '#prefix' => '<div id="checkboxes-div">',
    '#suffix' => '</div>',
    '#type' => 'fieldset',
    '#description' => t('This is where we get automatically generated checkboxes'),
  );

  for ($i = 1; $i <= $num_checkboxes; $i++) {
   $form['checkboxes_fieldset']["slideshow_item_$i"] = array(
    '#title'    => t('Image')." $i:",
    '#type'     => 'managed_file',
    '#required' => FALSE,
    '#upload_location' => file_default_scheme() . '://mymodule_images/',
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
    ),
    '#tree' => TRUE,
    '#description' => t("Upload slideshow image. Allowed extensions: gif, png, jpg, jpeg."),
   );
  }
  return $form;
}

function ajax_example_autocheckboxes_callback($form, $form_state) {
  $form_state['rebuild'] = TRUE;
  return $form['checkboxes_fieldset'];
}

?>

```

I think the Problem is in $form\_state. How i can refresh / rebuild $form\_state? In ajax\_example\_autocheckboxes\_callback i set $form\_state\['rebuild'\] = TRUE; but without effect :(

Code Test Video:

http://www.youtube.com/watch?v=PtRiQorCTA4

I looking 3 days for a solution :-/

Helpful articles:

How to add more Fields using Form Api

https://drupal.org/node/752056

https://drupal.org/node/331941

How to wrap managed\_file Form API element with custom HTML using #theme\_wrappers?

# Answer
OK, i have it!

The right way: "Submit button":

```
  $form['add_file_field'] = array(
                     '#type' => 'submit',
                     '#value' => t('Add one more'),
                     '#submit' => array('add_more_file_fields'),
                     '#ajax' => array(
                         'callback' => 'ajax_example_autocheckboxes_callback',
                         'wrapper' => 'ajax-generated-fields',
                     ),
                 );

```

Function, called after submit:

```
 function add_more_file_fields($form, &$form_state) {
   $form_state['values']['howmany_select']++;
   $form_state['rebuild'] = TRUE;
 }

```
> 0 votes

# Answer
You need to pass the parameters by reference if you want changes to persist outside the function scope:

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

```
> 1 votes

---
Tags: ajax, files
---


# Question
Title: How can I use Views to create a page with 3 Content Types, grouped by type, limited to x number of each type?
Sorry for the long title. Essentially what I'm looking for is the best way to create the standard News style list page, in which I might display something like the 3 most recent News Articles, Company Events and Press Releases.

The content would be grouped by content type so would essentially look like this:

```
News Header
News Item 10
News Item 9
News Item 8

Events Header
Event 10
Event 9
Event 8

Press Releases Header
Press Release 10
Press Release 9
Press Release 8

```

Seems like a common use case so I'm thinking (hoping) someone has done it before.

I've got it working up to the point of showing only x number of each content type, but can't seem to figure how to limit content without limiting just the overall number of items, not per Content Type.

Thanks a lot.

# Answer
> 3 votes
Here's a solution using only the Views UI.

* Create a view with the following master settings: display 3 items, sort post date descending with the node tile included in your fields. Probably as you have it already.
* Add a page or block display with type == News articles. This will be your parent view display. Again, you might have this already, but your type filter may need to be adjusted. We just want 3 news articles here.
* Add an attachment display with title as Events and update type == events. Attach this to your parent view display above.
* Add another attachment display with title as Press Releases and update type == press releases. Attach this to the parent view in the second bullet point above.

You can find the attachment to setting in the second center column on the views ui, assuming this Drupal 7.

Jason.

# Answer
> 1 votes
why do you try to do that in just one query?

Simply create a block view for each content type: News, Events, Press Releases. Add a header within each view block.

Then go to the blocks admin page, and define the correct settings to display your blocks wherever you need to.

---
Tags: views
---


# Question
Title: Using drush to run a local script on a remote site
I frequently use `drush scr` for little tasks throughout my day. Sometimes these end up a proper commands in my environment, but more often they are just standalone things.

If I have `@foo` set up in my drush aliases with `remote-host`, and try to run a local script, I get

```
$ drush @foo scr ./foo.php
Unable to find any of the following:                                     [error]
/home/mpd/drush/commands/core/./foo.php, /home/mpd/./foo.php

```

Can this command run a local script on a remote site?

# Answer
Nope, what you want to do is not supported. When you run `drush @foo scr`, it causes Drush to run your scr command on the remote system. The scr command on the remote system will then look for the script it wants to run on its own filesystem. In order to make this work, you'll need to somehow get your script on the remote system, and then run it with your remote scr command.

Note that this is different than the `drush php-eval` command, which takes the php code to run on the commandline. So, in theory, you could passing your php over on the commandline rather than in a file; however, in practice you may find this to be problematic due to the fact that bash is going to process your text, so you'll have to make sure that everything is properly escaped. Moving the script to execute to the target machine will be more reliable for any nontrivial script.
> 13 votes

---
Tags: drush
---


title: Can't get to /admin

text:
# Question
Title: Can't get to /admin
First time using Drupal. It's a friend's site that her former developer stopped hosting because he couldn't afford his server and gave her the public\_html zip and an .sql file on a flash drive, she gave it to me and I assumed it would be as simple as turning on mod\_rewrite, importing the database and uploading the files. I did this with ease, site displays fine except no form submissions of any kind work and the only console error I get is some cdn hosted file missing. After some reading, I go to http://dkmcosmetics.com/admin and I get a 403 access denied page, so then I go to http://dkmcosmetics.com/user/login and there's a login page, the form submission doesn't work on there either(just refreshes page after submission). Check folder permissions on the server, double check the settings.php, made sure there's no "cookie domain" and still no luck. Can anyone pinpoint where my problem may lay?

# Answer
> 0 votes
If the database dump they gave you is corrupt, or missing sensitive information (such as the users table), you may need to do some work.

Have you tried installing this "site" on a local environment first? You can, for example, download Drupal core from Drupal.org, install it as you normally would any Drupal site, and after making sure it works - you could: 1) copy the modules in the zipped or tarred file they gave you to your local install, and 2) import the database they gave you on top of the database you already installed successfully.

# Answer
> 0 votes
Adding a second answer. Do you have drush installed on the server? If not, you probably should ;)

Drush can help you with situations like this. You can do `drush status` on your site to double check your settings.php. You can also use `drush upwd` to change the password of the admin user, and `drush uli` to provide you with a one-time login link. If `upwd` or `uli` do not provide a fruitful result, then you may really have either a corrupt database (see my original answer) - or you simply may have server/LAMP issues (such as bad system permissions, Apache or PHP config issues, etc.)

---
Tags: forms
---


# Question
Title: field collection v seperate content types
For my property management admin application I want to assign charges of different types to the properties being managed (e.g. service charge, utilities bill, maintenance costs etc.). So each property on an estate will have many charges associated with it.

In my original spec I have a table for properties/flats and an table for charges that records a foreign key from the property table in order to associate a charge with a property.

New to drupal I implemented this by creating a content type for properties and a content type for charges with a entity reference field to record which property node is related to which charge node. Next I will look into building a form that allows me to fill fields from more than one node at a time and some code to grab the correct property and autofill the entity reference field when adding a new charge by selecting say. 'add charge' from a page that lists properties.

Now I have doubts. I could also create a field collection with all the fields required for a charge (type, amount, date, comment) and allow unlimited values for this field collection. As this field collection is stored as an entity, doesn't this do the same thing as above without having to use the entity reference field and so avoiding some of the coding? Also, if I wanted to add a charge to many apartments at the same time, wouldn't it be simpler using a field collection?

I am too new to drupal to understand the difference. I now it is related to what I want to do with the data after it is stored (it should be available for use in calculated fields, to be listed with data from other nodes, searched for by charge type, for instance) but I don't know how to know which is better without building it twice!

# Answer
Good question, but hard to answer. I can't tell you what to choose but I hope my thoughts will help.

If I understand your needs correctly, Field Collection definitely has some advantages. Firstly, field collections are purpose built to be related to other entities. Each field collection entity is always related to one (and only one) node. That seems so match your use case, although I wouldn't know how if it's easy to add multiple field collections to multiple nodes at once. In my experience, field collection provides a pretty smooth way for site maintainers to add new data, so that's good.

The downside of field collections is that many contrib modules are still node-centered. For every site you build, it's hard to predict which problems you will be solving or which features you will be adding 6 months after the launch. If you decide to use field collections, you may find yourself in a situation where you want to add something that would have been really easy with nodes.

Since you're exploring different solutions, maybe you should also look at Drupal Commerce, if only for inspiration. It's a really flexible system which adds line item entities to orders more or less like you want to add charges to properties.
> 1 votes

---
Tags: nodes, entities
---


# Question
Title: Executing a view programmatically with input filters
I've created a View to search for suitable jobs. Along with View I want to give a "Subscribe" button for those who want matching jobs(if any) be delivered in their inbox daily. I want to save the input entered in the exposed filters and run the View at night in a batch for all those who have subscribed for jobs.

I will add a *"Subscribe"* button along with *"Apply"* in the Views form. So if any logged-in user selects the *"Subscribe"* button I want to: 1) Save the input of exposed filters; 2) Run this view every night and see if any new matches are found; 3) Email the user with new jobs found.

Is there any easy way to do it? Is there any module to help me?

I can use Views Saved Searches module to save current user selection of exposed filters. This input could be fed when calling view programmatically.

Also two more useful links: Using Views Programmatically Drupalcamp & get the result view creates.

EDIT: **I need someone to provide me practical in-use implementation that can save my time.**

# Answer
> 3 votes
I don't think that you need to execute the view programmatically. Because it's meaningless. Views just fetches data from the tables which you show and display it, it's all it does. I think you need to alter Exposed Filter form and add your additional submit callback which on submission writes the searched strings into your custom table. And then you can query those table (from which table views fetch data.) with saved string as condition.. All of this logic must be run on cron job..

**EDIT:** I don't know this can help you or not, but here is a very poor example. Not very performance friendly :). OPTIMIZE IT.

```
function MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
   if ($form['#id'] == 'MY_EX_FORM_ID') {
      if(user_is_logged_in()) {
         $form['actions'] = array(
            '#type' => 'actions',
         );

         $form['actions']['submit'] = $form['submit'];
         $form['actions']['subscribe'] = array(
            '#type' => 'submit',
            '#value' => 'Subscribe',
            '#submit' => array('my_ex_form_subscribe_submit'),
         );
         unset($form['submit']);
      }
   }
}

function my_ex_form_subscribe_submit($form, &$form_state) {
   global $user;
   $account = clone $user;

   $input_val = $form_state['values']['field_adv_price_first']['min']; //Find your input field value and change this..

   db_insert('MY_SUBSCRIBE_TABLE')
      ->fields(array(
         'uid' => $account->uid,
         'email' => $account->init,
         'input_val' => $input_val,
      ))
      ->execute();
}

function MY_MODULE_cron() {
   $subscribed_query = db_select('MY_SUBSCRIBE_TABLE', 'mst');
   $subscribed_query
      ->fields('mst', array('uid', 'email', 'input_val'))
      ->execute()
      ->fetchAllAssoc('id'/* id - is the primary key of MY_SUBSCRIBE_TABLE */);

   // Supposing that your view is querying for the node table to fetch jobs, by title field
   if(!empty($subscribed_query)) {
      foreach($subscribed_query as $key => $val) {
         $nids = db_select('node', 'n')
            ->fields('n', array('nid'))
            ->condition('title', '%' . db_like($subscribed_query[$key]['input_val']) . '%', 'LIKE')
            ->execute()
            ->fetchCol();

         if(!empty($nids)) {
            foreach($nids as $nid) {
               $node_url = url('node/' . $nid, array('absolute' => TRUE));
               $template = 'New job is found in our site and blablabla... <a href="'. $node_url . '">BLABLABLA</a>';

               // Suppose that you are using SwiftMail library.. You can use drupal's mail system as well. It's up to you
               $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
                  ->setUsername('MYGMAILUSERNAME')
                  ->setPassword('MYGMAILPASS');

               $mailer = Swift_Mailer::newInstance($transport);

               $message = Swift_Message::newInstance()
                  ->setFrom(array('no-reply@'.$_SERVER['SERVER_NAME'] => 'MY-SITE.com'))
                  ->setTo(array($subscribed_query[$key]['email']))
                  ->setBody($template, 'text/html');
               $mailer->send($message);
            }
         }
      }
   }
}

```

# Answer
> 2 votes
**Is there any module to help me?**

Much easier to answer if you break down your question logically.

**1) Save the input of exposed filters;**

The input of exposed filters is relative to the user entities “saving” those filters. In Drupal 7 users are entities, and some entities are fieldable (meaning you can add fields to them). Drupal 7 users are fieldable. This DA question contains all sorts of useful answers you can use to add fields to your user - where later on you can store the *exposed filter* data: How to add extra fields to user profile?.

**2) Run this view every night and see if any new matches are found;**

This separate questions gets into batch/cron jobs area. Look into hook\_cron. You can define your own Drupal “job” that will run on any schedule you want. When the schedule runs depends if yo use standard system tools from managing cron (cron tab) - or if yo use a Drupal module such as elysia cron.

In your `hook_cron()` you could write a custom query that would search for all the users with a saved search. Since Drupal 7 users are entities, you can use `EntityFieldQuery` to get started.

If any users are found, then you could execute the View programatically (as you answered yourself), get the results, and email them. I don’t think Views will provide you with the best e-mail friendly output out of the box. But you could easily write your own custom theming function that parses the output returned by the View. This should be relatively easy for a Drupal beginner to do. Drupal theming is a topic of it's own. So I'm going to spare readers of an answer to that and assume due diligence on behalf of those seeking an answer. Links: one, two.

**3) Email the user with new jobs found.**

Multiple questions already answered here on DA can help you with that. I’m only providing one, two, three as a sample, but you could keep searching DA to your heart’s content. No reason to re-invent the wheel (or re-answer what’s been already answered).

To conclude - there is no easy answer to your question that I could think of, and my answer would assume that you've got at least a decent handle on Drupal. But I hope it helps nevertheless.

# Answer
> 1 votes
In one of my projects I build something like this in custom way.Here are few pointers I can think of now.

1. Create custom form, custom database table to map filter values with uid,keep a flag\_cron column and flag\_updated in your custom table,flag\_cron which will make sure that you are not picking up same filters to get data for and set flag\_updated to 1 every time you get data for a set of filters and again if the user against a uid updates the filters set the flag\_updated to 0,So while picking up the filters on cron run(you must be picking up the filters in chunks otherwise when users will grow system will fail to make request for),check for 0,0(flag\_cron,flag\_udpated) then give priority to 1,0(flag\_cron,flag\_updated).Key will be every time you get data update flag\_cron and flag\_udpated to 1. This is what I did in my project, I feel custom forms give more flexibility over expose filters.
2. On cron run you might be calling API's , so with the fetched data if you are building nodes then views are good solution to create the display while this views is programmatically called with the filter values against the current logged in user or if not set any then you can keep default in place.(creating nodes should be good approch). In case you are not making nodes and simply filling custom tables with data you get,you might make database query and may use different theme function to show the data.
3. Try to evaluate if better exposed filter form can take place for your custom form,otherwise underlying concept and custom filter table is supposed to be same.
4. In my projects I have to make several API calls at frequent intervals.Since API calls were large amount and they were fetching large data so I was looking for non blocking system, I used php command line tool exec.Code example

exec("/usr/bin/php path\_to\_php\_file.php $param\_0 $slot\_0\> /dev/null 2\>&1 &");

and $patam $slot are diferent arguments you need on the stanalone php file, the benefit you get using non blocking call system is you can trigger different php process at same time thus making different API calls by passing different arguments in parallel, but its important to control the php process otherwise it may crash your server.Later on I found there is a drupal module which allows to make non blocking calls "backgroung\_process"

1. For cron I used elysia cron and set crontab on server.

> Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

---
Tags: 7, views
---


title: Duplicated modules and drush

text:
# Question
Title: Duplicated modules and drush
During an update process of Open Atrium I ended up with the Organic Groups module (og) duplicated in sites/all/modules/og an profiles/openatrium/modules/contrib/og. I checked the 'system' table in the database and the one that's enabled is in sites/all/modules, however if I update the record in the 'system' table in order to use the module in profiles/openatrium/modules and afterwards I run the drush command

```
drush pmi og

```

and the output still reads:

```
Path: sites/all/modules/og

```

so where does drush get this value from?

# Answer
Drupal caches the system table with all the module locations, so you'll need to run:

```
    drush registry-rebuild

```

or use the Registry Rebuild module in order to flush that cache after manually updating the module paths in the system table. Alternatively, you could also just manually delete the system list from the cache bootstrap table:

```
    DELETE FROM cache_bootstrap WHERE cid='system_list';

```

Sources:

Overriding and Removing Overridden Modules included in a Distribution - https://drupal.org/node/1974964

Disabling or Enabling modules manually in the database - https://drupal.org/node/157632
> 3 votes

---
Tags: 7, drush, organic-groups, distributions
---


# Question
Title: How can I add HTML ASCII codes into menu link items?
Is there a module or method for adding in HTML ASCII codes into menu item links in Drupal 7?

Currently, I want to make the following a link in my footer menu.

```
© Copyright 1998-2000

```

# Answer
> 1 votes
Another solution would be to use CSS and then use :before to insert the copyright symbol.

```
.copyright-block:before {
  content: "\a9";
}

```

# Answer
> 2 votes
Yes. Menu HTML.

> This very simple module adds a checkbox to the menu item edit form and allows the admin to add html to the menu item title. The idea is to use this for external links for which you want to display a logo of the visited site or simply to add strong on some words.

---
Tags: 7, routes
---


title: Generate a PDF of an admin page

text:
# Question
Title: Generate a PDF of an admin page
I was wondering if anyone knew of a way to generate a PDF of an admin page in Drupal. I've looked at a bunch of custom modules but they seem only to work on nodes, which I know are not used to generate admin items. I have a client I've given limited back-end access to that would like a "Create a PDF" button placed in one of the admin areas. Does anyone have any recommendations? Here are my specs:

Drupal version: 7.24 Modules tried: mpdf, print

Thanks! -Dave

# Answer
Dear friend I suggest you if you only want provide a visual manual for your customer install pdf printer ( software that print result is pdf like foxit,nitro etc) then in each page ctrl+P (print ) and enjoy ( admin pages are not very much and not need put yourself in complex ways,It seems you want fast and short way to achive it ) :)
> 1 votes

# Answer
If the data your talking about is accessible to views you might try: https://drupal.org/project/views\_pdf. You can easily restrict access to the view, as well as provide it with a /admin path prefix.

As with previous comments, you might need to be a bit more specific.
> 0 votes

---
Tags: 7, files, users
---


title: How to upload files under taxonomy?

text:
# Question
Title: How to upload files under taxonomy?
Suppose in a School's website, I have some departments. They want their class lectures, class routines, course curriculum to be uploaded under their departments. Typically we did some very simple things - all the departments are now simple hierarchical pages. How to go with it.

We thought to go with a new content type, where the taxonomy will be the department name, where under the department names will be the type of document (whether class routine, or class lecture etc.) and under that taxonomy if we write a content, then we can go through the taxonomies to the content. In a scene they will be:

```
Home
  - Departments
     - Zoology
       - Class Lecture
         - Content
       - Class Routine
         - Content
       - Class Curriculum
         - Content
     - Biology
       - Class Lecture
         - Content
       - Class Routine
         - Content
       - Class Curriculum
         - Content

```

BUT NOT the file directly. We need to attach file under taxonomy, not the content. So there is a problem.

How can we proceed to such extent?

# Answer
> 2 votes
You can attach `file` with `taxonomy` as below:

* Go to Administration -\> Structure -\> Taxonomy
* Edit `Vocabulary`, which you want to use, from the list of `Vocabulary`.
* Click on "Manage Fields" tab in the top of the page.
* Add new field of `field type` as `file` and assign the required `file extension` which you want to upload and save the field.
* When you create new term of the vocabulary, it will allow you to upload file with term.

---
Tags: taxonomy-terms, files
---


# Question
Title: Create Nodes for multiple languages in webform?
I have a default Node for English, which will be translated when user logs in based on the user locale. Beside I need to create a separate node for ja(Japanese) like (`mydomain.com/node/7`).

I created a node(`nid=7`) by changing the 'Language neutral' to 'Japanese' language. when I hit the node it not gets translated to Japanese.

Is there any way to get it translated?

# Answer
I think maybe your problem is because mistake configuration of translation

Enable translation support for a content type

* Navigate to the Content types administration page (Administration \> Content \> Types in Drupal 6, or Administration \> Structure \> Content types in Drupal 7).
* Select a content type you want translated, and select "edit", then "Workflow settings" for Drupal 6 or "Publishing options" for Drupal 7.
* At the "Multilingual support" section, select "Enabled, with translation". Be sure to save each content type after enabling multilingual support.
> 0 votes

---
Tags: 6, webforms, i18n-l10n
---


# Question
Title: Upgrading complex content types from D6 to D7
I have a Drupal V6 website with some complex content types that I have created using CCK and Contemplate. That is, the content types have fields of type Text, Integer, Link, Node Reference and so on. I've been unable to upgrade this website to Drupal V7.

I have a few Drupal websites without complex content types and I've been able to upgrade those so I think I understand the general upgrade concepts and procedures. However I'm having trouble with this particular site. The process seems to complete normally, but nodes with complex content types have not migrated and only their basic fields can be displayed and edited. Checking the DB, the raw data appears to be there.

I've read the standard upgrade procedure and the CCK upgrade procedure but with no luck. Has anyone done this themselves and can you outline the steps you took.

# Answer
> 0 votes
I had the same Problem, but when you follow cck upgrade procedure step by step, it works. I think you need additional Variable Check Module. After upgrade i had 2 corrupted vars. With Variable Check you can find corrupted vars and remove them.

My solution:

1. many cck fields are included in core
2. download and unpack missing modules in to sites/all/modules
3. download "cck 7.x version", "variable check" and unpack
4. after upgrading activate "Variable Check" and "CCK Content Migrate" modules
5. run upgrade.php
6. under admin/reports/variablecheck check the validity of settings in the variable table

---
Tags: nodes, entities, upgrading
---