# Question
Title: Add a New [content type] on each content type
I want to create a block and put it in the sidebar of each content type that says "Add a new \[content type\]" So if the user was viewing an article, it would have "Add a new article", if the user was viewing a car, it would say "add a new car" etc.

Obviously I could make a different block and then control their display via context, but I'd rather create one block that essentially always links to add/new/\[content-type\] where content-type is whatever is being viewed.

Is there a way to pass in this argument via context?

# Answer
In the hook that return the block content, call a function with a code similar to the following one.

```
function mymodule_node_add_link() {
  $node = menu_get_object();

  if (!empty($node->type)) {
    $types = node_type_get_types();
    return l(t('Add a new @name', array('@name' => $types[$node->type]->name)), 'node/add/' str_replace('_', '-', $node->type));
  }

  return '';
}

```

The hook calling this function should always check the value returned from the function. In the case the showed page is not a node page, `menu_get_object()` doesn't return a node object, and this function returns an empty string.

Notice that every string shown in the user interface should be passed to t(). When passing a string to `t()`, you should avoid concatenating string, but you should use the placeholders the function supports, as in the code I shown.
> 1 votes

# Answer
In D6, you could use something like this snippet...

```
function create_another() {

  $node=menu_get_object();

  if (!empty($node->type)) {

    return l('Add a new ' . $node->type, 'node/add/' . str_replace('_', '-', $node->type));

  }

}

```

which, if used on a page displaying a full node, would return a link to node/add/`content type`. In D7, `menu_get_object()` does the same thing, so you'd probably just have to change the actual link path. Just be careful if you have \_'s in your node type. In D6 they need to be translated into -'s in the link above. I'm not sure about D7.
> 0 votes

---
Tags: nodes, 7
---


title: Multiple Themes per site

text:
# Question
Title: Multiple Themes per site
I want to include a whole new theme into a site to run along side the existing site on new pages (which make up another 'site' on this installation) . I have thought that I could just create new page templates prefixed with the new site name within the existing theme and it would all be seperate, but I didn't think about the stylesheets and scripts in the theme.info file.

I want to use completely new html, js, and css as the current stuff is horrible (I can just not render the current scripts and css, but I am wondering if there is a better way.). I also want to avoid unnecessary impact to the current installation as there are already 3 sites running on it.

Is this the best way to add another simple site to an existing Drupal installation?

# Answer
Use the Domain Access module and Domain Themes module in combination to switch themes depending for a domain within the same Drupal installation.

Domain Access allows you to specify multiple domains for your site installation, and control what is created for those.

Domain Themes allows you to specify what theme is used for a domain.
> 2 votes

# Answer
The ThemeKey module may be able to accomplish what you're looking to do.

The granular control it gives you as to when to show a specif theme is very impressive.
> 3 votes

---
Tags: theming, multi-sites
---


# Question
Title: Using Drupal 7 with APC, Varnish and Memcache, what bins to put in which cache?
I'm optimizing a Drupal 7 website and I have varnish, memcache and APC all installed and working with their individual Drupal 7 modules. In my settings.php I have the `$conf` options below.

My question is to get better performance and have all these caches work together well, do I need to add more configuration options?

The module readme's usually assume a single cache system. Are there any tweks needed to get better performance out of running 3 separate caching backends?

```
// Add Varnish as the page cache handler.
$conf['cache_backends'][] = 'sites/all/modules/varnish/varnish.cache.inc';
$conf['cache_class_cache_page'] = 'VarnishCache';
// Drupal 7 does not cache pages when we invoke hooks during bootstrap.
// This needs to be disabled.
$conf['page_cache_invoke_hooks'] = FALSE;

$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';
$conf['cache_class_cache'] = 'DrupalAPCCache';
$conf['cache_class_cache_bootstrap'] = 'DrupalAPCCache';
//$conf['apc_show_debug'] = TRUE;  // Remove the slashes to use debug mode.

$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['cache_default_class'] = 'MemCacheDrupal';
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

```

# Answer
Looks ok to me.

What you can try is play around with Memcache options. There is for example a compression flag but it usally depends on the site if it makes sense to enable it because you then have a higher cpu usage to do the compression/decompression.

I also think that page\_cache\_invoke\_hooks flag is not necessary anymore, see http://drupal.org/node/804864. If you don't need those hooks to run then you can set it, but it's not necessary anymore for Varnish to work.

Using APC cache with multiple webservers means that you run into inconsistencies when clearing caches on one server, so if you do have multiple ones, you probably want to use Memcache for cache and cache\_bootstrap as well. I've also had stability issues when using APC cache but I did use it for all caches, which might have been the issue.
> 6 votes

# Answer
I am running a similar setup with memcache servers and Varnish locally on each web server. I thought that page caching locally with Varnish would not be as effective as using memcache.

I am considering using MongoDB for something since I have it running as well and it is also a shared resource.
> 2 votes

---
Tags: performance, proxies, caching
---


# Question
Title: handling non-node based items with ubercart
I'm working on a book repository website very similar to Islandora which is based on Fedora Commons and Drupal.

Books's information stored in repository outside Drupal. Apache Solr is configured on server and Drupal to search repository and display result in Drupal.

everything works fine, now I want make this books purchasable in Drupal.

As these search results are not nodes and there is not a node per book, I'm looking for a way to adding this non-node based items to cart!

any suggestion may be helpful!

http://www.ubercart.org/forum/support/14856/non\_node\_based\_items

# Answer
Having dealt with this exact circumstance before, we had a content type named 'bundle' which was purely a placeholder for the product details in Ubercart.

The user views the product and clicks 'add to cart' and in the cart is an instance of this 'bundle' with the product details in it.

Its far from a good solution and I would definitely be looking at creating a node for each of the products you have for sale - You could even create the nodes when 'added to cart' so you didnt need to add any in advance.

Ubercart has a great API for manipulating cart contents and line items, have you looked at that at all?
> 1 votes

---
Tags: 6, ubercart
---


title: node/add is breaking menu hierarchy

text:
# Question
Title: node/add is breaking menu hierarchy
I'm a newbie, and I'm trying to create a site on Drupal7.

I have a taxonomy vocabulary with many terms. Then I use taxonomy\_menu and nice\_menu to show the terms. This is working perfectly.

The problem comes when I create (or edit) a node (of any type) and I associate it to a term. The menu item(s) corresponding to selected(s) term(s) loses his place in hierarchy. Searching on database I realize the column "plid" on "menu\_links" table is set to 0.

Searching on drupal.org I found this post, I think my problem is related to it. On first comment someone gives a solution, but I can't use it, because in this case nodes won't be shown in the menu.

ideas?

P.S.: sorry on my bad english, ask if you don't understand

# Answer
> 0 votes
It looks like this could be a known issue. Please see the below two issues for the taxonomy\_menu project - the second contains a patch you could try?

http://drupal.org/node/1208484

http://drupal.org/node/1485198

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


# Question
Title: Content API - parameter to find link url of a Link field
I have a custom content type called Link, which has a Link field. I'm using services and Content API to query the list of Links, and I want to show the data for a Link node where the Link is equal to a parameter passed into the URL.

Eg, I would like to do something like the following:

\[Drupal root\]/api/content?field\_link=http://www.google.com

# Answer
> 1 votes
The Content API is a tricky thing to get the hang of, but try to do the following:

As long as your Rest Server endpoint path is "api" and the resource is "content" what you have above should technically work. Make sure you also enabled the Link content type in the Content API configuration.

When you do query with /api/content?field\_link=http://www.google.com you will only get the base fields returned, even if you filtered by http://www.google.com it won't show in the response you get. You then have to send another request to /api/content/ and that will return every field for that given node.

Hopefully this helps a little bit, if anyone can fill in my holes I would appreciate it, I'm by no means an expert, just played around with the Content API and got it to work a little.

I did respond to your email with some private links to prove that it is possible.

---
Tags: services
---


# Question
Title: Field that links to a path/url defined with Tokens, is it possible?
I would like to create a few fields in a content type that will link to certain paths defined with Tokens, in my particular case the node author uid. I am using a number of user related modules including Flag, User Relationships, Heartbeat etc which define user specific paths for a number of tasks that users can do (eg. view their flagged content, manage their relationsships etc). Hence my need to use Tokens to define the paths as oppose to just writing the static path myself. The paths would need to be auto generated for each node based on the Tokens, like Pathauto except for field links.

The Link module would be perfect for this, but in my experience, it does not fully support Tokens for the url. Are there any alternatives?

# Answer
> 1 votes
The Link field module DOES support tokens in Drupal 7, both in the link title and the link url field. You might be confused by the fact that the token drop down menu is at the top of the link edit form so it looks like it's not for the url field at the bottom of the page. I was confused by this before myself. Also make sure you have the right input field focused on first before you start clicking to add tokens.

---
Tags: entities, navigation, tokens
---


# Question
Title: PDOException when saving node with AudioRecorderField
Occurs on client's computer but not mine. Does not appear to be a user-related problem. Using SoundCloud recorder.

```
PDOException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid
input syntax for integer: "NULL" LINE 4: WHERE (base.fid IN ('NULL')) ^:
SELECT base.fid AS fid, base.uid AS uid, base.filename AS filename, base.uri
AS uri, base.filemime AS filemime, base.filesize AS filesize, base.status AS
status, base.timestamp AS timestamp FROM {file_managed} base WHERE (base.fid
IN (:db_condition_placeholder_0)) ; Array ( [:db_condition_placeholder_0] =>
NULL ) in DrupalDefaultEntityController->load() (line 196
of /Users/Shared/Server/HTTP/chinese/includes/entity.inc).

```

# Answer
Looks like the problem was with the PHP upload limit. Seemed to be a computer problem because I always used short recording files when testing, while my client tested with a full recording.
> 0 votes

---
Tags: database
---


# Question
Title: Is there any built in function to render image file extension like jpg, png etc?
Is there any built in function in Drupal 7 to render image file extension like jpg, png etc on node load.

I have tried image\_get\_info etc.

# Answer
`image_get_info()` should do the trick.

```
//if you want to get the extension of image1.jpg
$filepath = "sites/default/files/images/image1.jpg";
$info_var = image_get_info($filepath, FALSE);
echo "the image extension is ".$info_var['extension'];

```
> 2 votes

---
Tags: 7, media
---


# Question
Title: Before upgrading, do I need to upgrade the Views module to 6.3.x?
I'm going to update a site from Drupal 6 to Drupal 7. It uses the Views module version 6.x-2.

I would like to know if I need to upgrade the Views module to version 6.x-3 before moving to Drupal 7.

# Answer
It's not necessary. I have migrated one large site from Drupal6+Views2 to Drupal7+Views3 in just one step.

You have to take in account that views3 (views\_ui submodule) depends on ctools. If you follow this path you have to disable views\_ui before the upgrade and activate views\_ui (and ctools) once the upgrade has finished.
> 3 votes

# Answer
Yes, in this case you should upgrade Views to 3.x first as there is no Views 2.x version for Drupal 7. It might still work to just upgrade Views after Drupal but by upgrading Views first I think you have prepared your site and the upgrade process better.

For more information and checklist on upgrading from Drupal 6 to 7, checkout this link.
> 1 votes

---
Tags: 7, views, upgrading
---


title: Content is not displayed in front page

text:
# Question
Title: Content is not displayed in front page
I am using drupal 7. In theming i have created page--front.tpl.php

Every thing is working properly, but when i create a basic page and assign it to display on front page then page is not rendered.

I have also written this `<?php print render($page['content']) ?>` but content is not being rendered. It is showing error

> No front page content has been created yet. Add new content

# Answer
I had installed weight module to assign weight to nodes. This was creating problem. I just uninstalled it to debug and surprisingly it was working, but to work with weight module i assigned -1 weight to front page content and it started displaying the content.
> 0 votes

# Answer
That's the message you get for the standard front page (located at `/node`), so it looks like your attempt to update which page is the front page hasn't taken for some reason.

In case you've done it another way, the usual way to set this front page is to go to `admin/config/system/site-information` and set the "Default Front Page" to the path of the new node that you've created.

You'll also need to clear Drupal's caches once you've added the new template file in case you haven't done that already.
> 1 votes

---
Tags: theming
---


# Question
Title: How can I make Drupal use token for summary instead of breaking at <br>?
I'm using "Long text with summary" fields for some different content types.

Right now the summaries are rendered until the first
-tag (the web site already contains ~5000 nodes) but I would like to use a token created by a module that I'm currently using for the meta description of each page.

How can I use a token to display a nodes summary in a standard taxonomy node listing?

# Answer
Assuming you're using Drupal 7, you can change how the content type is displayed in 'manage display'. You need to make sure you are using the correct view mode (probably teaser) which can be selected in the top left. You can then set the format to 'Summary or trimmed' and adjust the trim length by clicking the cog button.
> 1 votes

---
Tags: tokens, entities
---


# Question
Title: How do you print nothing from a Field template? (field--field_name.tpl.php)
I need to show a block if a field has a given state, or print nothing if it has a different state. I can get it to work using a field template with the code below, but printing useless html just to stop it from rendering it's default output seems more than a little hacky.

I've tried setting `$element = null;` \- that didn't work. I tried changing #markup to be empty, that didn't work. Even using `print '';` means Drupal kicks it's default rendering back in.

**Is there a recommended method for telling a field to do nothing?**

```
<?php if($element['#items'][0]['value'] === 1){
    //This is an archive page - show the block.
    $block = module_invoke('customblocks', 'block_view','archive');
    print render($block['content']);
    } else {
        //nothing to do here - not an archive page
        //The only way to stop Drupal rendering something appears to be to get it to print SOMETHING.
        //So we're going to print an invisible hr.
        print '<hr style="display:none;" />';
    }
?>

```

# Answer
This tutorial might be helpful http://akyl.net/how-extract-and-theme-drupal-7-fields-out-renderpagecontent
> 0 votes

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


title: How reload form values with ajax

text:
# Question
Title: How reload form values with ajax
So I'm trying to do something really simple but haven't manage to know how to do it with the Ajax API form from drupal 7. I have an administrative GUI with a select input type, I set the #ajax property with the callback but I don't want to replace anything just need to reload/refresh the values for specific inputs most of them textfield, when the selection change.

Any insight on how to do this? Can it be done with the Ajax Drupal 7 API?

Thanks....

# Answer
> 2 votes
You should put a wrapper around the fields of which you want to reload/refresh (basically replace) and in the call back return the either the form values in an array or the wrapper.

This basically means that on the event specified in the callback, eg change the whole wrapper div is swapped out and replaced with a new one built by the php in your form.

---
Tags: forms, ajax
---


title: variable_get with prefix

text:
# Question
Title: variable_get with prefix
It's there a chance to retrieve all key/value, stored in `variable` table, that have a prefix, using `variable_get()`? e.g: variable\_get("prefix\_\*")

Or I have to use db\_select('variable')?

# Answer
> 2 votes
I'm afraid not, `variable_get()` is a very simple function that just returns an item in the global `$conf` array, there's no method for searching built in.

You could write your own `variable_select()` function though, and you wouldn't have to go into the database as the entire variable table is loaded into `$conf` at the start of the page build. It might go something like this:

```
function variable_select($prefix) {
  $found = array();

  global $conf;
  foreach ($conf as $key => $value) {
    if (strpos($key, $prefix) === 0) {
      $found[$key] = $value;
    }
  }

  return empty($found) ? FALSE : $found;
}

```

I'm sure that could be improved but it's a start. It's worth noting that this method might match elements from the settings.php file that aren't actually variables in the database as such.

For example, if your prefix is `data`, it's likely you'll see the `$conf['databases']` variable from settings.php in your results. There wouldn't be a way around that without going directly into the db I don't think.

---
Tags: configuration
---


# Question
Title: DrupalDefaultEntityController invalid argument supplied for foreach
Been trying for the last hour to work this one out.

```
$query = new EntityFieldQuery();
$query -> entityCondition('entity_type', 'node')
       -> entityCondition('bundle', 'subscription');

$results = $query->execute();

if(isset($results['node'])) {
    $subscription_nids = array_keys($results['node']);
    $nodes = node_load_multiple($subscription_nids, TRUE);
    return $nodes;
} else {
    return FALSE;
}

```

This is a very simple version of the entire query, but the error is exactly the same:

```
Warning: Invalid argument supplied for foreach() in DrupalDefaultEntityController->buildQuery() (line 290 of /var/www/ml/data/www/ml.mailapproved.com/includes/entity.inc).

```

I don't understand what's wrong here.

# Answer
> 2 votes
The 2nd argument for `node_load_multiple()` is an array of conditions; currently you're providing a boolean so when the `buildQuery` function tries to iterate over the variable you get a warning.

The 3rd argument is to reset the cache (I guess that's what you're trying to do), so the call should be:

```
$nodes = node_load_multiple($subscription_nids, array(), TRUE);

```

---
Tags: 7, database
---


# Question
Title: Devel : what kind of information devel_boot, devel_shutdown and php tweak describes?
I have a problem on my website about slow query and many 324 errors. I tried to resolve them but as i'm new in Drupal i have a lot of difficulties to understand some stuff.

(The website site i'm making actually have 102 modules install, 9 differents roles and a lot of permission on fields, node etc. We don't have a dedicated server so it's very slow and not optimize)

So i tried to do my best and i'm actually working with devel to see if i can do something maybe.

I read this about devel\_shutdown on drupal.org but as a beginner i'm not really sure to understand the meaning and the purpose of this function. So i would like to know more about some function used by devel like:

* devel\_boot
* php peak
* devel\_shutdown

(devel\_shudown = memory\_allocated per user? and php peak = memory allocated by the server?)

As you see in my picture, i have a devel\_shutdown greater than 41mo (sometimes more than 51mo). For people who worked on Drupal since many years do you think it's normal for a drupal site or do i have to be worried about that?

Thanks,

# Answer
> 4 votes
* **devel\_boot** is the memory in use during hook\_boot. It is the amount of memory Drupal is using just getting bootstrapped and ready to run module and theme code.
* **php peak** is the maximum amount of memory in use during your page request. It is provided by the PHP function memory\_get\_peak\_usage. This is probably the most important metric to consider.
* **devel\_shutdown** is the memory in use at the last possible moment it can be measured with code in a request. It is registered via drupal\_register\_shutdown\_function() which registers functions to be called once all other PHP code has finished executing.

Memory is important to monitor, but it doesn't seem like you are having issues with memory use. I can see from your screenshot that you are using 42MB of memory - that is nothing to be concerned about in most cases.

I would be more concerned about your slow cache queries (highlighted red in your screenshot). Try and figure out why they are taking so long to run.

There are a lot of resources on the web and drupal.org on improving performance. The biggest wins will come from caching and improving SQL performance - then you can start honing in on code profiling to figure out where your time is best spent.

Some resources that may help:

Best of luck!

---
Tags: debugging
---


# Question
Title: How to generate block with Views, Entity Reference and Taxonomy Terms
I have a site with content types: book-page & ride.

These are organized so that each book-page displays several rides (using Entity Reference), and each ride is tagged with several taxonomy terms.

I'd like to create a block which displays links to other pages whose rides share a taxonomy term with any of the rides on the current page.

Looking at the table structure I can see that the following query will yield the desired results (for node id 9).

```
SELECT DISTINCT your_page.title
FROM node my_page
INNER JOIN field_data_field_rides my_page_rides ON my_page.nid = my_page_rides.entity_id
INNER JOIN node my_ride ON my_page_rides.field_rides_target_id = my_ride.nid
INNER JOIN taxonomy_index my_ride_terms ON my_ride.nid = my_ride_terms.nid
INNER JOIN taxonomy_term_data my_term ON my_ride_terms.tid = my_term.tid
LEFT JOIN taxonomy_index your_ride_terms ON my_term.tid = your_ride_terms.tid
INNER JOIN node your_ride ON your_ride.nid = your_ride_terms.nid
INNER JOIN field_data_field_rides your_page_rides ON your_page_rides.field_rides_target_id = your_ride.nid
INNER JOIN node your_page ON your_page.nid = your_page_rides.entity_id
WHERE my_term.vid = 2
  AND my_page.nid = 9
  AND (your_page.nid IS NOT NULL AND your_page.nid != my_page.nid)
  AND your_page.status = '1'
  AND your_page.type IN ('book')
  AND your_page_rides.entity_type = 'node'
  AND your_page_rides.deleted = '0'

```

My question is - can the same thing be done through the Views UI using a Relation?

I'm using D7 with Views 3.

# Answer
> 1 votes
Many thanks to @flocondetoile for responding, but I think the problem I posed was a join too far for Views. That is, whereas @flocondetoile needed to join:

```
parent-node -> child-node -> parent-node

```

I needed to join:

```
parent-node -> child-node -> taxonomy-term -> child-node -> parent-node

```

Try as I might I could find no way to do this directly in the Views UI. I *did* though find an elegant solution which I share here in case anyone else finds it useful.

Step 1

Save your query as a database view, i.e.,

```
CREATE VIEW view_name AS ...

```
Step 2

Describe your database view (or table) to the Views module. This is done by implementing **hook\_views\_data** (you can find the Views version in **node.views.inc**). It's a big method, but not too scary. In effect you just build up an array of meta-information about your database view. I based mine fairly closely on the code in node.views.inc. This step is described in some detail on this blog page, which also includes a worked example. Be sure to check out the slides linked at the bottom of the page.

Step 3

Views will now know about your custom database view/table. You can query it directly.

# Answer
> 0 votes
What are you use for you entity relation ? Is the module Relation or the module Entity Reference ? If it's Entity Reference, you should read this post http://drupal.org/node/1714188. It could help you

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


# Question
Title: Single Sign On Integration with NetCommunity
I want to integrate Drupal with Net Community Black Baud single sign on.

The approach/process flow is same like FaceBook Connect or LinkedIn integration for single sign on.

NetCommunity is just another sign-on site and behaves just like LinkedIn users.

But I am stuck with from where to start the implementation of this. I have seen LinkedIn module to login with LinkedIn. But I want to know whether it can be done using oAuth library or not.

# Answer
The last time I looked into BBNC (which was two or three years ago), you had to do a two-fold approach.

First, you need to write an ASP.NET webservice on the BBNC side using their API to expose login. This may have changed since I checked it out. Poke around the BBNC forums to see what may already exists.

Two, you wire up authenticate against a non-drupal database. This is actually fairly easy. I would look at the LDAP module to see how it does things. It essentially hook\_form\_alter's the user\_login form to add some additional validation, which checks the external database.

I would also poke through the BBNC forums to see if anyone has an LDAP, OAuth, or OpenID solution for NC. Then you can use one of the existing solutions. Those three modules are also good to look through for ideas on how to do the authentication.

The question that @indrock gives is also a good read about session management.
> 3 votes

---
Tags: users, authentication-authorization
---


# Question
Title: Drupal login error message display on page by make new module
I created the module and added the field in the user login block form for displaying error. I want to display the error in warning field instead of using `form_set_error()`. I am able to see the warning field in the login block. When I submit with error it did not display the error. Code is as under. I am missing how to refresh the value of form once it gets error.

```
function usermoved_form_user_login_block_alter(&$form, &$form_state) {
$form['warning'] = array(
'#value' => t('oops'),
'#weight' => 11
);
$form['#submit'][] = 'usermoved_form_submit_code';
}

function usermoved_form_submit_code($form, &$form_state)
{
  global $user;
 if (!$user->uid) {
  $form['warning']['value']= "changed to something";

}

}

```

I have disabled the error in user.module as follows.

```
function user_login_final_validate($form, &$form_state) {
  global $user;
   if (!$user->uid) {
//form_set_error('name', t('Sorry, unrecognized username or password. <a
    //href="@password">Have you forgotten your password?</a>', array('@password' =>
    //url('user/password'))));
}
}

```

# Answer
> 1 votes
I suggest you **DO NOT CHANGE DRUPAL CORE** , if you want your custom validation use something like this

```
function usermoved_form_user_login_block_alter(&$form, &$form_state) {
   $form['warning'] = array(
   '#value' => t('oops'),
   '#weight' => 11
   );
  $form['#submit'][] = 'usermoved_form_submit_code';
  $form['#validate'][] = 'yourcustomvalidationfunction';
     }

```

and in your custom validate fuction put your error in `warning field`

```
 function   yourcustomvalidationfunction(&$form,&$form_state){
    if (your validation accure error) {
        $form['warning']['#value']= t('my error message that come in warning field') ;
       }
    }

```

or you can **create and initial** `warning` directly in validation function and not require create `warning field` in alter

---
Tags: 7, users
---


# Question
Title: Custom actions not appearing in the Trigger/Action settings page
I am developing a custom module which defines custom Triggers and Custom actions. When I add or change an action, this action doesn't inmediatelly appear in the select list of the Triggers admin page.

I refresh, flush all caches and even activate/desactivate the Trigger Unlock module (which seems to work), but now when I create a new custom action, I go nuts to make it appear.

You can appreciate in the image and code what I am talking about (notice the Description has not changed after update).

```
/**
 * Implementation of hook_action_info().
 */
function commercegate_action_info() {
    return array(
        'commercegate_show_message' => array(
            'description' => t('Show message 1.'),
            'type' => 'commercegate',
            'configurable' => false,
            'hooks' => array(
                'commercegate' => array('callback_sale','callback_cargeback'),
            )
        ),
        'commercegate_show_message2' => array(
            'description' => t('Show message 2.'),
            'type' => 'commercegate',
            'configurable' => false,
            'hooks' => array(
                'commercegate' => array('callback_sale','callback_cargeback'),
            )
        ),
    );
}

```

Anyone familiar with this problem? Thankyou

# Answer
> 1 votes
To allow a new action to appear on the triggers page, you need to visit the administration page at admin/settings/actions, or call actions\_synchronize().

# Answer
> 1 votes
It's actually `hook_rules_action_info()` not `hook_action_info()`.

# Answer
> 0 votes
try this: uninstall and reinstall your module.

# Answer
> 0 votes
Check the permissions, sometimes it automatically is deselected.

---
Tags: rules
---


title: Show/Hide regions in Omega subtheme

text:
# Question
Title: Show/Hide regions in Omega subtheme
I am using Drupal 7 and I am creating an Omega subtheme.

In my case I want a page without left and right sidebars. But when I inspect the page.tpl.php from alpha theme it contains only code for printing attributes, content and footer regions

Here is my page.tpl.php

```
print $attributes;
  if (isset($page['header']))

   print render($page['header']);

  endif;

 if (isset($page['content']))

    print render($page['content']);

 endif;

  if (isset($page['footer']))

     print render($page['footer'])

  endif;

```

In the above snipped I don't find any option to show/hide sidebars as we used to do like in Garland theme.

# Answer
You can create multiple page layouts using delta modules and use the same for required page.
> 2 votes

---
Tags: theming
---


# Question
Title: connect apache solr to a custom search function
I am having some trouble with creating a search module (dictionary) that uses apache solr. The current module is connected to a solr instance from a different source that has a indexation from a postgresql database with it's own schema.

Now I'm in the process migrating all the content to nodes in Drupal and so far so good. The thing now is that I need to change the search request from the current solr to Drupal apachesolr with its standard schema. Problem is that I am relative new to how solr works, but I do understand the basic structure.

Anyone that might be able to give me a hand or point me to some kind of documentation to how to do this?

I tried to change the query search quartiles from what i could find in the schema . The only thing keep getting when i do a search is "Your search yielded no results"

Here is the cod in the callbacks.inc file unmodified

```
<?php

function ne_norstedts_page($types) {
  $ret = '';

  $form = drupal_get_form('ne_norstedts_search_form', $types);

  // Render search form.
  $ret .= '<div id="norstedts-search-form" class="fourcol">';
  $ret .= render($form);
  $ret .= '</div>';

  // Get search results and output them
  isset($_GET) ? extract($_GET) : '';
  if (isset($q) && isset($from) && isset($to) && isset($type)) {
    $query = array(
      'q'  => $nq,
      'fq' => 'type:norstedts AND subtype:' . $from . '-' . $to . '-' . $type,
      'start' => isset($page) ? ($page) * 10 : 0,
    );

    $result = ne_api_get_api_fetch('/search', $query);

    $title = '';
    foreach ($types as $t => $name) {
      if ($t == $type) {
        $title = $name;
        break;
      }
    }

    $ret .= theme('ne_norstedts_results', array('result' => $result['result'], 'title' => $title));
  }

  return $ret;
}

/**
 * Gets text for a single word for ajax
 */
function ne_norstedts_ajax_load_word() {
  $url = isset($_GET['url']) ? $_GET['url'] : '';
  if ($url) {
    $result = ne_api_get_api_fetch($url);
    if (isset($result['text'])) {
      echo drupal_json_encode($result['text']);
    }
  }
  exit;
}

```

and here is my modified version of it

```
<?php

function ne_dictionary_page($types) {
  $ret = '';

  $form = drupal_get_form('ne_dictionary_search_form', $types);

  // Render search form.
  $ret .= '<div id="dictionary-search-form" class="fivecol">';
  $ret .= render($form);
  $ret .= '</div>';

  // Get search results and output them
  isset($_GET) ? extract($_GET) : '';
  if (isset($q) && isset($from) && isset($to) && isset($type)) {
    $query = array(
      'q'  => $nq,
      'fq' => 'site:' . $from . '-' . $to,
      'start' => isset($page) ? ($page) * 10 : 0,
    );

    $result = apachesolr_search_search_page('/search', $query);

    $title = '';
    foreach ($types as $t => $name) {
      if ($t == $type) {
        $title = $name;
        break;
      }
    }

    $ret .= theme('ne_dictionary_results', array('result' => $result['result'], 'title' => $title));
  }

  return $ret;
}

/**
 * Gets text for a single word for ajax
 */
function ne_dictionary_ajax_load_word() {
  $url = isset($_GET['url']) ? $_GET['url'] : '';
  if ($url) {
    $result = apachesolr_search_search_page($url);
    if (isset($result['text'])) {
      echo drupal_json_encode($result['text']);
    }
  }
  exit;
}

```

# Answer
> 1 votes
You dont need a module for this. Activate your solr module, index your content and the core drupal search will be replaced by the solr search. There is nothing else you need to do. From then on, every search you make using the domain.com/search/site url will be automatically directed to solr.

It is just a matter of setting the right options in the solr module.

# Answer
> 0 votes
How about trying Apachesolr Views module, where you can create a view page and achieve your functionality. The parameters can be configured in filters.

---
Tags: search
---


# Question
Title: Hook to run code after a rule has been executed
I have a module which performs a specific task. The task itself runs fine, though it also needs to be exectued when a specific rule is triggered. Is there a hook for rules which I can use in my module to check if a specific rule has been fired?

# Answer
You can make that "specific task" as an action to a rule using hook\_rules\_action\_info and add that action for the rules which you want to exectue.
> 3 votes

---
Tags: 7, rules
---


# Question
Title: Flag- is there a way to allow users to only flag themselves?
I'm on Drupal 7 with Flag 2.0 (beta9). The flag module provides a checkbox option for user flags, **Users may flag themselves**. However, I would like to allow users to *only* flag themselves. In other words, I want to give each user an on/off switch as a flag, but each user should only be able to toggle the switch for herself.

What I am trying to do: I have some options users select at registration (are you interested in A? B? C? etc.) These are checkboxes. I want to give users an easy way to change these options after registering. If I send them to the edit account screen, they get the option to change their password, e-mail address, etc., which is too much. I was thinking of using flags to do this (with a rule that triggers to *Set a data value* when the user is flagged/unflagged), but it is crucial that users only be able to change their own values.

# Answer
Is there a way to use a node flag instead? Out of the box, there you can restrict it to a node type and also to content only owned by the user (or not).

So if you have the equivalent of a content profile set up in d7, you would be able to set it up so a flag was restricted to that type of content and only to the node owner, which might accomplish what you are after.
> 2 votes

---
Tags: flags
---


# Question
Title: Straightforward method to get related items view from Solr
I have a Drupal 6 site with an Apache Solr search index. I'm trying to create a block that displays 'related content', much like Stack Exchange sites have 'related' in the sidebar of questions. The modules Apachesolr\_views seems like a good candidate, but it's current development status and issue queue is less than inviting. Does anyone have suggestions of a straightforward way to implement this?

# Answer
> 3 votes
The feature is actually built in to apachesolr.module. It is called 'mlt' (short for More Like This).

You can add differently configured MLT blocks via `?q=admin/settings/apachesolr/mlt/add_block` and then configure their visibility in `?q=admin/build/block` or whatever block visibility mechanism you are using (context etc).

---
Tags: blocks, search, views
---


# Question
Title: template suggestion not working (page--front.tpl.php) in windows 7 env
I do my development in a windows 7 env. Using XAMPP to run D7 and supporting apps.

I am giving the template suggestion of `page--front.tpl.php` for my D7 theme. For whatever reason the file doesn't seem to be getting recognized by D7. I pushed my code to my development server (linux) and `page--front.tpl.php` is picked up without issue.

has anyone seen this behavior? I can't lock down what is happening here.

# Answer
> 0 votes
I've seen this happen when there is another `page--front.tpl.php` lurking around in your directory structure and it is being picked up and used instead of the one you are looking at. And, if that one is a copy of `page.tpl.php`, it will *appear* that it isn't being picked up. So, I'd look around and make sure you don't have one anywhere in your theme directory as Drupal will recurse through the entire tree looking for templates. Another edge case is permissions so make sure it is readable to the world. If all else fails, strangling the pc with the mouse brings some level of relief and entertainment :)

---
Tags: 7, theming
---


title: How do I git pull a dev branch?

text:
# Question
Title: How do I git pull a dev branch?
I'm trying to switch to the dev version of Views. Repository instructions worked and I was able to `git clone` Views.

However, listing the available branches with `git branch -a` only shows `* 7.x-3.x`.

And trying to add a "dev" branch with pull returns an error:

```
$ git pull origin 7.x-3.x
From http://git.drupal.org/project/views
 * branch            7.x-3.x    -> FETCH_HEAD
Already up-to-date.
$ git pull origin 7.x-3.x-dev
fatal: Couldn't find remote ref 7.x-3.x-dev

```

What am I doing wrong?

# Answer
If I do

```
git clone --recursive --branch 7.x-3.x http://git.drupal.org/project/views.git

```

and then

```
git branch -r

```

I get

```
origin/4.6.x-1.x
origin/4.7.x-1.x
origin/5.x-1.x
origin/6.x-2.11-security
origin/6.x-2.x
origin/6.x-3.x
origin/7.x-3.x
origin/8.x-3.x
origin/HEAD -> origin/7.x-3.x
origin/d7v3ui
origin/master

```

I believe you need the recursive flag to get all remotes. Not sure if you did that, but a quick git fetch will update your list of remotes.

```
git pull origin 7.x-3.x-dev
fatal: Couldn't find remote ref 7.x-3.x-dev
Unexpected end of command stream

```

I think this is just due to the naming conventions, current dev is HEAD afaik.

```
git pull origin 7.x-3.x
From http://git.drupal.org/project/views
 * branch            7.x-3.x    -> FETCH_HEAD
Already up-to-date.

```

I believe that any branch (not tag) can be considered 'dev' for that drupal version.

Hope this helps.
> 5 votes

# Answer
I'm not a Git expert, but as I understand it all of the releases of the dev branch listed on the project page are made directly to the 7.x-3.x branch. Of course you're free to create your own branches locally for your own needs, but the `master`-like branch, which includes all of the releases pushed to drupal.org, is always going to be that 7.x-3.x branch.

If you want to switch to one of the tagged releases, use `git tag` to get a list of all the releases. Then, to check out the `7.x-3.1` release (for example), use `git co 7.x-3.1`.

If you intend to edit the code for this release, you can then create a new branch (as Git explains) by using `git checkout -b mycustombranch`.
> 6 votes

# Answer
The way to pull the repository for the 7.x-3.x branch of the Views module (i.e. the development snapshot 7.x-3.x-dev for the Views module) from Drupal.org for the first time is executing the following command:

```
git pull git clone --recursive --branch 7.x-3.x http://git.drupal.org/project/views.git

```

After that, if you need to keep the local repository for the Views module updated, you should execute the following commands:

```
cd views

```

```
git reset --hard

```

```
git pull origin 7.x-3.x

```

To make it clear: A Drupal development snapshot is created from a git branch, while a Drupal release is created from a git tag. The name of the git branch is the name of the Drupal development snapshot without the -dev part. In your case the development snapshot is 7.x-3.x-dev, and the git branch is 7.x-3.x.
Furthermore, the git tag used to create a Drupal release must follow a specific schema. Tags similar to 7.x-3.0 (or 7.x-3.1-beta3) are for the 7.x-3 version of a module, and its development snapshot is named 7.x-3.x-dev. On Drupal.org, you cannot create a Drupal release from a git tag similar to beta-release, or a Drupal snapshot from a git branch similar to test-branch.
> 3 votes

# Answer
EDIT: As pointed out, the **question** was "How do I git pull a dev branch" which has been partially demonstrated in the other answers. Yet, a key second part of any answer must include a translation of the Drupal -dev naming convention. Simply because it does not appear using the commands `$git branch` or `$git tag` while `-dev` clearly is evident in the "Development releases" table on a module's main page. This is my attempt to clarify this with a reasoned, but in no sense authoritative, definition:

There is a sense **-dev** is equivalent to **rough draft** in the familiar metaphor of writing. An article describes setting up "your own Git repository viewer" on a local repository (for developers who prefer to not host in *the cloud*),

> "You can choose either the latest stable version or the master version, but keep in mind the master version may have bugs since developers are actively working on it." PHPMaster

Now we have a definitive statement describing a convention for *active development* on the "master version". And here is the principal issue I've been working on in this post: relating a convention (developer convention, programming best practice, or *The Drupal Way*) to the operation and use of the git application.

Now, you'll have to bear with me for a moment as I digress. In my novice git-ucation, I wasn't sure if "master" was also a naming convention of developers or built into the git application itself. And here I turned to a site search at the maintainers site, git-scm.com, to find this gem:

> "In the default case that is automatically written by a `git remote add` command, Git fetches all the references under refs/heads/ on the server and writes them to refs/remotes/origin/ locally. So, if there is a master branch on the server, you can access the log of that branch locally..." git-scm

*if there is a master branch*? That does not suggest "every" git repository has a "master". Fortunately this mystery was quickly solved by creating my own test repository and a subsequent search at Stackoverflow confirms this is technically true, a new git repository without *any* commits does not have a *master* branch:

> "Now, the reason you wouldn't have a master branch even after doing a git init is that there are no commits: when you create your first commit, you will then have a master branch." stackoverflow: "fatal: Not a valid object name: 'master'"

Its a strange example to find at the maintainers site, adding a remote repository without any commits, but in the Land of Oz customization to the *nth* degree is a known hazzard.

Now, returning the helpful advise I've received to this point. Kiamlaluno points out,

> "A Drupal development snapshot is created from a git branch, while a Drupal release is created from a git tag." Instead of git tag try with git branch."

And yet, still won't say what I'm about to say. Now its finally possible to understand **the `-dev` branch in Drupal as the "development snapshot" created from the "master" branch of the git branch hosted at Drupal.org.** The `-dev` branch label is not present in the branch command output *unless you put it there yourself* in your local cloned repository. This I've also tested, recently, because I found it useful to label my current working brach different than the remote master branch of the same name.

I chose to use the git versions and use git to make my own `-dev` branch of a few modules to troubleshoot the interaction of Views and Draggableviews modules, because. as Kiamlaluno points out, the tar and gzip files in the "Development releases" table are snapshots. Thus, by reason they are always older than the master branch.

---

In another curious event, here is a definition of snapshot from a Wikipedia Disambiguation Page,

> Snapshot: "A view of a source code repository as it was at a particular time for the purpose of revision control in software development." Wikipedia

Its ironic to find this definition for "source code repository" not in an wiki-article, or at wiktionary, but tucked away in a disambiguation page. Not ironic because the definition should be tucked away in a remote location, rather this brings to mind a printing term widow, which does have its own wiki-article page and wictionary entry, unlike git's 'master branch', or Drupal's '-dev branch' (at the time of this missive).
> 2 votes

---
Tags: version-control
---


# Question
Title: Problem with views edit link not appearing
I have created a view (block) that has contained in its fields user account information (including content profile fields). Along with that, there is an edit link to edit the profile information. The problem I am experiencing is; when logged in as a regular user, the edit link does not appear. When logged in as user 1 it does appear. I thought this would be a permission issue but I can't see what should be checked. I think I have enabled all the necessary permissions. Aren't users enabled to edit their profiles by default?

Here is a screenshot of the view's settings:

I am using Drupal 6.26 and views 6.2.16 and displaying this view in a panel. Any suggestions as to what I may be missing?

Thanks.

# Answer
> 1 votes
Found the answer to my problem. I had missed enabling access user profiles permission for authenticated users.

---
Tags: views, 6, users, panels
---


title: Create URL field

text:
# Question
Title: Create URL field
I want to create a field that is automatically filled with the current page URL, and displayed as a link. The user should not be able to change that field. How can I do this?

If coding is required, please describe exactly what, and where to code.

# Answer
Have a look at the Link module, it defines a link/url field. If you have the Token module, you might be able to use `[site:current-page:url]` as a default value for the field.
> 2 votes

# Answer
The link module accepts tokens.

I used it many time to build url in some of my content type to pass on the value of the `[node:id]`.

If you want to have the current url you have to use `[current-page:url]`.

In the default value of the link module write this `http://example.com/[current-page:url:path]`, and you will have the good result. I just test on my website (so don't forget to write your domain).

\[\]\]
> 1 votes

---
Tags: uri
---


# Question
Title: Use Javascript to Incrementally Add a Numer to a Selected Class
I am dynamically generating content using Drupal. I am running javascript that places a div before another div. The code works fine, and looks like this:

```
  $(function() {
    $('.views-row-1 .content .body').insertBefore('.views-row-1 .content .field-name-field-image-one');

   });

```

My issue is that because the content is generated dynamically, the class "views-row-#" changes incrementally. For example, if I have 3 elements of content on the page, Drupal will create the class views-row-1 for the first one, views-row-2 for the second, views-row-3 for the third.

What I have done (which is not ideal) is written out a line of code for each piece of content like so:

```
  $(function() {
    $('.views-row-1 .content .body').insertBefore('.views-row-1 .content .field-name-field-image-one'); // check before() examples
    $('.views-row-2 .content .body').insertBefore('.views-row-2 .content .field-name-field-image-one'); // check before() examples
    $('.views-row-3 .content .body').insertBefore('.views-row-3 .content .field-name-field-image-one'); // check before() examples
    $('.views-row-4 .content .body').insertBefore('.views-row-4 .content .field-name-field-image-one')
   });

```

I will never know how many pieces of content there will be because it's dynamic, so I'm looking to have the javascript add the number to the class. Is this even possible?

# Answer
I don't think you really need to add the number to the class; the elements that you're targeting also have the `.views-row` class on them so you can use a bit of contextual jQuery to get the job done in a couple of lines:

```
$('.views-row').each(function(i,e) {
  $('.content .body', e).insertBefore($('.content .field-name-field-image-one', e));
});

```

I haven't tested that but I can't think of a reason why it wouldn't work.
> 2 votes

---
Tags: javascript
---


# Question
Title: Including call to drupal_get_form('user_login') causes seemingly endless loop in Firefox
One of the features that I've tried to include in my Drupal site is a persistent login form in the page's footer. After doing some searching around, I found that the best way to call the login in Drupal 7 is the following:

```
print drupal_render(drupal_get_form('user_login'));

```

So, I put this in a simple if/then statement that looks like this:

```
<?php
global $user;

    if ( $user->uid ) {
        echo "<a href='admin/' target='_blank'>Go to Admin area</a>.";
    }
    else {
        print drupal_render(drupal_get_form('user_login'));
    }
?>

```

I then tucked this away in a jQuery accordion, and it was working just wonderfully in Chrome.

Then came Firefox. It loaded fine the first time, but then once I clicked on the accordion to view the login, it never loaded correctly again. I know that this is the culprit, because once commented out, the page loads fine in Firefox. Am I doing this call wrong?

# Answer
> 0 votes
Here's what ended up working. After debugging, Firefox (and my mountains of code) was having an issue with the core module OpenID. I assume that since it only recently became an issue that it's a particular problem for my particular framework.

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


# Question
Title: Module to do an action based on content type user sees
I would like to achieve, for my custom module, this behavior:

1. It triggers only when user sees the node of some content type
2. It does a calculation based on field present in that content type (it checks the values of taxonomy term assigned to that node)
3. It prepares a variable based on calculation (it might be a complex query)
4. article.tpl.php is injected with the content of that variable

# Answer
> 2 votes
Assuming you're using Drupal 7 you can do all of this in `hook_node_view()`, e.g.

```
function MYMODULE_node_view($node, $view_mode, $langcode) {
  // Check the node type and that the user is viewing a full node page
  if ($node->type == 'article' && $view_mode == 'full') {
    // Get some field values from the node
    $field_items = field_get_items('node', $node, 'field_name');

    // Get the first field value.
    $first_field_item = array_shift($field_items);

    // The index will depend on the type of field; for taxonomy term refs it's 'tid'
    $value = $first_field_item['tid'];

    // Perform some complex operation on the value.
    $new_value = MYMODULE_complex_op($value);

    // Add the new value to the node content, to be found in the $content array
    // in node--article.tpl.php
    $node->content['my_new_value'] = array(
      '#markup' => $new_value
    );
  }
}

```

In your template file you'll be able to call `print render($content['my_new_value']);` to output the variable to the page.

Obviously that'll need some adjusting for your own needs but hopefully it'll help.

---
Tags: nodes, database
---


# Question
Title: User redirect after changing profile information
I am having a problem trying to get the user to redirect to their profile page (user/uid) after they update their profile (user/uid/edit), I don't want them to remain on the page they just edited. I have looked high and low on drupal answers, google, and the documentation I can't get this to work.

Here is the code;

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

    global $user;
    switch ($form_id) {
         case 'uprofile_node_form':
             $form_state['redirect'] = 'user/'.$user->uid;
             break;
    }
}

```

I have tried everything including a submit\_handler and that doesn't work. I have tried including the base\_url - doesn't work either. What am I overlooking. I figure that this should work.

I read somewhere online that redirects will not work if $form\_state\['storage'\]\['values'\] is not empty. If this is the problem, how would I overcome it?

Thanks.

# Answer
> 1 votes
There were a bunch of issues with your example, but this should work:

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

  switch($form_id) {

    case 'user_profile_form':

      $form['#redirect']='user/' . arg(1);
      break;

    // any other forms here

  }

}

```

which will redirect to the user page of the user being edited after editing that user. This way, if an admin is editing another user, it redirects to that user's page, not that of the logged in admin.

---
Tags: 6, users, redirection
---


# Question
Title: How can I invoke Drush command inside hook_cron?
I have module that provides drush integration.

Now I want to create modules with hook\_cron where I want to launch drush command.

How can I run Drush command programmatically?

# Answer
You should not call drush from inside a Drupal module. Instead, factor out the functionality of your Drush commands into separate functions that can be called from module code and drush commandfiles alike. Your module code should do all user access / permissions checks before calling the API functions (usually via the access checks provided by Drupal's menu system); the Drush commands should call the API functions directly, without access checks.
> 4 votes

---
Tags: 7, drush, cron
---


# Question
Title: How do you access custom user information added from: Configuration » People » Account settings
I'm looking to create a script that pulls some of this information, but I need to know how to call it. For example one of the 'machine names' for one field is **field\_first\_name** how could I call this?

At the moment I'm using:

```
<?php
global $user;
print $user->name;
?>

```

Below is what I'm looking for, pulling the custom information instead of the username.

```
<?php
global $user;
print $user->feild_first_name;
?>

```

# Answer
try $account = user\_load($user -\> uid) after global $user and then dsm($account) or print\_r($account);, global $user get only basic data of object I think
> 1 votes

# Answer
Install the devel module. Now you are trying to access the currently logged in user profile so go to the user profile page like www.example.com/user and if you have proper permission you will see the complete user object user the devel tab which will be available next to the view and edit.

Also if you have the devel module you can access the global user profile like this in your code

global $user; dpm($user);

devel module: http://drupal.org/project/devel

devel debugging commands: http://ratatosk.net/drupal/tutorials/debugging-drupal.html
> 0 votes

---
Tags: users
---


title: Drupal automatic "antihack" behaviour

text:
# Question
Title: Drupal automatic "antihack" behaviour
I experience some difficulties with formalizing a question for Google, so I'm going to post it here and request real human help=)

Are there any systems (modules or smth similar) in Drupal that monitor user activity and detect possible malicious actions? And react automatically?

For example, in some form, a dummy user tries a certain kind of SQL injection. Typing something like `" or 1=1 --` or similar. This is obvious that this sort of data cannot be entered be accident. Drupal then detects this:"Ahah, this is going to be something like an SQL injection", then blocks the user IP for a month, for example, and logs all information about this event. Or sends an email to admin: "User @@ possibly tried to carry SQL injection while entering @@ form while doing @@ (situation description goes there) and was blocked for a month. See log at @@"

As I understand Drupal is pretty secure but it's secure in a passive way. I want to get it not only waiting for an attack and process it but also response to this attack. Or at least notify administrator of something anusual and therefore dangerous.

I hope you will understand what I want to get (not necessarily exactly what I mentioned) and extend the scope from my possibly idiotic imaginations to what is really used today.

# Answer
> 7 votes
I believe you're looking for the Drupal Tiny-IDS module:

> Minimalist, but performant intrusion detection system that monitors Drupal for malicious activities and targets to be simple to understand and easy to use.

It attempts to detect:

* XSS (Cross Site Scripting)
* SQLi (SQL Injection)
* Code execution (Local/Remote file inclusion, etc.)

And can 'react' in a bunch of different ways:

* Log entry
* Warning message (to the malicious user)
* Mail alert
* Rules integration (which you could use to disable the user account)

I think that ticks all the boxes :)

---
Tags: security
---


title: Setting up a drush sql-dump alias

text:
# Question
Title: Setting up a drush sql-dump alias
I have the following in my `aliases.drushrc.php` file --

```
$aliases['prod'] = array(
    'uri' => 'foo.com',
    'root' => '/var/www/foo/htdocs',
    'remote-host' => '123.456.78.90',
    'remote-user' => 'bob',
    'databases' =>
      array (
        'default' =>
        array (
          'default' =>
          array (
            'driver' => 'mysql',
            'username' => 'foo',
            'password' => 'bar',
            'port' => '',
            'host' => 'localhost',
            'database' => 'foodb',
          ),
       ),
     ),
    'shell-aliases' => array (
        'dump' => '!drush sql-dump --gzip --ordered-dump',
    ),
  );

```

When I run `drush @prod dump` it attempts to connect to `'remote-host'`. If I comment out `'remote-host'` it dumps just as expected. I do need this value though for other functions such as `sql-rsync`.

I could create a new alias just for dumping but this seems a little excessive.

Any ideas?

# Answer
> 4 votes
Drush decides whether a site is local or remote via the function `drush_is_local_host`. Make up a domain name for your system, such as foo.local, and make an entry for it in /etc/hosts (123.456.78.90 foo.local). Next, make sure that /etc/hostname also contains foo.local, and confirm this by running `hostname -f`. If you do all of this correctly, then you can set `'remote-host' => 'foo.local'`, and Drush will still treat it like localhost for commands such as sql-sync.

---
Tags: drush
---


# Question
Title: Displaying taxonomy term list within another taxonomy term
I have a vocabulary that list schools that users can select on registration and other vocabularies for books and courses, used on nodes.

Under each school's term page I would like to display a list of terms from Book vocabulary and other vocabularies and clicking on the any of the terms will list nodes with the term.

CT\>Ucon

* Books
    + textbooks
    + fiction
    + animes

I have thought of using panel to display school terms and then place a block of the book terms in a region in the panel, but I'm not sure how to go about it especially the URL. I would like the url to look like uconn/books/texbooks.

Additional info: Craigslist has similar nested categories. You have city category then under each city you have sale, services, community sections. This is what I'm trying to achieve. I want each school to have their own sub-categories listed under them.

# Answer
Dee, I completely did not understand your question. But these code might help you.

```
/*To load a vocabulary*/

 $vocabulary = taxonomy_vocabulary_machine_name_load($machine_name);
 Example::$vocabulary = taxonomy_vocabulary_machine_name_load('book');

/*To get array of all term objects as a tree*/

$terms = taxonomy_get_tree($vocabulary);

/*To get children of all terms*/

foreach($term as $aterm) {

  $child = taxonomy_get_children($aterm);

}

```
> 0 votes

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


# Question
Title: Safe string checkup against user-supplied suffix/prefix strings
> **Possible Duplicate:**
> Is check\_plain() enough?

When authoring own plugin/formatter and giving user an option to provide their own HTML prefix and suffix strings , what would be the Drupal way of ensuring safety of those strings? Would it suffice to `filter_xss` with custom list of allowed tags, or a sequence of some functions would be required?

# Answer
> 0 votes
Treat it like any other user input; that is, not to be trusted. Do you have a reason to allow HTML tags in the prefix/suffix? If not, output only after running through check\_plain(). filter\_xss() is quite permissive in its allowed tags so just be sure you're OK with that before using. See also the drupal.org documentation on handling text in a secure way.

---
Tags: theming
---


title: drupal_queues for drupal 6

text:
# Question
Title: drupal_queues for drupal 6
So this all starts when I hit my php memory limit, I know I can increase my php memory limit... but in order to get the process that I needed running I had to up my limit to 1026M... and I dont think that this is the right way to go.

My process needs to run using cron, so I first looked to batch processing... its very usefull and works well, except when implemented with cron.

I know see that the right path is to use the d7 backport of drupal\_queues.

I would put up some code, but what I am really trying to understand is the logic behind setting up and processing a queue using drupal\_queues and cron.

So far this is what I got:

I set up hook\_queue\_info:

```
function mymodule_cron_queue_info() {
  $queue['mymodule_queue'] = array(
      'worker callback' => '_mymodule_queue_worker',
      );
  return $queue;
}

```

I setup hook\_queue\_worker($item)

```
function _mymodule_queue_worker($item) {
  $acc_id = $item['acc_id'];
  //Collect list of relevant campaign ID's
  $campaignNIDs = mymodule_get_campaignNIDs($acc_id);
  dpm($campaignNIDs);
  foreach($campaignNIDs as $key => $value) {
       $CampaignNID = $value;
       mymodule_collect_contact_actions($acc_id, $CampaignNID);
  }
}

```

And then I worked in the hook\_cron

```
function mymodule_cron(){
  //Adding drupal_queue into the cron
  $items = mymodule_get_all_accounts();
  //This is the list of items that we need to itterate through
  //This will be the different ESP accounts
  $queue = drupal_queue_get('mymodule_queue'); //grab the queue
  $queue->createQueue(); //initiate the queue
  foreach ($items as $item) {
    $queue->createItem($item); //each item passed as param to worker
  }

  drupal_queue_cron_run();

```

So far this works and allows me to call each account separately in the queue. but now I have processes(functions) that need to be run per account. Ho would I add these processes as a "Sub-queue" to the queue that is currently being processed.

Do I need to do this or is what I have so far satisfactory?

Any light on this subject would be really appreciated as the documentation on this subject is somewhat lacking

# Answer
> 1 votes
There's no concept of a "sub-queue", it's just queues, items in the queue, and workers of a queue (on items). Without knowing more about your use case I'd say you should may want to have a queue per account. Or create a queue item containing the account its for and working that way. So, you can either have many queues with some items in each or one queue with a whole bunch of items.

---
Tags: 6, cron, queue
---


# Question
Title: Form theme function is not invoked for a block content
Have a custom module with a block. Added form and form theme functions. Using hook\_theme() to register form theme function.

Trying to put form content in the \_block\_view() function into block content. But finaly it doesn't use form theme function - theme\_mymodule\_custom\_form()

The form is displayed on a block, but theme function is not in use, Have no idea how to make this work. Found a good sample here http://www.jaypan.com/comment/1758, but it didn't help me.

```
 function mymodule_block_view($delta = '') {
  switch($delta){
    case 'mymodule':
      if(user_access('access content')){
        $block['subject'] = 'Block header';
        $block['content'] = drupal_get_form('mymodule_custom_form');
      }
    return $block;
  }
 }

function mymodule_theme()
{
    return array
    (
        'mymodule_custom_form' => array
        (
            'render element' => 'form'
        ),
    );
}

/**
*  Create a form
*/
function mymodule_custom_form($form, $form_state) {
  // Form elements
  $form = array();

  // Text field
  $form['Input'] = array(
    '#title' => t('Input field'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );

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

    // Get the path to the module
    $path = drupal_get_path('module', 'mymodule');
    $form['#attached'] = array
    (
        'css' => array
        (
            'type' => 'file',
            'data' => $path . '/css/style.css',
        ),
        'js' => array
        (
            'type' => 'file',
            'data' => $path . '/js/sample.js',
        )
    );

  return $form;
}

function theme_mymodule_custom_form($variables )
{
    // Isolate the form definition form the $variables array
    $form = $variables['form'];
    $output = '<h3>Themed form</h3>';
    $output .= drupal_render($form['Input']);
    $output .= drupal_render_children($form);
    return $output;
}

```

# Answer
Add $form\['#theme'\] = "my\_theme\_form"; in your form.

I always use this base for theming forms and work without problem.

```
function contact_form() {

    $form['name'] = array(
        '#title' => t('Name'),
        '#type' => 'textfield',
        '#required' => TRUE,
    );

    $form['mail'] = array(
        '#title' => t('e-mail'),
        '#type' => 'textfield',
        '#required' => TRUE,
    );

    $form['comment'] = array(
        '#title' => t('Comment'),
        '#type' => 'textarea',
        '#required' => TRUE,
   );

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

    $form['#theme'] = "my_theme_form";

    return $form;
}

function MYMODULE_theme() {
  return array(
    'my_theme_form' => array(
      'render element' => 'form'
    ),
  );
}

function theme_my_theme_form(&$vars) {

    $form = $vars['form'];
    $output = "";

    //Render separated fiels
    $output .= drupal_render($form["Input"]);
    $output .= drupal_render($form["submit"]);

    //And the rest of your form
    foreach (element_children($form) as $key) {
        $output .= drupal_render($form[$key]);
    }

return $output;
}

```

That's all. just call the form in a block for example:

```
$form = drupal_get_form("contact_form");

```
> 0 votes

# Answer
Somehow, this started working on my localhost. I think this was a cache issue. If you have the same problem, try clearing the cache.
> 0 votes

---
Tags: forms, blocks, theming
---


# Question
Title: Getting a specific value from form api in theme-settings.php
In my custom theme I am developing, I have a form API setting in `theme-settings.php` that lets a user choose one of two options with a select menu as such:

```
 $form['txtr_settings']['general_settings']['choose_slideshow'] = array(
        '#type' => 'select',
        '#title' => t('Choose a slideshow'),
        '#default_value' => theme_get_setting('choose_slideshow'),
        '#options' => array(
            'basic' => t('Basic'),
            'fancy' => t('Fancy'),
        ),
    );

```

Then in my theme's `page.tpl.php` I want the value the user has selected to be part of an if else statement.

Right now I have this code which does not seem to work:

```
<?php if (theme_get_setting('choose_slideshow') == 'basic')
            include(dirname(__FILE__) . "/slideshow_alpha.inc");
        else
            include(dirname(__FILE__) . "/slideshow_beta.inc");
  ?>

```

I know if I have a simple single checkbox (checked = yes or '1' I can do something like this:

```
<?php if (theme_get_setting('choose_slideshow') == 1)

```

... but in this case I really want to show the user both options and have them choose one or the other in the select menu.

If I use either option on it's own without the if / else, each works fine so I think it's a question of my `theme_get_setting` value. I am not really sure if this is a Drupal question or a PHP question that I should ask over on Stack Exchange.

# Answer
> 0 votes
The way to really do this was to create variables in template.php using a preprocess function and take some of the logic out of page.tpl.php and to instead use the actual variables created. Based on this, my updated code that's working is:

***template.php***

```
function my_theme_preprocess_page(&$variables) {
 // create variables for each slideshow
  $variables['slideshow_alpha'] = (theme_get_setting('choose_slideshow') == 'alpha');
  $variables['slideshow_beta'] = (theme_get_setting('choose_slideshow') == 'beta');
}

```

... and then in ***page.tpl.php***

```
 <?php if ($slideshow_alpha): ?>
    <?php require_once dirname(__FILE__) . '/slideshow_alpha.inc'; ?>
  <?php else: ?>
    <?php require_once dirname(__FILE__) . '/slideshow_beta.inc'; ?>
  <?php endif; ?>

```

It's important to note that what helped me figure much of the code updates out were running it through PAReview.sh. However, I did not want to set up the module and there is an online version which works great but your code needs to be in a git repo on drupal.org so you would have to set up a simple sandbox project to test your code. The online version is on ventral.org and it's what drupal.org uses to review projects. The new updated code also does not throw any errors with the code sniffer an the old code did.

---
Tags: theming, forms
---


# Question
Title: How to prevent non-English characters from turning into jumbled words?
Whenever I move database, even within the same server the non-English characters change into words that are unreadable. My site is not multilingual (it will be in the future) but users post products titles with accents and in French, Polish or another language. How do I retain the characters and prevent the jumbled words? Thank you.

# Answer
This is a bit of a guess, but it sounds like some part of the process isn't UTF-8 clean. If Drupal is displaying everything properly, then it sounds like the database actually is UTF-8. This leaves phpMyAdmin.

I would log into phpMyAdmin with Firefox. Right-click, and do View Page Info. Make sure the encoding say UTF-8.

Then install the Live HTTP Headers plugin. Download a backup and restore one with the plugin running. Make sure the Content-Encoding is always UTF-8.

If any of them aren't, then you have some server-specific configuration to fix.

Personally, I think phpMyAdmin is a terrible tool and a security risk. I use the legacy MySQL Administration Tool for most of my server work and a fair number of backup tasks. You can also try the Backup and Migrate module for taking and restoring backups. You can also use the `sql-*` and/or `bam-*` commands in drush.
> 1 votes

---
Tags: database
---


# Question
Title: Wrapping multiple cck fields into a single div tag for theming?
I have a content type that uses many cck fields, and I would like to theme the content type by grouping certain fields in "blocks" (not Drupal blocks but div blocks), preferably div tags, so that the fields aren't just displayed one after the other. I can edit the css of individual fields, but if I want a field to be in a div on the top right hand corner of my node types page, and then another group of fields to be along side it, and then another group of fields to fall underneath all of the other fields, that css could get messy and interfere with my themes main css. I'm not sure what to put in my template file, since all the fields just fall under "content."

I'm using Drupal 6, and a little new with php, but can do basic "print" and "if" conditions. Any help would be greatly appreciated! Thanks in advance!

# Answer
In your node templates, you have access to the `$content` variable, which includes all of your fields mushed together as CCK et al wants them, but you also have the `$node` object which includes all the raw information about your node.

So, first thing to do is to put a

```
<php drupal_set_message('<pre>' . print_r($node, TRUE) . '</pre>'); ?>

```

at the beginning of your `node-TYPE.tpl.php` file to see what you have to work with fieldwise. There you will see lots of information, but basically, it is broken down into stuff like

```
 field_name[0]['value'] = // raw information stored in the database
 field_name[0]['safe'] =  // the above info in a safe format
 field_name[0]['view'] =  // the above info passed passed through the widget

```

So. If you want to put some of the fields in one `<div>` and some in another you can do something like

```
 <div class="whatever">
   <?php print $node->field_name[0]['view']; ?>
   <?php print $node->another_one[0]['view']; ?>
 </div>
 <div class="another">
   <?php print $node->yet_another[0]['view']; ?>
   <?php print $node->one_more[0]['view']; ?>
 </div>

```

Now, of course, you probably don't want to create everything yourself, so you then add

```
 <?php print $content; ?>

```

but lo and behold, you get the fields you printed manually in there as well. To get rid of that duplication, go into your content edit screens and in the Display Page (`admin/content/node-type/NODETYPE/display`) just exclude them from `$content` in your teaser and/or full node display) and they *should* be displayed just once now in your custom `<div>`s.

When all is working, take out that `drupal_set_message()` so you don't totally confuse your users :)
> 1 votes

---
Tags: theming, entities
---


title: Validate textfield

text:
# Question
Title: Validate textfield
I created a custom content type with textfield called productID. Well all the data is imported and now he wants that field to be validated against a list of productId's. I have not imported the list if productID's yet so I can put them in a taxonomy, however how would I go about validating against this list so when they go to save the content type it returns false if not in the list and not allow them to save.

Thank you

# Answer
First you should add a validation function to your form in your custom module , in hook\_form\_alter

```
function yourmodule_form_alter(&$form,$form_state,$form_id) {
  if($form_id == 'yourform_name') {
       $form['#validate][]='yourcustom_validate_function';
      }
}

```

and after it you can everywhat you want in yourcustom validation function

```
function yourcustom_validate_function(&$from,&$form_state) {
  'your validation come here'
  if('not validate')
     form_set_error('yourfieldname',t('error message'));

}

```

I suggest you perform validation and get taxonomy with `taxonomy_get_term_by_name`,Its help you.

This links can help you more
drupal form\_alter
custom drupal form validation1
custom drupal form validation2
form\_set\_error
> 1 votes

# Answer
If you are using feeds (http://drupal.org/project/feeds/) to import your data you can also use feeds tamper (http://drupal.org/project/feeds\_tamper) to validate the data. Here is all the available option you have when using the feeds tamper (http://drupal.org/node/1246578)
> 0 votes

---
Tags: 7, forms
---


# Question
Title: How do I dynamically fill a textfield with #ajax?
As the title states, I'm wondering how I dynamically fill a textfield using an AJAX callback from a "select" form field.

I'm trying to test a select form with a number of options that, when changed, populates the textfield with data. I've tried setting the textfield's "`#default_value`", but it doesn't seem to work. Setting "`#value`" does work and I do get the information to show up in the textfield but this presents another problem. When I try to go to the next step and have a button save the data, the textfield's value remains what I set it to and doesn't change. What I mean is that when I select an option in the select form, the textfield gets populated correctly but if I change the textfield and hit save, the `$form_state` value is still what I set it to not what I changed it to. Is what I'm trying to do even possible?

```
$form['profiles'] = array(
    '#type' => 'select',
    '#title' => 'Profiles',
    '#options' => $profiles,
    '#ajax' => array(
        'callback' => 'profile_callback',
        'wrapper' => 'profile-wrapper'
    )
);

$profile = isset($form_state['values']['profiles']) ?
             _get_profile_info($form_state['values']['profiles']) : NULL;

$form['profile_name'] = array(
    '#type' => 'textfield',
    '#prefix' => '<div id="profile-wrapper">',
    '#suffix' => '</div>',
    '#title' => 'Profile Name',
    '#value' => $profile == NULL ? '' : $profile[0]->{'name'}
);

$form['profile_save'] = array(
    '#type' => 'submit',
    '#value' => t('Save Profile'),
    '#submit' => array(
        'save_profile'
    )
);

```

I'm saving the value of my textfield from the `$form_state` into a file for testing right now.

```
function save_profile($form, &$form_state){
    $fh = fopen('C:\out.txt', 'w+');
    fwrite($fh, $form_state['values']['profile_name']);
}

function profile_callback($form, &$form_state){
    return $form['profile_name'];
}

```

# Answer
> 3 votes
After messing with this for a while, I discovered that I needed to unset the textfield. Once I did this default\_value started to work with ajax, below is the final code I had.

```
unset($form_state['input']['profile_name']);

$form['profiles'] = array(
    '#type' => 'select',
    '#title' => 'Profiles',
    '#options' => $profiles,
    '#ajax' => array(
        'callback' => 'profile_callback',
        'wrapper' => 'profile-wrapper',
    ),
);

$profile = isset($form_state['values']['profiles']) ? _get_profile_info($form_state['values']['profiles']) : NULL;

$form['profile_name'] = array(
    '#type' => 'textfield',
    '#prefix' => '<div id="profile-wrapper">',
    '#suffix' => '</div>',
    '#title' => 'Profile Name',
    '#default_value' => $profile == NULL ? '' : $profile[0]->{'name'},
);

```

# Answer
> 2 votes
@Sathariel I don't think you need to do `unset($form_state['input']['profile_name']);`

This is what I'd do to make it work, since it works for me:

```
$form['profiles'] = array(
    '#type' => 'select',
    '#title' => 'Profiles',
    '#options' => $profiles,
    '#ajax' => array(
        'callback' => 'profile_callback',
        'wrapper' => 'profile-wrapper',
        'event' => 'change',
    ),
);

$form['profile_name'] = array(
    '#type' => 'textfield',
    '#prefix' => '<div id="profile-wrapper">',
    '#suffix' => '</div>',
    '#title' => 'Profile Name',
);

function profile_callback($form, &$form_state){
    $form['profile_name']['#value'] = _get_profile_info($form['profiles']['#values']);
    return $form['profile_name'];
}

```

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


# Question
Title: How to stop the script drush if previous command failed?
Any idea how can I tell the script/drush to stop when the previous command failed?

Ex:

```
#!/bin/sh
#
echo "Disabling parallel config..."
drush vset parallel_enabled 0

drush vset preprocess_css 0
drush vset preprocess_js 0
drush cc all

# Disable Mobile theme
echo "Disabling Mobile theme..."
drush dis --yes mobiletheme

# Disable Zen theme
echo "Disabling Zen..."
drush dis --yes zen

# Running the site to offline mode
echo "Running site in offline mode..."
drush vset --yes site_offline 1

# Deleting node revisions
echo "Deleting node revisions..."
drush delete-revisions -y

echo "Clearing all the caches..."
drush cc all

# Rename duplicate files
echo "Renaming duplicate files..."
drush rename-duplicate-files

drush pm-uninstall publication_date -y
drush pm-uninstall date -y
drush pm-uninstall custom_pagers -y
drush pm-uninstall custom_breadcrumbs -y

```

I want something like this:

```
#!/bin/sh
#
echo "Disabling parallel config..."
drush vset parallel_enabled 0
if [ ! success ]; then
  echo "The command failed to execute."
  exit
fi

```

# Answer
Checkout the run\_cmd function in this file: base\_functions, which wraps any command and terminates the script if it fails.

You should also be able to do something like:

```
drush cc all || exit;

```

where exit will only run if the previous command fails, and you could replace exit with a call to a function that outputs a more meaningful error message. You may also add a number between 1 and 255 after `exit` to have your script emit an exit status that can be used further using `$?` in any other script calling this one.
> 2 votes

---
Tags: drush
---


title: Get main menu in to my search page

text:
# Question
Title: Get main menu in to my search page
I'm using the built in search in Drupal 7. My problem is that I need to customize the search page. Is it possible to get the search results into a panel so that I can output my main menu and a few other elements? Now My search result page is very bare.

# Answer
You can customise your search-results.tpl.php by copying this file from the core search module and putting it into your theme directory. You can add your menu in where you like using code:

```
<div id="menu">
  <?php print theme('links__system_main_menu', array('links' => $main_menu)); ?>
</div>

```

Also remember to clear your cache after making changes!
> 0 votes

---
Tags: search
---


# Question
Title: Custom error page: The path is either invalid or you do not have access to it
I'm trying to add a custom page, by using `admin/config/system/site-information`

When I enter the field, as follows:

**Default 404 (not found) page**

```
http://mysite.com/errors/404.html

```

It shows the following error:

`The path 'errors/404.html' is either invalid or you do not have access to it.`

Though when I enter in my browser: `http://mysite.com/errors/404.html` it opens just fine.

So, what's wrong with `Drupal`, why it doesn't see it?

# Answer
When you go to `admin/config/system/site-information` to enter the path in the field **Default 404 (not found) page**, you don't have to add `.html` just write `errors/404` and it will work.
> 2 votes

# Answer
I suppose if properly, you have directory "errors" where have a file 404.html. In Drupal one of the right way to do this is like next: create node Page content type (may by only enter title, see and remember node id after saving), copy node.tpl.php from modules/node folder in your current theme folder, rename this copy to node--NID.tpl.php where NID is id of previosly saved node, then edit this template as you want, then add path alias to this node as "errors/404.html"
> 1 votes

---
Tags: 7, uri
---


title: node_submit fill start/end date field

text:
# Question
Title: node_submit fill start/end date field
I have the following code:

```
            $node = new stdClass();
            $node->type = 'enterprise_event';
            node_object_prepare($node);
            $node->title = $event->title;
            $node->venue = $event->venue;

```

My enterprise\_event content type also has a date field which is a (start\_date - end\_date) field, but using the devel module it shows that the field is called date. How can I set the date-\>start\_date, date-\>end\_date values?

Is there something like $node-\>date-\>start\_date?

# Answer
The db columns for a date field's start and end are `value` and `value2` respectively. The usual method to set them would be:

```
$node->field_date[$node->language][0]['value'] = $from_date;
$node->field_date[$node->language][0]['value2'] = $to_date;

```
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: how to resize image programatically with theme image
i need to resize image in my module output, but this code seems not working

```
$file = file_load($fid);
$image = theme('image', array('style_name'=> 'small', 'path' => $file->uri, 'alt' => 'user picture'));

```

i am getting my image from database. i have created media type **small** to scale my image, but **style\_name** does not work.

# Answer
> 3 votes
You need to use `theme_image_style()` for that one:

```
$image = theme('image_style', array(
  'style_name'=> 'small',
  'path' => $file->uri,
  'alt' => 'user picture'
));

```

---
Tags: media
---


# Question
Title: Is there a module to show photos on Drupal site that come from Facebook user profile/Facebook page, like Wordpress Fotobook
Wordpress Fotobook plugin will show photos from a user's Facebook profile (assuming the user has set the appropriate permissions for them to be made visible, and that suitable Facebook App settings and id have been setup).

I wondered if there was an equivalent module for Drupal?

I would prefer a module that doesn't locally copy the photos onto the site but rather links to the original photos on Facebook. This preference is be efficient with bandwidth, storage space, and backup. Effectively, I'm looking for something that makes Rvisible album photos in a similar way to RSS feed (doesn't have to be exactly the same format as RSS but the same kind of idea whereby the original content is not copied.)

I am developing sites for two friends who actively use Facebook but want photos on their own sites. With the Drupal 7 Media module, multi-image batch uploading is very capably handled in Drupal, however this still requires double effort to upload photos both to their profiles and their sites.

Let me know if a module is available. I am considering writing one myself, learning from Fotobook, but didn't want to duplicate effort.

# Answer
> 0 votes
There is a sandbox project: http://drupal.org/sandbox/kcmanc87/1591712 And maybe Feeds would work. I will try both soon.

# Answer
> 0 votes
Kept this open for a while but there has been no answer so I guess not. So, another module for my to do list to write, once I am fluent in writing modules and the Facebook APIs.

---
Tags: 7, media, feeds, importing-exporting, social-network
---


# Question
Title: Add users from SSO server database to Drupal
I am trying to implement an SSO system for Drupal system. The detailed description of the scenario can be seen in "Understanding Drupal's session management and user authentication".

I did implement the authentication part, as per the using the suggestions provided (thanks to Pierre Buyle). Now, I have a requirement to add the users to Drupal database which are already present in SSO database.
The IT team of SSO will create a form which will post this values to a URL on the Drupal site.

This URL have to catch the request and create a user in Drupal. I'll be using the method `user_save()` to achieve this.

My questions are:

1. How do I create this URL in Drupal? (Thought of using `hook_menu` and use `$items` to create the URL, but I don't want it to be accessible to users except admin.
2. How could I read the data from that URL?

I'm not asking for the complete code. Just pointers to which *hooks* or *methods* should I use for the use cases would be enough.

# Answer
> 3 votes
IMHO, integration of different system through form POSting is at the hack level. To let external system inject data into Drupal, the Services module let you easily build HTTP REST API in Drupal. It comes out of the box with a user API that allow external system to easily create new Drupal users.

Off course, you can create your own *page* to receive POSTed data from a form build outside Drupal. You simply have to declare it through a `hook_menu()` implementation. For access control to the page, you can either use the `'access arguments'` to restrict access with Drupal permission system. you can also use your own `'access callback'` to implement your own access control logic (ie. for instance, using a secret token based access control).

# Answer
> 1 votes
Used `hook_menu()` to create an URL, and got the values which were POSTed on this URL (as per @Pierre 's suggestion)

```
function MYMODULE_menu() {
    $items['add-new-user'] = array (
        'title' => '',
        'type' => 'MENU_CALLBACK',
        'page callback' => 'MYMODULE_add_new_custom_user',
        'page arguments' => array($_POST),
        'access arguments' => array('access administration pages'), //Admin access only
    );
    return $items;
}

```

In the function to create user, used `user_save()` to save the user.

```
function MYMODULE_add_new_custom_user($post_value) {
    $account = new stdClass();
    $account->is_new = TRUE; //This is a new account
    $edit = array (
        'roles' => array(
          //left empty because only needed to create authenticated users
        ),
        'administer_users' => FALSE,
        'name' => $post_values['username'],
        'mail' => $post_values['mail'],
        'status' => FALSE,   //newly created user would have STATUS as blocked.
        'notify' => 0,
        'timezone' => 'America/Chicago',
        'signature' => '',
        'picture' => '',
        'picture_delete' => '',
        'picture_upload' => '',
        'signature_format' => 'filtered_html',
        'pass' => $post_values['pass'],
        'init' => $post_values['mail'],
    );

    $user_obj = user_save($account, $edit, 'account');
    if(isset($user_obj->uid)) { //as $user_obj will be an object of stdClass and not an array.
      //user created
    }
    else {
      //some error occurred, handled seperately;
      //user_save returns FALSE if saving a users returns any error.
    }
}

```

---
Tags: 7, hooks, authentication-authorization
---


# Question
Title: Userpoints: deduct points programmatically
Is there a way to programmatically deduct points from user points?

I want to deduct points from users if a certain "featured Item" field is checked when they create a new content, but don't want to deduct points from users that created content without "featured Item" checked.

# Answer
> 6 votes
You can use userpoints\_userpointsapi and pass points in negative if you want to deduct.

example

```
    $params = array(
      'uid' => $user->uid,
      'points' => -5,
      'operation' => 'mymodule_some_operation',
    );
    userpoints_userpointsapi($params);

```

For more information http://drupal.org/node/993376 http://api.worldempire.ch/api/userpoints/userpoints-7.x-1.x%21userpoints.module/function/userpoints\_userpointsapi/7-1

---
Tags: 7, userpoints
---


title: Truly Uninstalling Modules

text:
# Question
Title: Truly Uninstalling Modules
So being relatively new to Drupal development (I have experience programming in other Content Management Systems and writing bespoke functions in PHP/MySQL) I noticed something interesting...

I realised after some development that the custom modules I had installed by uploading to */modules/* should actually have been uploaded in */sites/all/modules/* to avoid being overwritten on a Drupal update.

So I swiftly deleted the modules via FTP, cleared the cache, reuploaded in the correct directory, cleared the cache and continued where I left off.

What I found interesting was that all of the settings I applied to these modules had been remembered.

So my question is, why did this happen? Do modules have access to the DB and store variables there?

And so, if you want to truly remove a module and all its attachments from Drupal, how do you go about this (If it is just a case of storing in DB, then obviously you could delete through phpMyAdmin...but are there any other things to look for that could be left behind)?

Beginning to develop for drupal, it's good to know what is "under the hood" and that's why I ask this question.

Thanks so much for your time, Scott

# Answer
> 1 votes
Without disabling/uninstalling the modules, you deleted and placed them in different folder. So here the beauty is Drupal will automatically scan for modules in modules/ and sites/ folder. Thta's why for Drupal the module is still in use.

Disabling a module means, the module is currently not in use, however its data(like DB tables), configuration and everything will kept.

Uninstalling a module means, the module is completely removed. Its data, configuration everything will be cleared.

However the particular module folder will not be deleted.

# Answer
> 0 votes
Depending on the nature of the module, most of the use the DB to store settings/data. Some small modules might not do this though.

Anyway if you want to delete a module, go to "admin/modules/uninstall" to uninstall your module and then remove it from your server. This way you can keep you DB clean.

---
Tags: 7
---


title: Panels and pager in the pane

text:
# Question
Title: Panels and pager in the pane
Is it possible to load next page of the view inside a pane (by using pager)?

# Answer
> 0 votes
Actually, I found out what was missing. I had to turn on Ajax, in the View.

# Answer
> 1 votes
If I understand the question correctly, you need to set the *Use panel path* to *Yes* in order for things like pagers, exposed filters/exposed sorting, and ajax to work properly.

---
Tags: 7, panels, paging
---


# Question
Title: Checkboxes in exposed form in block aren't checked in initial state
I have views with exposed form.

In filter criteria I have filter category which has 4 checkboxes.

If I choose to display exposed form in block, in initial state checkboxes aren't checked but results appears for each of them. It seems like a bug, user is not selected nothing but results are there. I want to these checkboxes be checked in initial state when the page is opened.

If exposed form isn't displayed in block, the checkboxes are checked in initial state.

I also try to change with form alter but without success, I couldn't print anything

```
function module_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'views_exposed_form':
            krumo($form);
        break;
    }
}

```

# Answer
To do so you might have to checkboxes when you expose the form and save the view.
> 0 votes

---
Tags: views, forms
---


# Question
Title: Drupal changes my markup in full html mode
While editing body of the node in Full HTML format, i enter these lines:

```
<div style="text-align:right">
    string 1<br />
    string 2<br />
    <br />
    string 3
</div>

```

But the real generated html is:

```
<div style="text-align:right">
    string 1
    <br>
    string 2
    <p>string 3</p>
</div>

```

What's wrong with that? Why Drupal changes my code in full html? I don't want any extra `<p>`'s because it breaks the layout.

# Answer
> 7 votes
By default the Full HTML format has the

> Convert line breaks into HTML (i.e. `<br>` and `<p>`)

option selected. If you don't want that behaviour, just go to http://mysite.com/admin/config/content/formats/full\_html and deselect that option:

---
Tags: theming
---


title: Drupal views contextual filters

text:
# Question
Title: Drupal views contextual filters
I have set up a Drupal View (as a block) listing a number of books in my left sidebar (an unformatted list of fields, title, image etc.), in the main area the individual book is displayed as you click on the image in the left sidebar. Is it possible to use the contextual filters to disable that particular book from my view in that left sidebar? I'm relatively new to Drupal! Many thanks if anyone can help!

# Answer
Yes, you can use a contextual filter on a node `nid`. For its value, select a default argument (since a block won't have it) and then select `node id from url`. Then also click on `exclude the argument`. This will create a contextual filter that excludes the node on the page from the View.
> 3 votes

---
Tags: views
---