# Question
Title: drupal 7 date field stores todays date even when user hasnt entered a value
I don't want it to! :-)

I'm using custom forms implementing a date field, then saving values manually to a node later. I could add an extra step preventing the value from being saved to the node, but I won't have the necessary info available to calculate whether to do this if it's an 'edit'.

Any ideas? I just dont want to save a value if the users doesnt enter anything. Seem's simple enough to me... :-S

# Answer
> 0 votes
By Form API reference you need to manually set `'#default_value'` to prevent it from defaulting to `today`. So just add:

```
'#default_value' => NULL,

```

to your field's array to prevent it.

---
Tags: datetime
---


title: How to render a node field

text:
# Question
Title: How to render a node field
I can get the field using `entity_metadata_wrapper` like this

```
$node = node_load($nid);
$node_wrapper = entity_metadata_wrapper('node', $node, array(
    'langcode' => $GLOBALS['language'],
    'bundle' => 'unit'
     )
);

$field_value = $node_wrapper->field_photo->value();

```

And that returns an array which I don't know how to render. I tried `drupal_render()` but it seems that it doesn't do the job.

So how can I render this field ?

# Answer
> 3 votes
The photo field is an image field? The value() function returns an array which is actual file data linked to the image. To render (or to create a renderable build), you can for example use `theme_image` function, which prints out an \<img\> tag.

```
$node = node_load(43);
$node_wrapper = entity_metadata_wrapper('node', $node, array(
    'langcode' => $GLOBALS['language'],
    'bundle' => 'subject'
));

$field_value = $node_wrapper->field_teaser_image->value();
$build = array(
    '#theme' => 'image',
    '#path' => $field_value['uri'],
    '#alt' => $field_value['alt'],
    '#title' => $field_value['title'],
    '#width' => $field_value['width'],
    '#height' => $field_value['height'],
);

print drupal_render($build);

```

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


# Question
Title: Drupal showing blank page after migrating to a local server
(this question has been asked on Stackoverflow so I apologise for the repitition)

Firstly some background,..

IVe started a new job as PHP developer with a company that hosts 2 Drupal (6.x) sites.

While I have years of experience in PHP, Drupal ( and indeed off the shelf content management systems in general ) is a new one on me. Still, there is loads of documentation and its not rocket science, so no problems there.

The server environment is IIS (live server 7.0, locally 7.5) IIS is a totally new beast to me too, so it adds to teh learning curve.

I have successfully gotten a clean install of Drupal (7.x) to run locally, so I know the server is up and running correctly

The problem happens when I try to pull down the live site. I have replicated the database locally, and I know that it is connecting, however when I try to run the local site I get a blank page with the following source c ode:

```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en">
  <head>
    <?include '_inc_head_common.tpl.php';?>
  </head>

  <body id="body">

      <?include '_inc_header.tpl.php';?>
      <?include '_inc_content_3col.tpl.php';?>
      <?include '_inc_footer.tpl.php';?>
  </body>
</html>

```

So it seems that it is getting to a point and no further..

has anyone encountered this before or could someone point me in the direction that I should be looking at?

Thanks

Kevin

# Answer
Seems like you are using PHP shorthand. Can you change it to a proper and see if that helps? Please see if the path is correct since drupal is using relative path (base\_url, base\_path). Also please update the $base\_url in the settings.php if you have.
> 0 votes

# Answer
As your don't have the Gui error reporting running, you can check it out through the database with this query:

```
SELECT * FROM watchdog ORDER BY wid DESC LIMIT 2;

```

Also place this in the very beginning of your index.php:

```
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

```

Good luck!
> 0 votes

---
Tags: migrations, iis
---


# Question
Title: What hook function (is _form_alter correct?) do I use to alter the input submitted by the user into a views exposed filter form?
I'm developing a views exposed filter form for searching for items in given geographic locations.

I want to restrict this to a particular country so that cities with the same name in other countries aren't shown in the View results. For example only London, UK not London, Ontario; Portsmouth UK not Portsmouth New Hampshire, USA.

*(Note please don't close this topic as being too local - my question would apply to anyone who wants to do this whatever country they are in.)*

The simplest approach I want to consider is suffix the user input with the country. For my example this would be Newcastle becomes Newcastle, UK. Given that the site is focused on users in particular country, for user experience (UX) usability reasons I do not want the user to have to enter the country name at the end.

I had tried to add a function to do the suffixing by adding it as a callback in the `form[#submit]` array in `_form_alter` and implement the function in my custom module. But this did not alter my submitted input as required. Here is my code snippets:

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

// keep the standard handler
$temp = $form['#submit'][0];

// put my handler in first
$form['#submit'][0] = '_mymodule_custom_handler_submit';

// restore the standard handler to appear in the array after mine
$form['#submit'][2] = $temp;
}

function _mymodule_custom_handler_submit(&$form, &$form_state) {
    $form['field_geofield_distance']['origin']['#value'] .= ", UK";
}

```

When I try this I find (using `dpm` ) that the submitted input is not altered before it gets sent to the View for it to create the results - so I deduce that this code is not running before that, but instead after that.

Can you advise on what I might be doing wrong here?

Also, in the `$form['#submit']` array, are the callback functions "chained" together - i.e. in that the first function in the array gets called, it modifies the form submitted input and this is then passed to the next callback. If this were the case I would have expected my code to work.

Is `_form_alter` the right hook to use for this problem?

**Update**

Now using debugger (Komodo IDE) connected to my Vagrant VM-based local development environment that's running the site to investigate a solution:

Thanks.

**Update 2:**

I don't think this form handler approach is going to work, the screenshot below shows a callstack - see bottom right, showing that the views execute display function (presumably the view itself) runs before my code to modify the input

# Answer
There are 2 solutions, depending on what you are trying to do:

1. **For searching in a View of location specific items using geofield**: (the specific solution that I was looking for) append `",UK"` onto the $location variable in function `getSourceValue` in geofieldProximityGeocoder.inc in `proximity_plugins` in views folder of `geofield`. Notes if interested: This is a hack - it's altering the module code directly, so ideally we'd want to make this override-able in the conventional way - i.e. make the function hook-able so that it can be overridden in a custom module (or theme). I'll try to make a patch for all this. Also written up here: https://drupal.org/node/2070905
2. Normally, in **other exposed filter forms in general**, I believe the solution to modify user entered data at the exposed filter would be to use `hook_views_query_alter` https://api.drupal.org/api/views/views.api.php/function/hook\_views\_query\_alter/7 and modify the required input variable (that came from the user) contained in: exposed\_raw\_input array. Solutions offered by user20301 in their answer regarding handlers may also work, perhaps also for other behaviour that needs to occur when hitting the submit button. But for my solution I with location I needed something else as here I found that the entered location had already been calculated as I could see the long and lat values in the one of the arrays in the $query variable. So that led me to believe that geofield had already been involved and lo and behold it was.
> 2 votes

# Answer
First if you want to add submit handler as first in form\_alter do

```
//prepend the handler to array
array_unshift($form['#submit'], '_mymodule_custom_handler_submit');

```

So you dont overwrite any other callback by some other module.

Second, check that the form input elements dont have overriding submit handlers (" submit action on the buttons")

Third, try to assign the value with form\_set\_value

```
$oldValue = $form_state['values']['field_geofield_distance']['origin'];
$value = array('origin' => array('#value' => $oldValue. ', UK')
form_set_value($form['field_geofield_distance'], $value, $form_state);

```

Syntax above is not correct, but without knowing the structure of the field its impossible to know what kind of array it requires. For example Link module fields can be modified with following.

```
    // Set first link of the field pointing to google, most likely
    //unsets all the following ones
  $link = array(
    0 => array(
      'title' => 'Google',
      'url' => 'google.com'
    )
  );
  form_set_value($form['field_link'], $link)), $form_state);

```

Last but not least, use additional form validation callback instead submit handler, that way its sure that the values get passed to all "targeted(see second)" submit handlers.

Long story short. When form is being built, add input validator to it. Validator will get called after user sends the form and there you can modify values before they get submitted to submit handlers.

**Summary interpretating view flow**

While the view is being built first time it calls the form (which runs through standard drupal hooks like form\_alter) and gets the values from it just in case it has some defaults or accepts 0 filters.

After that it runs the queries, renders the form and the result. When finished you get the view including all the elements without user input. Like clean plate (mayby some contextual filters and stuff is applied but thats irrelevant?).

Next when the user sends the form with custom input, drupal (field widgets/handlers) transforms input to values and store them in $form\_state and passes them to validators. Here the custom validator can modify the user input values in $form\_state and attach them with form\_set\_value.

If the validation passes correctly $form\_state values(modified) get passed to submit handlers. Most likely views will start building itself from them. Heres more exact flow(pdf)
> 5 votes

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


# Question
Title: db_insert() execute() without auto_increment primary key is returning 0
I'm trying to determine whether a database insert query was successful or not by checking the return value of `execute()`, but it seems to be returning `0` even though I can see the data has been inserted into the database. The table I'm adding data to has a primary key but it's not set to auto increment.

```
$result = db_insert('my_table')
                    ->fields(array(
                      'user_id' => $user_id,
                      'my_value' => $num,
                    ))
                    ->execute();
print_r($result); //Prints 0, even when successful

```

How can I check to see if the `db_insert()` was successful or not if I'm not using an auto increment primary key?

Many thanks

# Answer
> 7 votes
That makes sense - if you haven't got an auto-increment field on the table, then you already *have* the ID that you're inserting, so it would make no sense for an arbitrary column (or primary key, or whatever) value to be returned by PDO.

If the query *fails* it will throw an exception. That's the best (probably only) way to check that the insert was successful in your case, short of running a separate query.

```
try {
  db_insert('...')->execute();
  // No exception thrown; PDO thinks the record was inserted correctly.
}
catch (PDOException $e) {
  // Query failed; recover based on $e->getMessage()
}

```

---
Tags: database
---


# Question
Title: How to check whether multi value field is of type field_collection_item or not?
I am trying to check the type of multi value field is a `field_collection_item` or not inside computed field using this code:

```
$wrapper = entity_metadata_wrapper($entity_type, $entity);
$fields_info = $wrapper->getPropertyInfo();
foreach ($fields_info as $req_field) {

  if ($req_field['type']=='field_collection_item') {
    //do something here
  }
}

```

The `if` statement failed as `$req_field['type']` returns `list<field_collection_item>`.

Any ideas?

# Answer
That's how an `EntityMetadataWrapper` stores multiple fields. There are only those two types, so just use

```
if($req_field['type'] == 'field_collection_item' || $req_field['type'] == 'list<field_collection_item>') {
  // So something here
}

```

Or some variation on that.
> 3 votes

---
Tags: 7, entities
---


title: Appropriate filters' setting

text:
# Question
Title: Appropriate filters' setting
I've custom content-type with several fields, e.g. rozdzielczosc1, rozdzielczosc2 and rozdzielczosc3. There are references to the term.

I'm creating the search. Now, I've several filters

My question is about third group of filters. I created exposed filter for field\_rozdzielczosc1 and filters for field\_rozdzielczosc2 and field\_rozdzielczosc3 inherit values from filter for field\_rozdzielczosc\_1. When user set the filter value for field\_rozdzielczosc1, filters values for another filter (field\_rozdzielczosc2 and field\_rozdzielczosc3) is the same. It works.

My search

In my description I ignore the two first group of filters. They work.

When user set "Rodzielczosc" in the search I'd like to choose contents whose field\_rozdzielczosc1 or field\_rozdzielczosc2 or field\_rozdzielczosc3 is equal choosen value.

When user set "Rodzielczosc" and fill in the "title", I'd like to choose what above but only if title of content includes given "title".

When user doesn't set anything I'd like to choose all contents.

As you've seen, I tried something, yet it doesn't work.

# Answer
> 0 votes
Create separate Group of filters and move a "title" filter there.

Maybe also check all OR and AND (but they seems fine for me...)

# Answer
> 0 votes
I think your content type is not properly organized. Have a look at your fields:

```
field_price
field_price_1
field_price_2

field_resolution
field_resolution_1
field_resolution_2

```

Why don't you use `field_price` for all items for sell? If you will have a thousand different products for sell, will you create a thousand fields like `field_price_xxxx` for them?

This is how I would do that:

Content type: `Image`

Fields:

```
field_image
field_price
field_category (term reference)

```

View page showing `fields` from `Image` content type.

Fields:

```
Content: Title
Content: Image
Content: Price

```

Filters criteria:

```
Content: Title (exposed)
Content: Published (Yes)
Content: Type (= image)
Content: Image:height (exposed)
Content: Image:width (exposed)
Content: category (exposed)

```

Done!

Notice: There is no fields like: `field_price_1`, `field_price_2` and there is no fields with resolutions (you don't need them).

---
Tags: 7, views
---


# Question
Title: Display register form to logged in users
I am on Drupal 7. When users log into a Drupal website, they aren't allowed to see the register form anymore. That is the regular behavior and I understand the reason why Drupal behaves like that.

But I have a specific situation in my website. I need users in a specific role to register new users. I will create an invisible field in my form that will tie these new users with the UserId of the "parent" user creating them. Maybe I will use the User Reference module. There is no problem here, I can do that.

The question is: how can I get the register form to be displayed to logged in users in a specific Role without giving them the "Administer users" rights? I don't trust these guys to give them that much access.

Thank you!

# Answer
> 1 votes
The access check is made in the `user_register_form()` function itself:

```
$admin = user_access('administer users');

...

// If we aren't admin but already logged on, go to the user page instead.
if (!$admin && $user->uid) {
  drupal_goto('user/' . $user->uid);
}

```

As you can see the check for the `administer users` permission is hard-coded. That said, I think you've got 2 options:

1. Grant the appropriate permission to that user role (obviously undesirable as you've mentioned).
2. Re-implement the user registration form in a custom module, changing the access check to a more appropriate one for your situation. You should be able to use pretty much all of the code from `user_register_form()` and piggyback off the validation/submit handlers, so there shouldn't be much coding involved at all really.

# Answer
> 0 votes
In my case I could solve the problem with the following approach. Actually, I have a very site specific and more complex configuration, but I'll try to simplify.

I have set a new permission called 'create users'. Then, just before the actual callback function, added the following lines, which check if the user have the 'create users' permission, and give him temporarily for that page callback the 'administer users' permission:

```
global $user;

if (user_access('create users')) {
  $static = &drupal_static('user_access');
  $static[$user->uid]['administer users'] = TRUE;
}

```

I am actually using the Administer Users by Role module with this patch. The patch is posted by me and it is an enhanced version of a previously posted patch. This module with the mentioned patch works most of the cases. If you have AJAX-enabled fields in the user registration form, then you should use some custom callback paths (which I had to do) and add the above lines before the actual callback function.

---
Tags: users
---


title: Change content of a node

text:
# Question
Title: Change content of a node
What is the best practice to change content links based on a class in drupal? I want to have www.example.org transformed to some text based on foo. Should I use `hook_view()`, or `hook_nodeapi()`?

# Answer
You can only use hook\_view() when you are implementing the code for the module that defines a content type.

> Display a node.
>
> This is a hook used by node modules. It allows a module to define a custom method of displaying its nodes, usually by displaying extra information particular to that node type.

The documentation of `hook_view()` for Drupal 7 is clearer:

> Display a node.
>
> This hook is invoked only on the module that defines the node's content type (use hook\_node\_view() to act on all node views).

If you are writing code in Drupal 6 to alter the content of a content type implemented by another module, you can only use hook\_nodeapi('alter'), for which the documentation reports:

> **"alter"**: the `$node->content` array has been rendered, so the node body or teaser is filtered and now contains HTML. This op should only be used when text substitution, filtering, or other raw text operations are necessary.

As what you are trying to achieve is text substitution, this is the hook you should use.

The equivalent for Drupal 7 is hook\_node\_view\_alter().

> Alter the results of node\_view().
>
> This hook is called after the content has been assembled in a structured array and may be used for doing processing which requires that the complete node content structure has been built.
>
> If the module wishes to act on the rendered HTML of the node rather than the structured content array, it may use this hook to add a #post\_render callback. Alternatively, it could also implement hook\_preprocess\_node(). See drupal\_render() and theme() documentation respectively for details.
> 3 votes

# Answer
Another option (in Drupal 7) if you're modifying other nodes with your module is to use hook\_preprocess\_field().

I use it to modify the body of nodes by searching for patterned strings to replace with module widgets. For instance I use |*youtube:{VideoID}*| to place a video in a node body then use mymodule\_preprocess\_field() to find and replace the patterns with the appropriate videos.

Not a better solution, just an alternative for modifying nodes your module does not control.
> 0 votes

---
Tags: nodes
---


title: file upload using Webservice

text:
# Question
Title: file upload using Webservice
I am using Drupal 7 and trying to upload a file

```
function upload_service_menu() {
  $items = array();

  $items['api/v1/upload'] = array(
    'title' => 'File Upload Service',
    'description' => 'Upload files to public directory on this server',
    'page callback' => 'upload_service_job',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Function to get the path, download and store the file on our server.
 */
function upload_service_job() {

    $file = $_FILES;

    $validators = array();
    $file = file_save_upload($file, $validators, 'public://');
    if($file){
        echo "Sucess";
    }else {
        echo "fail";
    }
}

```

and my local form is

```
<form action="http://example.com/api/v1/upload/" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

```

But i am not able to upload file. Seems file\_save\_upload($file, $validators, 'public://'); function is not working .I checked permissions also.. Can anybody tell me what to do.

Thanks

# Answer
> 0 votes
`$_FILES` is

> An associative array of items uploaded to the current script via the HTTP POST method.

`file_save_upload()` takes as its first parameter

> A string specifying the filepath or URI of the uploaded file to save.

Your code essentially does this

```
$file = file_save_upload($_FILES, $validators, 'public://');

```

So you're currently passing an array to a function that's expecting a string.

You're probably looking for something along the lines of

```
$file = file_save_upload($_FILES['file']['name'], $validators, 'public://');

```

---
Tags: 7
---


# Question
Title: How I can give a particular style to maps in drupal site based on gmap module
I am currently developing a website which makes heavy use of gmap and location module. I want to style maps in a particular style by appending style to google.maps.MapOptions.styles array, But maps in website still come out plain defaults. I am not sure how I have to proceed, as firebug reports that style changes are done properly in styles array

```
(function() {
var style = [
{
    featureType: "landscape",
    elementType: "all",
    stylers: [
    { hue: "#ffa200" },
    { lightness: -20 }
    ]
},{
    featureType: "water",
    elementType: "all",
    stylers: [
    { hue: "#ff9100" },
    { lightness: 52 }
    ]
},{
    featureType: "administrative",
    elementType: "labels",
    stylers: [
    { hue: "#1100ff" },
    { saturation: -100 },
    { lightness: -18 }
    ]
},{
    featureType: "poi",
    elementType: "all",
    stylers: [
    { lightness: -18 },
    { visibility: "off" }
    ]
},{
    featureType: "landscape",
    elementType: "all",
    stylers: [
    { visibility: "off" }
    ]
},{
    featureType: "water",
    elementType: "labels",
    stylers: [
    { lightness: -18 },
    { visibility: "off" }
    ]
},{
    featureType: "road",
    elementType: "labels",
    stylers: [
    { visibility: "off" }
    ]
},{
    featureType: "administrative",
    elementType: "geometry",
    stylers: [
    { visibility: "simplified" }
    ]
},{
    featureType: "road.highway",
    elementType: "geometry",
    stylers: [
    { saturation: -100 }
    ]
},{
    featureType: "road.arterial",
    elementType: "geometry",
    stylers: [
    { saturation: -100 }
    ]
},{
    featureType: "road.local",
    elementType: "geometry",
    stylers: [
    { lightness: -27 }
    ]
},{
    featureType: "transit",
    elementType: "all",
    stylers: [
    { visibility: "off" }
    ]
}
];

Drupal.behaviors.sepiaStyle = function(context) {
Drupal.gmap.addHandler('gmap', function(elem) {
    var obj = this;
    obj.bind("bootstrap_options", function() {
    var new_style = $.extend(obj.vars.styles, style)
    jQuery(elem).change(function() {
        obj.vars.styles= new_style;
    });

    });

});
};
}());

```

Any help is greatly appreciated. Thanks in advance

# Answer
> 1 votes
I managed to do it by changing a little bit the gmap.js file. At the line 358

```
obj.bind("boot", function () {
    obj.map = new google.maps.Map(elem, obj.opts);
});

```

Add these line:

```
obj.bind("boot", function () {
     obj.opts.styles = [
                                        {
                                            "featureType": "water",
                                            "stylers": [
                                                { "color": "#808084" }
                                            ]
                                        },{
                                            "featureType": "road",
                                            "stylers": [
                                                { "color": "#c8cacc" }
                                            ]
                                        },{
                                            "featureType": "landscape.man_made",
                                            "stylers": [
                                                { "color": "#b0b3b4" }
                                            ]
                                        },{
                                            "featureType": "road",
                                            "elementType": "labels.text.fill",
                                            "stylers": [
                                                { "color": "#000000" }
                                            ]
                                        },{
                                            "featureType": "poi",
                                            "stylers": [
                                                { "color": "#9c9ea2" }
                                            ]
                                        },{
                                            "featureType": "poi",
                                            "elementType": "labels.text.fill",
                                            "stylers": [
                                                { "color": "#000000" }
                                            ]
                                        },{
                                            "featureType": "administrative",
                                            "elementType": "labels.text.fill",
                                            "stylers": [
                                                { "color": "#808080" }
                                            ]
                                        },{
                                            "featureType": "landscape.natural",
                                            "stylers": [
                                                { "color": "#808084" }
                                            ]
                                        },{
                                            "featureType": "transit",
                                            "stylers": [
                                                { "color": "#c9c9cc" }
                                            ]
                                        },{
                                            "featureType": "transit.station.rail",
                                            "stylers": [
                                                { "color": "#838080" }
                                            ]
                                        },{
                                            "featureType": "road.arterial",
                                            "stylers": [
                                                { "color": "#adaeb1" }
                                            ]
                                        },{
                                            "featureType": "poi",
                                            "elementType": "labels.icon",
                                            "stylers": [
                                                { "color": "#3e3d3a" },
                                                { "visibility": "off" }
                                            ]
                                        },{
                                            "featureType": "transit.station",
                                            "elementType": "labels",
                                            "stylers": [
                                                { "visibility": "off" }
                                            ]
                                        },{
                                        }
                                    ];
    obj.map = new google.maps.Map(elem, obj.opts);

});

```

Also check this thread:

drupal.org

---
Tags: google-maps
---


title: CKEditor adds inline nonsense

text:
# Question
Title: CKEditor adds inline nonsense
I'm hoping someone else has run into this and has a solution:

I have the CKEditor module (v. 7.x-1.13) installed using ckeditor.js version 4.01 (due to compatibility with Media module). The problem I run into is after I've added content into a field and publish it. After I return to edit the content, CKEditor has added all kinds of "stuff", a ton of inline CSS inside of a paragraph and span, and the letters "BESs" See sample below. Hoping someone can make some sense of this and offer a solution.

```
<p><span style="position:absolute;top:-999px;left:-999px;font-size:300px;width:auto;height:auto;line-height:normal;margin:0;padding:0;font-variant:normal;font-family:adelle,Georgia,'Century Schoolbook L',serif;font-style:normal;font-weight:900;">BESs</span><span style="position:absolute;top:-999px;left:-999px;font-size:300px;width:auto;height:auto;line-height:normal;margin:0;padding:0;font-variant:normal;font-family:ff-tisa-web-pro,arial,'URW Gothic L',sans-serif;font-style:italic;font-weight:700;">BESs</span><span style="position:absolute;top:-999px;left:-999px;font-size:300px;width:auto;height:auto;line-height:normal;margin:0;padding:0;font-variant:normal;font-family:proxima-nova,Georgia,'Century Schoolbook L',serif;font-style:italic;font-weight:800;">BESs</span></p>

```

Thanks in advance.

# Answer
> 0 votes
I guess it's a bug in WebKit/Blink http://dev.ckeditor.com/ticket/9998. I don't know what you did with your text so I can't help more. But if it does not happen within Firefox or IE, then it is definitely that bug.

---
Tags: wysiwyg
---


# Question
Title: How to get core to leverage a MySQL master/slave configuration?
I read this question MySQL master/slave replication not working and its answer:

> Using slave databases is barely implemented in Drupal core. If you are developing your own modules then calls to db\_query need to specify that they want to use the slave database using the $options array. See DatabaseConnection::defaultOptions for how to set this array.

Is there a way without killing kittens hacking the core to get `db_query()` and `db_select()` to make more slave SELECT queries ?

By default, these functions will query the master unless specifically told to query the slave (see their API). You have to write `db_query($query, $args, array('target' => 'slave'))` in order to query the slave and the core (and all the modules) aren't written to achieve this.

Only search (see the slave part) and aggregator seems to leverage this.

**Edit:** Oct, 25
I saw pressflow 7 is out but I'm not sure if it helps a lot right now.
I haven't found something relevant so let's try a little bounty to help this getting an answer.

**Edit:** Oct, 31
I'm mainly worried about Crell's comments regarding this topic: What to do with slaves?.
Mainly, is there troubles if I send `SELECT` queries to the slave, what happens with delays in the replication and the fact that I may want to do a `node_load()` just after saving a new node.

# Answer
> 17 votes
Here's how I currently implement this.

First you need to set up a SelectQueryExtender class like this:

```
class SlaveTarget extends SelectQueryExtender {
  public function __construct(SelectQueryInterface $query, DatabaseConnection $connection) {
    if ($connection->getTarget() != 'slave') {
      $connection = Database::getConnection('slave', $connection->getKey());
    }
    parent::__construct($query, $connection);
    $this->addTag('SlaveTarget');
  }
}

```

Once you have that, then all you have to do is get all the other queries to extend the extender. :) if that makes sense. Here's the snippet.

```
/**
 * Implements hook_query_alter().
 */
function example_query_alter(QueryAlterableInterface $query) {
  if (is_a($query, 'SelectQuery') && !$query->hasTag('SlaveTarget')) {
    $query->extend('SlaveTarget');
  }
}

```

And now all your SelectQuery hit the slave ;-) This is the only way I've been able to accomplish this. Anyways it works great.

Also if you have this on a custom module you can set up the SlaveTarget to be it's on file SlaveTarget.inc and add a files\[\] = SlaveTarget.inc to your module info file.

# Answer
> 5 votes
The AutoSlave module redirects `SELECT` queries to read-only replicant databases, ***and*** it takes into account replication lag.

According to the module docs, it only uses the read-only replicant when all of the following conditions are true:

> 1. The query is a select query
> 2. The tables in the select query have not been written to during the request and within the assumed replication lag
> 3. A transaction has not been started
> 4. The tables in the select query are not specified in the 'tables' option in the driver settings
> 5. A lock has not been started (core db-lock and memcache-lock supported)

# Answer
> 1 votes
from what I heard at the recent Drupal BADcamp Pressflow is the way to go if you want master/slave configurations. You'll be limited to Mysql as the DB. Also, checkout the "high performance group" on d.o.

# Answer
> 1 votes
Despite all of the amazing work done on the database abstraction layer in Drupal 7, this is still surprisingly difficult to do with Drupal core out of the box. As others have mentioned, AutoSlave is an option, although not one I've attempted due to my stubborn refusal to believe that it should be that difficult to do this.

A simpler solution I have found is the following. To route **all** `SELECT`s to the slave server, you create a file titled `select.inc` inside of the core `includes/database/mysql` directory with the following contents:

```
<?php

/**
 * @file
 * Select builder for MySQL database engine, routing all SELECTs to the slave.
 */

/**
 * @addtogroup database
 * @{
 */

class SelectQuery_mysql extends SelectQuery {
  public function __construct($table, $alias = NULL, DatabaseConnection $connection, $options = array()) {
    $key = $connection->getKey();
    $connection = Database::getConnection('slave', $key);
    $options['target'] = 'slave';
    parent::__construct($table, $alias, $connection, $options);
  }
}

/**
 * @} End of "addtogroup database".
 */

```

There are some risks with this method:

1. This method will hijack **all** `SELECT`s and direct them to the slave, which will undoubtedly cause issues if you have any lag in replication. Read that sentence again.
2. When you upgrade Drupal core, it is possible that this file will get deleted.
3. If Drupal core were ever to start shipping with its own `includes/database/mysql/select.inc`, your file would get overwritten during upgrade, and you would have to start maintaining your own patched version of the select.inc that ships with Drupal core.

If you don't have any slave servers specified in settings.php, the above code will not cause a problem. It will still gracefully degrade to using the **master** server.

---
Tags: 7, performance, database
---


# Question
Title: How do I get the highest `field_id` value that exists in content of a specific type?
I have a content type which, among other things, have a field which contains a unique ID number (this number is used to connect the individual content to related information stored on paper).

When creating new entries I'd like to automatically generate this ID by finding the highest ID already present in the system, and calculating the next ID from that.

I have written a small module (using `hook_menu()`) which presents the user an interface for adding new content. How can I, from within this module, get the `field_id` values of my already existing content? (So that I can calculate which ID a new entry should have?)

Is there any PHP command which can be made to return an array containing all the `field_id`s from my content type?

---

Worth to know here is that the system is kinda small (500–1000 entries of my content type, at most). There will also only be a single person entering data at a time. Also, I'm using Drupal 7.

# Answer
The easiest sulotion I can think about is to use Computed field module and the id field will be computed field.
Then, in the field read the last value using `variable_get()` and then update that value using `variable_set()`.
> 0 votes

---
Tags: 7, hooks
---


# Question
Title: Block in custom module not registering on a particular site
I'm having issues with a block that is created with a module I wrote. This module works on 2 out of 3 sites, all of which have a similar setup, so I'm not sure why it's being picky on one site. Here is what I know:

1. The block is not showing up in the list on admin/structure/blocks, and is not available anywhere else.
2. hook\_block\_info() is being invoked on the site, but none of the other functions are being called. On the other two sites, calls are made to all the functions.
3. There aren't any blocks in the `blocks` table with the same name, but there is a record of the block in the table for each active theme.
4. I tried deleting these records out of the `blocks` table with no luck.
5. I've tried clearing cache and uninstalling/reinstalling with no luck.

Here code for my .module file. It is available here as well: http://pastebin.com/EYFgneie

```
/**
* Implements hook_block_info()
*/
function kcc_menu_block_info() {
    $blocks = array();

    //This IS being called
    dpm('hook_block_info');

    $blocks['kcc_menu_block'] = array(
        'info' => 'KCC Menu',
        'subject' => 'Menu within a block generated by a module.',
        'cache' => DRUPAL_NO_CACHE,
        'properties' => array(),
        'weight' => null,
        'status' => 1,
        'visibility' => null,
        'pages' => null,
        'region' => 'sidebar',
        );
    return $blocks;
}

/**
* Implements hook_block_view()
*/
function kcc_menu_block_view($delta = '') {
    $block = array();
    switch($delta) {
        case 'kcc_menu_block' :
            //Only show this block on non-admin pages
            if(!path_is_admin(current_path())) {
                $block['content'] = _kcc_menu_block_view_content();
                $block['title'] = _kcc_menu_block_title();
            }
        break;
    }
    return $block;
}

/**
* Implements hook_block_view_content()
*/
function _kcc_menu_block_view_content() {
    $results = _kcc_menu_block_links();
    return array(
        'message' => array(
            '#type' => 'markup',
            '#markup' => $results['markup'],
            '#prefix' => '<div class="kcc_block">',
            '#suffix' => '</div>',
            ),
        );
}

/**
* Function to return the entire set of 1st-level links in the sidebar menu
*/
function _kcc_menu_sidebar_links() {
    return menu_tree_all_data('menu-menu-sidebar');
}

/**
* Function that returns the submenu for a specific link item out of a list of menu items.
*/
function _kcc_submenu_tree($menu_items, $mlid) {
    /**
    * The link returned is chosen by the mlid passed.
    *  An empty array will be returned if there are no children.
    *  $menu_items is from array returned from menu_tree_all_data()
    *  Sub-items of that array can be passed here
    */
    foreach($menu_items as $branch) {
        if($branch['link']['mlid'] == $mlid) {
            $child_tree = $branch['below'];
            return $child_tree;
        }
    }
}

/*
* Function to return the block title
*/
function _kcc_menu_block_title() {
    //The value is returned along with the
    //results from _kcc_menu_block_links()
    $result = _kcc_menu_block_links();
    return $result['title_link']['title'];
}

/*
* Function to determine and return the block content
*/
function _kcc_menu_block_links() {

    $returned = array();

    $sidebar_menu_links = _kcc_menu_sidebar_links();

    //An array of link items representing where the
    //user is currently located in the menu
    $current_trail_links = menu_get_active_trail($sidebar_menu_links);
    //Remove 'home' link from the current path
    unset($current_trail_links[0]);

    //Last item in the current trail is the current page
    $current_page_link = end($current_trail_links);
    reset($current_trail_links);

    //Get the set of links for the first level menu item
    $second_level_menu_items = _kcc_submenu_tree($sidebar_menu_links, $current_trail_links[1]['mlid']);

    if($current_page_link['depth'] == 1) {

        //1st level menu item with children
        //Display child links for level 1 menu
        $left_menu_items = $second_level_menu_items;
        $title_link = $current_trail_links[1];
    }
    elseif($current_page_link['depth'] == 2) {

        $third_level_menu_items = _kcc_submenu_tree($second_level_menu_items, $current_page_link['mlid']);
        $has_children = (!empty($third_level_menu_items)) ? true : false;

        if($has_children) {
            //Display child links in menu
            $left_menu_items = $third_level_menu_items;
            $title_link = $current_trail_links[2];
            //dpm('2nd level menu item with children!');
        }
        else {
            //Display sibling links in menu
            $left_menu_items = $second_level_menu_items;
            $title_link = $current_trail_links[1];
            //dpm('2nd level menu item without children!');
        }
    }
    elseif($current_page_link['depth'] == 3) {

        $third_level_menu_items = _kcc_submenu_tree($second_level_menu_items, $current_trail_links[2]['mlid']);
        $fourth_level_menu_items = _kcc_submenu_tree($third_level_menu_items, $current_trail_links[3]['mlid']);
        $has_children = (!empty($fourth_level_menu_items)) ? true : false;

        //Display child links for level 2 menu
        //whether or not there are children
        if($has_children) {
            //dpm('3rd level menu item with children');
            $left_menu_items = $third_level_menu_items;
            $title_link = $current_trail_links[2];
        }
        else {
            //dpm('3rd level menu item without children');
            $left_menu_items = $third_level_menu_items;
            $title_link = $current_trail_links[2];
        }
    }
    elseif($current_page_link['depth'] == 4) {

        //Display child links for level 3 menu
        //dpm('4th level menu item without children');
        $third_level_menu_items = _kcc_submenu_tree($second_level_menu_items, $current_trail_links[2]['mlid']);
        $fourth_level_menu_items = _kcc_submenu_tree($third_level_menu_items, $current_trail_links[3]['mlid']);
        $left_menu_items = $fourth_level_menu_items;
        $title_link = $current_trail_links[3];
    }
    else {
        $left_menu_items = null;
    }

    $returned['title_link'] = $title_link;
    $returned['markup'] = '<ul>';
    foreach($left_menu_items as $left_menu_item) {
        $returned['markup'] .= "<li><a href=\"/{$left_menu_item['link']['href']}\">{$left_menu_item['link']['title']}</a></li>";
    }
    $returned['markup'] .= '</ul>';

    return $returned;
}

```

I've exhausted all of my knowledge, so I'm up for any and all suggestions. Thanks in advance for you help!

# Answer
I have no clue why, but having this in hook\_block\_info() is causing my problem:

```
'status' => 1,

```

That is supposed to set the block to be enabled by default, but for some reason it removes the block from /admin/structure/block for all three sites.

This solved my problem, but it doesn't seem right. Any thoughts?
> 1 votes

---
Tags: 7, blocks
---


# Question
Title: How to delete a comment via an HTTP GET link in an email
On my site, moderators are notified of comments via email whenever a new comment is posted. I would like to offer them a one-click approve/delete feature directly from the email.

There is an approve comment link, so I can easily put that link into the email for them to approve the comment directly.

However comments are deleted via a form - an HTTP post - so I can't do that from a link in an email as far as I know. At least that's how it is on my site - not sure whether the form behaviour is normal or is because I have Mollom installed.

Is there a way to delete a comment directly from a link in an email?

# Answer
This will do it.

Obviously you don't want to allow just anyone to delete any comment.

The authentication step is to require the user to be logged in with "*administer comments*" permission.

Alternatively, you could perhaps use a token in the querystring to check access to delete the comment.

```
/**
 * Implements hook_menu
 */
function MY_MODULE_menu() {

  $items['action/comment/%/delete'] = array(
    'title' => 'Delete comment',
    'page callback' => 'MY_MODULE_action_comment_delete',
    'page arguments' => array(2),
    'access arguments' => array('administer comments'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Menu callback
 * Delete comment via GET request
 */
function MY_MODULE_action_comment_delete($cid){

  try{
    // Delete the comment
    comment_delete($cid);
    drupal_set_message(t('The comment and all its replies have been deleted.'));
    watchdog('MY_MODULE', 'Deleted comment @cid and its replies.', array('@cid' => $cid));
    // Clear the cache so an anonymous user sees that his comment was deleted.
    cache_clear_all();
  }catch(Exception $e){
    drupal_set_message(t('There was a problem deleting the comment.'));
    watchdog_exception('MY_MODULE', $e);
  }

}

```

The path to delete a comment would then be:

http://www.example.com/action/comment/12/delete

Where "12" is the comment cid.
> 0 votes

---
Tags: 7, comments, advertising
---


# Question
Title: How can I load a theme template to render $submitted
I'm trying to replace the output of `$submitted` in my nodes. I have found how to replace the value which is fine. The problem I'm facing is how to load a template file properly.

```
function pod_preprocess_node(&$vars) {
  $vars['submitted'] =  t('!datetime ', array(
    '!datetime' => include_once(__DIR__.'/system/submitted.tpl.php')
  ));
}

```

As you can see above, I've just included a template file and in there I can use $vars but this is clearly sub optimal. What I'd like to do is just load a template file from my theme which has some sensibly named variables in.

I've looked at `hook_theme()` which now allows me to call `theme('pod_submitted', $vars)` but I don't know how to make `pod_submitted()` include the right file etc.

I assume that somewhere I need to do the following

```
$vars['theme_hook_suggestions'][] = 'system__submitted';

```

But I'm not sure how my template function relates to/knows which template to call.

# Answer
Well, what you're looking for is hook\_theme. With `hook_theme` you can declare new theme implementations, which can be either functions or templates. I'll stick with templates for this answer. Just define it in `YOURTHEME`'s `template.php` file:

```
function YOURTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'YTsubmitted' => array(
      'template' => 'YTsubmitted',
      'variables' => array('whom' => NULL, 'when' => NULL),
    ),
  )
};

```

I'm calling the theme hook `YTsubmitted` and the template file `YTsubmitted`. Those names don't need to be the same, but I'm prefixing to avoid collisions. Now, whenever you call `theme('YTsubmitted')`, Drupal will look for `YTsubmitted.tpl.php` in your theme and use it for rendering. You can pass variables to it when calling, just like `theme('YTsubmitted', array('whom' => 'Jake the dog'))`. Variables will default to values set when defining the theme hook in `hook_theme` (`NULL` in our example). But you can also preprocess variables:

```
function YOURTHEME_preprocess_ytsubmitted(&$vars, $hook) {
  $vars['extra'] = 'Mathematical!';
}

```

And now you can use it in your template file (`YTsubmitted.tpl.php`):

```
<p>Submitted by <?php print $whom ?> right after <?php print $when ?>. <?php print $extra ?>!</p>

```

That's precisely how Drupal sets several of the templates and its variables. For instance, `node.tpl.php` will print the `$submitted` variable, which can be redefined in your `template.php` file:

```
function YOURTHEME_preprocess_node(&$vars, $hook) {
  $vars['submitted'] = theme('YTsubmitted', array('whom' => 'Finn the human'));
}

```

AAAaaand you're done.
> 5 votes

# Answer
Is *system/submitted.tpl.php* in your theme directory?

Your method is not the correct way to accomplish what you are trying to do. I hope this clears it up.

hook\_preprocess\_node is pretty close. **Do** override the 'submitted' variable. **Do** add extra variables (you can name them how you please). **Don't** include a template file.

```
function themename_preprocess_node(&$vars) {
  $vars['submitted'] = "foo";
  $vars['foo'] = "bar";
  $vars['bar'] = "xyz";
}

```

Template override. You don't need to add a *submitted* template. Simply copy the *node.tpl.php* file from either your parent theme's directory, or the node module in core, and place it in your theme directory. Flush you caches. Edit that file and make your changes in there. For example adding in the $foo variable from above (note: All $vars\['foo'\] are exposed both as $vars\['foo'\] and $foo for convenience).

```
cp modules/node/node.tpl.php sites/all/mytheme/node.tpl.php

```

--

```
  <?php if ($display_submitted): ?>
    <div class="submitted">
      <?php print $submitted; ?>
      Foo:
      <?php print $foo; ?>
      Bar:
      <?php print $bar; ?>
    </div>
  <?php endif; ?>

```
> 4 votes

---
Tags: 7, hooks
---


# Question
Title: How to create a view based on taxonomy term of a node reference
I have a taxonomy vocabulary called "Sports" that lists out a number of sports terms (Football, Tennis, etc).

I have one content type called "Team". I have a "Sports" taxonomy term reference field set as I associate a sport to the team. The field is called **field\_sport**.

I have another content type called "Fixture". It has a node reference to "Team". The field is called **field\_sport\_team**.

That is:

* a Fixture has a Team.
* a Team has a related Sport.

Question:

How can I create a view with a contextual filter based on a "Sports" term that returns all related "Fixture" given that the "Sports" term is associated to a "Team" node reference?

Been stuck over the past few days...

Thank you for your help in advance!

# Answer
OK. I've solved it myself!

I had to set up a relationship with "Team".

Then I added in a "Content: Has taxonomy term ID" contextual filter. Within the settings there is a relationship option which I set to the one I set above.

Works as I expected!
> 1 votes

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


# Question
Title: Change to posting status from registers users to anonymous
I'm not a hard core Drupal programmer but I'm learning bits by bits by using services like this one. I'm building a question answer site and was wondering how do I make to where users can select to be anonymous, like a little module that when a check box to be anonymous is selected the username will be changed to anonymous. It will be same thing as this one asked here but instead of posting as anonymous you will be logged in.

# Answer
> 0 votes
You could a field to the contenty type, like a boolean (0 = Anonymous, 1 = normal user) Then you can create a custom module with on hook\_node\_presave and, if the boolean value is "0" you set programmatically the owner to anonymous.

In this way you lose the "link" between node and author, so I suggest you to add in the content type something like a user reference to the "real" author of the node.

---
Tags: nodes, users
---


# Question
Title: How to hide exposed sort if view return empty result?
I have a view with an exposed filters and sorting. They are displayed as a separate block.

I want to hide only sorting widget if view return empty result (filters must left)

How to achieve this?

The problem is that when exposed form is rendered its view isn't executed yet - so i can't determine if view has any result.

# Answer
If javascript consider an option, you can hide sorting widget wrapper using javascript on page load when view returns empty result by checking if view result class or id exists in the html
> 2 votes

# Answer
In views-view.tpl.php, just replace this code

```
<?php if ($exposed): ?>
    <div class="view-filters">
      <?php print $exposed; ?>
    </div>
  <?php endif; ?>

```

with

```
<?php if ($exposed && $rows): ?>
    <div class="view-filters">
      <?php print $exposed; ?>
    </div>
  <?php endif; ?>

```

Cheers
> 3 votes

# Answer
This starts to get pretty complicated when you dig into it. Here's the process I've gone through with it:

1. Using JavaScript: You have a View with an exposed filter. Let's say the options are for whether it's published, and they're "Yes" and "No". Then imagine there is no unpublished content. So the user selects "No" from the exposed filter, and Views returns an empty result. The user can never switch back to the filter value that gives the result, because the filter is now hidden.
2. Ok, so now you realize what you want is to only hide the filter if all the filter values *except* the one that's currently being used will return empty results. You can't do this with JavaScript, but that's ok, because there are things like `hook_views_pre_render()` and `hook_form_alter()`. You're prepared to write a custom module, so it's all good.

So you want to look at all the exposed filter options and hide all the ones that would return an empty result. This would mean you would have to perform the query on every available value upon loading the View for the first time. That could be a little bit heavy, but perhaps you build in a boundary, like only try to do this if there are fewer than four available values.

We'll need to use something like an Entity Field Query to get the results from each available filter value. We do something like this:

1. Loop through all available filters that we want to limit (e.g. 'status' or 'author' or whatever)
    2. Inside that loop, loop through all the available values of that filter (e.g. 'published' or 'admin' etc.)
    3. Inside each of those, we need to do some kind of query to make sure that filter/value pair returns a result. We'll do an Entity Field Query. You can look at the documented examples, so I'll skip to where we specify what we actually want to look for: `-> propertyCondition($value, $filter)`. We have to do this for every single filter/value pair, but that's not the problem. Because we have to be doing all this in a `hook_form_FORM_ID_alter()` function in order to be able to hide form elements or allowed value choices, and AFAIK the closest thing I can get to the filter value out of the $form is the displayed choice (e.g. "Yes" for published status, when the Views query actually takes a "1" for "Yes" and "0" for "No".
    4. Ok, so no big, because we can look in `$form['view']` to figure that out. So we have our values to pass to our EFQ but we still have a pretty buggy system here, because in a real View our filters work together, whereas here they don't. Plus we haven't built node access into this yet. What if there are unpublished nodes of the type we're talking about but the current user won't get to see them in their View? Oh wait, of the right type? We didn't even include that yet. So basically we have to recreate the whole view every time the view loads to remove the filter values that would return null results.

My verdict: This is too complicated to do reliably with an override.
> 1 votes

# Answer
For Drupal 7 views, I added a "Global Text area" in the "No Result behaviour" in advance section of views. In that global text area, i selected text format to be "Full HTML" and added the following javascript

```
<script type="text/javascript">

  jQuery(function() {
    jQuery('.my-view-class .view-filters').hide("fast");
  });

</script>

```

(change my-view-class with your view's class name)

So this javascript only runs when there are no results and hides the exposed filters and exposed sorts. I think this is the standard way. Hope this helps someone

Muhammad www.app-desk.com
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to customize the map used on gmap module (node locations)
When gmap module and location module are installed, there is a page called "node locations", which display all node with a location field (filled) in the site.

How can I customize the google maps parameters? I want to disable the satellite map (and options in top right), enable street view, and change the zoom widget..

Thank you

# Answer
> 2 votes
The google maps parameters can be changed in file: "sites/all/modules/gmap/js/gmap.js"

Here is the option I choose:

**Street View enabled**:

```
opts.streetViewControl = true;

```

**Satellite map disabled**:

```
opts.mapTypeControl = false;

```

**Zoom widget change**:

```
opts.zoomControl = true;
opts.zoomControlOptions = {};
opts.zoomControlOptions.style = google.maps.ZoomControlStyle.LARGE;

```

# Answer
> 1 votes
What I would do is to use the GMap Views plugin of the GMap module, the Views module and the GMap Macro Builder module (comes with GMap):

* Download and enable Views
* Enable GMap Macro Builder
* Navigate to the macro builder (/map/macro) and create a map with the options you desire
* Copy the GMap macro to a temp place (clipboard obviously)
* Create a new view
* Select 'Show content' of any type you prefer and configure the remaining options accordingly (you can always change them at a later stage anyway)
* Click 'Continue & edit'
* In the format section, select Gmap In the GMap settings, paste the gmap macro so the produced map will follow the desired configuration
* Customize the view further and save.

I hope the above is helpful.

---
Tags: location, google-maps
---


# Question
Title: show archive block on every page containing certain content type
I have created one archive block using views for a content type. It holds the list of all the contents grouped year+month wise.

> Now I want to display it on the left sidebar of all the pages having this content type.

Using Block configuration of this archive block I have displayed it on certain pages, but I can't set it to appear on all the pages of type node/\*, because all nodes do not contain that very content type.

Please help if anyone knows the solution to it .

# Answer
> 1 votes
If you are using Drupal 7, you can go to Home » Administration » Structure » Blocks, and hit configure next to block you need:

In the Visibility settings section use Content types tab. In Drupal 8 it looked similar and probably will not change significantly.

The same functionality was backported to 5 and 6 by Block Node Visibility module.

If you don't want to install above module, and you're using Drupal 6, use Pages tab, and select last radio button "Pages on which this PHP code returns TRUE", and use code like:

```
<?php
// valid node id in view mode
if ( arg(0) == 'node' AND is_numeric(arg(1)) AND arg(2) == FALSE ) {

    $node = node_load(arg(1)); // cached

    if ( $node->type == 'insert type you want' ) {
        return TRUE;
    }
}

return FALSE;
?>

```

Code sample by bluesherpa from Drupal.org.

---
Tags: entities, backups
---


# Question
Title: How to check if this page is user Profile Page
I made a custom User Panel which is similar to Wordpress Top Panel in `page.tpl.php` so this panel will be shown for every logged-in users on the top of their page. But I want to hide that panel in `user-profile.tpl.php` but, not sure is there any function like `is_profile()` or something like that so I can check for a profile page and when the statement is `true` then hide the custom User Panel on `user-profile.tpl.php`.

Note that my d7 site has its custom user profile page.

Any idea? Thanks

# Answer
> 7 votes
Anywhere in code, you can use code like that:

```
if (    arg(0) == 'user' // test if you are on user page
    and is_numeric(arg(1)) // and if user ID was provided and is possibly valid (a number)
    and arg(2) == FALSE // and there is no /edit or /delete added
) {
  // Do something
}

```

Substitute `'user'` with any name provided by module, if you are using alternative user profile module.

# Answer
> 1 votes
You can do that in the Block configuration page. Click on 'configure block' on the contextual menu, or in blocks administration page `admin/structure/block`.

Below, under **Visibility Settings** make sure the **All pages except those listed** is selected, and in the textarea put this line:

```
user/%

```

If you are using Profile2 module, you may want to add also:

```
profile-name/%

```

Where the `profile-name` is the machine name of your profile type.

---
Tags: 7, users
---


# Question
Title: Insert the next recurring charge date in custom table when user purchase a product?
My site have a `subscriber role` that have some special permissions. User has to purchase the role. I used `ubercart` module for this.

I added a `feature` to assign role on purchase of subscription. Subscription can be for 1 week, 1 month or 1 year. User can cancel own recurring charge. `Uc_role` module manages the assign and remove role of user. It handles the next date of recurring. But `uc_role` not manages the past date.

My question is that I want to show the user who purchase a subscription in past. Is there any hook or something so I can work on it?

# Answer
Solved this just by adding my custom code `db_insert()` in `uc_role.module` file in `uc_role_grant` and `uc_role_renew` function.
> 0 votes

# Answer
I have done something similar although I don't think it's the best way.

I created a rule that is triggered with the event I wanted and then added an action which was custom php. Then use drupal db api to make the update or insert in the table.

https://drupal.org/project/rules https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db\_query/7
> 0 votes

---
Tags: 7, ubercart
---


# Question
Title: Form API submit with AJAX removes wrapper element?
I'm using the Form api to submit with ajax which works once, but once it's happened the wrapper element has also been replaced by the new ajax content. How can I make sure the content get replaced, but the wrapper element stays there so it can be replaced again?

```
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'submit',
  '#ajax' => array(
      'callback' => 'fung_filter_form_callback',
      'wrapper' => 'view-cont',
      'method' => 'replace',
)

```

For now I've got a workaround by returning the same wrapper in the ajax content, but this seems a bit strange - any ideas?

# Answer
> 2 votes
If you don't want to `'replace'` element with id `'view-cont'`, use another `'method'`, like:

```
'method' => 'append',

```

And if you in fact want to replace it, modify `fung_filter_form_callback` to make it return div with that ID again - that way you will replace original div with another div of the same ID, and will be able to repeat that process.

---
Tags: forms
---


# Question
Title: Issues migrating site back to local server
I have issues migrating my Drupal 7.14 site from Live Server back to local. This might be more sql related, but not sure at this point where the error comes from. Might be specifically Acquia related.

The site is now perfectly running on the live server. I made some new nodes etc and now I wish to work more on the structure. I was trying to migrate it back to my local Acquia server by doing the following:

* creating local safety copy of the current local site (also to preserve the local settings.php file)
* creating safety copy of local sql db
* exporting live sql db, then dropping tables of local db and replacing them with the live one
* replacing local site files with the ones downloaded from live
* updating settings.php from the original local safety copy

What happens is:

* when trying to access local address (mysite:8082) I get 'could not find' error message. this comes from google, so the local drupal site doesn't even get recognized in any way
* i am still able to set up new Drupal installations via Acquia and they run perfectly
* if I replace the sql db of a newly installed site with the one I got from the live site I get the same error
* i can't seem to get the local site running even if I use the safety copy sql + safety copy of the local site
* if I go to a definite url such as 'mysite:8082/index' I get the following: "The requested URL /index was not found on this server."

Where should I look next? What could be in the sql that makes the whole server unrecognisable?Any completely different ways to do this? Thanks!

# Answer
> 2 votes
As the OP noted in a comment, there is documentation available from Aquia that explains how to do this. For a better formatted answer please follow the above link.

> IMPORTING AN EXISTING SITE OR CODEBASE INTO ACQUIA DEV DESKTOP
>
> To run an existing site or new Drupal distribution on your local computer, complete the following steps:
>
> 1. Ensure that your local computer contains a copy of your site's Drupal files and directories (codebase).
>
> * Save your site's codebase in a place where you can find it and where you won't delete or move it unintentionally. This protects your site from accidental removal, and helps when you need to modify site content or change the installed modules.
>     * You cannot import zipped or compressed codebases into Dev Desktop. Ensure that your site's code is uncompressed.
>     * For more information about backing up the Drupal file system, see Drupal file system backup.
>
> **Note:** Dev Desktop does not move or copy your site's code into the Dev Desktop installation directory. Instead, Dev Desktop records where the Drupal directories are stored on your local computer.
> 2. Open the Acquia Dev Desktop Control Panel, click **Settings**, and then select the Sites tab.
> 3. Click **Import**. The Import site window opens.
> 4. In the Codebase section, click **Browse** to select the source code directory (also known as \[docroot\]) of your Drupal installation. This directory contains Drupal's files and directories, including index.php, the /includes directory, and the /modules directory.
> 5. After you select the your codebase, in the **Subsite** drop-down menu, select the site to import from the source code directory. For single-site codebases or Drupal distributions, select default. If you're importing a codebase that contains multiple subsites, select the subsite you want to import from the Subsites drop-down menu.
>
> **Note**: Dev Desktop can only import one site at a time.
> 6. Configure the database settings for the site import process. The settings are based on the type of site or codebase you're importing into Dev Desktop.
> 7. In the **Database name** field, enter a name for the database. If you're restoring a backed up database, the name does not have to match the backed up database's previous name.
> 8. Under **Domain**, enter the elements (server, subdomain, and URL path) of the local URL you want to use for your site. For example, if you want to reach your site locally at `http://my.example:8082/mysite`, enter my for the **Subdomain**, `example` for the **Server**, and `mysite` for the URL path. The subdomain and **URL path** are optional.
> 9. Click **Import**.
>
> Acquia Dev Desktop records the location of your site's Drupal codebase, creates its new database (if selected), and adds the site to the list of sites in the Sites tab.

---
Tags: 7, database
---


# Question
Title: Dropping options of exposed filters breaks when user is logged
I have a weird problem with Views exposed filters.

When I click on some exposed filters the dropping options are appearing, but when I hover with the mouse, dropping options are immediately dissapearing without letting me choose any of them. This problem only occurs when user is logged, no matter what role is using. I've disabled the administration module, but the problem still remains.

Using exposed filter as a block doesn't have this problem and anonymous users too.

The same problem I've experienced in my other website too.

# Answer
> 0 votes
As Bala said, it is a CSS issue. I finally fixed it. The problem comes from my `<#section id="main">`. It's a wrapper to all the main content area in my theme. It has `display:inline`, but when I change it into `display:inline-block` or by deleting the display, the dropping options are working flawlessly.

---
Tags: views
---


title: Username as a path to Profile page

text:
# Question
Title: Username as a path to Profile page
I am trying to set up username as a main path to the user profiles in Drupal 7; for example, I would like to have mypage.com/someusername as path alias for the profile of the user that uses "someusername" as username.

I am using the Profile 2 module as well. I tried everything, but I cannot achieve this.

# Answer
If you use the Pathauto module, you can set an automatic alias for the user profiles using a token that is replaced with the username. In Pathauto for Drupal 7, the default pattern for user paths is /users/\[user:name\], which is the pattern I would suggest to use to avoid conflict with path defined from other module. As you don't control the username chosen from a user, it could happen the username is admin, which conflict with the path used from system.module for its own menu callback.

If you want to use a different token, the list of available tokens is available right after the text field used for the pattern to use.

What I reported is still valid for Drupal 6; the difference is that the token for the username is \[user\].
> 7 votes

# Answer
There is the Menu token module for defining paths like 'user/\[user:uid\]'.

> Menu Token module provides tokens, that could be used in title or in path of menu items (links). For example, if you create menu item with path: "user/\[current-user:uid\]", the url will be changed "on fly" to: "user/1" (assuming you are user 1).
>
> Tokens are provided by Token module. Menu Token allows to use both global tokens and entity one: node, user, term. Entity tokens have several methods of substitution: from context, random and user defined.
> 1 votes

# Answer
Just came across this issue and in case anyone reading this didn't get much enlightenment, I'll light up a bit more.

By default, drupal use "**user/{user\_id}**" for the path to your **Profile** page. And on your path page above it could written "users/\[user:name\]" to go to some page like www.example.com/not-my-real-name-but-username-use-for-login

So to link to your Profile page,

1. aside from setting the Path like kiamlaluno described above...
2. remember to Delete all your user aliases on "Delete aliases" tab and rebuild them using the new pattern you entered above from "Bulk update" tab.

Hope that helps. Saved me few hours.
> 0 votes

---
Tags: users, path-aliases
---


# Question
Title: How to configure a module after installation
In my Drupal 6 website there are a bunch of modules. What is the simplest way to configure these modules? Also I am not sure of where their settings are? If there is a simple link that can be invoked to configure them , that will be awesome. In this case its the ctools module. I am not looking for http://www.sitename.com/admin/by-module neither the Site building has the module.

Thanks

# Answer
It's up to the module itself to present configuration options, and in Drupal 6 these can be a bit harder to find. I definitely recommend installing the admin\_menu module (http://drupal.org/project/admin\_menu), which can provide expanding drop-down menus to easily browse through all of the admin-side links.

With cTools specifically, the base 'Chaos tools' module won't do anything on its own, though it can be required by other contrib modules. If you're looking to use one of the bundled modules such as Stylizer or Page Manager, you'll need to enable and configure those modules separately.
> 3 votes

# Answer
\[your website domain\]/ctools\_ajax\_sample You don't really configure that module, but you can see it in action after it's been activated.
> -1 votes

---
Tags: 7
---


# Question
Title: View does not display attached file without Display field checked
I've got a view that exposes a list of nodes with fields: Title, Publishing date, Attached files.

If an attached file has checked the "Display" flag it is visible on the view result, but if the "Display" field is not checked the file is not visible.

Is it possible to show all attached files?

There are three files attached to node, but only two with "Display" checked, I'll want to show all files attached to node.

# Answer
> 0 votes
Under advanced \> query settings \> check "Disable SQL rewriting" - it should prevent any access or visibility checks for nodes and fields. Don't forget to add the ones you need directly to a view if you do this.

---
Tags: 7, views
---


title: Spam user accounts being created

text:
# Question
Title: Spam user accounts being created
I've made a site where users can create accounts. Lots of spam accounts are being created and I am not sure why. The form at mysite.com/user is mollom CAPTCHA protected, what other paths should I check?

# Answer
Mollom tests content for spam. But user creation form does not provide any opportunity to provide spam content in the first place. So you have 2 strategies available:

1. Protect user creation form with more traditional captcha, or one of it's mutations like reCaptcha or little game humanity test.
2. Protect comments / node forms with Mollom and automatically block users that will fail mollom test there.

Note, above ways are not mutually exclusive.
> 2 votes

# Answer
Well, in that case Spamicide Module is a gift to get rid of spam posts and spam accounts.

> Spamicide adds an input field to each form then hides it with css, when spam bots fill in the field the form is discarded. The field, and matching .css file, are named in such a way as to not let on that it is a spam defeating device, and can be set by admins to almost anything they like(machine readable please). If logging is set, the log will show if and when a particular form has been compromised, and the admin can change the form's field name (and corresponding .css file) to something else.
> 1 votes

# Answer
Try the `Spambot` module which makes use of stopforumspam.com's database of known spammers.

> Spambot protects the user registration form from spammers and spambots by verifying registration attempts against the Stop Forum Spam (www.stopforumspam.com) online database. It also adds some useful features to help deal with spam accounts.
>
> Features
>
> Checks (username, email, ip address) data against the www.stopforumspam.com blacklist. Blacklisting can be based on either of email, username or IP address (with configurable thresholds).

You could also make use of projecthoneypot.org

> Project Honey Pot is an open source initiative to track abuse, fraud, and other malicious behavior that occurs online. The Project tracks more than a million IP addresses engaged in suspicious behavior each day and reports on them through our website.
> 0 votes

---
Tags: users
---


# Question
Title: Drupal website only in Arabic on English installation
I have installed my Drupal in English Language. But i want my all pages to be only in Arabic as of now. English launch will be later. How i do such that all wesbiste content can be only in Arabic and Admin language will be in English.

# Answer
> 1 votes
First you'll need the i18n module to enable your drupal website for a multilingual setup. It should be no affair to have Arabic as the preliminary language, though you may think about having English as the default language due to some string issues. If you want a website with right-to-left text direction, you'll need a theme which supports this.

A good start to see what's also important can be found in this comprehensive tutorial.

# Answer
> 0 votes
You have to set the default language in i18n to Arabic.

After that you will have to install this module Admin Langauge

> This module lets the administrator see all administration pages in her preferred language.
>
> You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).

---
Tags: 7
---


# Question
Title: Is there a module that displays a RSS feed as horizontally scrolling text?
Is there an equivalent of the ScrollText module that takes text from a RSS feed and shows it as horizontally scrolling text?

The purpose of the ScrollText is showing text taken from node titles as horizontally scrolling text.

What I am looking for is a module that does the same, but with text taken from a RSS feed.

# Answer
> 1 votes
If you mean like a ticker, similar to what news sites have, then you can use the Views Ticker module.

> This module provides new styles for Views module to display news tickers. A comparison of similar modules is available here: http://drupal.org/node/418616.
>
> Available ticker styles:
>
> * Fade: Smooth transition between news titles, light and JQuery-powered
> * BBC Style: Display news titles typewriter-like (Only links)
> * Scroller: Display horizontally or vertically scrolling news titles
> * vTicker: jQuery based Vertical scrolling lines with options: pause time, speed, direction, items displayed
> * liScroller: jQuery based Horizontal scrolling lines with options Direction and Speed

---
Tags: 7
---


# Question
Title: How to add profile image into user profile
I am using D6. I want that users are able to upload their profile image like gmail, Facebook. How can i do this?

# Answer
I got how to upload photo into your profile. First install core module "profile". Go to "user setting" and set the profile image path, if you will get an error like "The directory does not exists".

Follow this instructions---- "go to the database and find a table named 'variable'. In this table find out the entry user\_picture\_path and put a value like this - s:8:"pictures"; where '8' is the length of the path string - 'pictures' which should be in the directory specified in the file system configuration. After setting the variable go in the user settings and change the path accordingly (in this case just write - pictures) and save it."
> 0 votes

# Answer
In Drupal 6 the, goto solution for this is the Content Profile module which allows you to add CCK fields to your user profile (in Drupal 7, the fields API allows you to do this in core):

> This module builds user profiles as content (aka nodes), which opens the opportunity to use all the powerful modules for content for user profiles too, e.g. the Content Construction Kit (CCK). It's intended to be simple and useful, but extensible by further modules.

You will also want to install the imagefield module to be able to add an image upload CCK field.
> 1 votes

---
Tags: users
---


# Question
Title: data in a select list clears out after adding one more field collection
I have a 2 select list inside the field collection. One is a parent list and another is a child list. Child list is populated when the parent list is selected.I use my custom Ajax and JQuery to achieve this. My field collection is in unlimited valued field the problem is whenever I clicked add another item to make a new field collection my previous selected child list looses its data. Is there any way how to retain the previously selected child list.

My jQuery code:

```
$(".field-name-field-countries .form-select").change(function(){
   $('[id$=field-cities-depend-und]').empty();
    //var id=$(".field-name-field-countries .form-select :selected").text();
    var id=this.id;

    var val=$("#" + id  +" :selected").text();

    var dataString = 'id='+ val;

    $.ajax
    ({
        url: "/sites/all/modules/customs/drop_down/ajax_city.php",
        type: "POST",
        data: dataString,
        dataType: 'json',
        cache: true,

        success: function(json)
        {
             $.each(json, function(i, value) {
                 $('[id$=field-cities-depend-und]').append($('<option>').text(value).attr('value', value));
            });

        }
    });

});

```

My Ajax code:

```
<?php

    $con=mysqli_connect("localhost","root","root","d7-demo");
    if (mysqli_connect_errno())
      {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }

     if($_POST['id']){
       $country=$_POST['id'];
       $result = mysqli_query($con,"SELECT country,city FROM cities_link where country='$country'");
       $rows = array();
            while($row = mysqli_fetch_array($result))
             {

             //  $data=$row['city'];
               $rows[] = $row['city'];
             // print json_encode($data);
             }
            print json_encode($rows);
            mysqli_close($con);

    }

?>

```

# Answer
In Drupal, forms are protected from submitting values that was never outputted as available options. When you alter options with custom JavaScript, you are making user to submit values Drupal does not know to be valid. Try to rewrite your code to use form API `#ajax` parameter. It will look more complicated indeed, but it'll make Drupal know about changed options.

Remember to make actual changes in form building function. Ajax handler is there only to provide the part of the form that needs to get updated, and maybe do some one-time touch-ups you don't care to keep.
> 0 votes

---
Tags: ajax, entities, javascript
---


# Question
Title: Which module supporting Google Charts allows for data being specified via a REST call?
I'm looking for a contributed module for Drupal 7 which can be used for creating a chart, and which satisfies all of these criteria:

1. Use Google Charts (the newest 'interactive' ones) as the charting engine (renderer).
2. Must provide an integration with the Views module.
3. The data to be charted are specified via a call, e.g. by using some query string.

Anybody any suggestion for any such module (or combination of modules)?

# Answer
You can use google chart tools for that. It works really well with views.

> Display live data on your site using Google Chart Tools Google Chart Tools module provides a simple API to Build custom interactive SVG charts. The module contain an example module which demonstrate how this module can be use.
> 1 votes

---
Tags: views, charts
---


# Question
Title: How to achieve triggered redirect after log in so that administration interface will be available on the redirected url?
I would like to ask for an advice. Recently, I was developing a conference site with Drupal 7. The site is hosted at domain1.com. However, the conference is covered by another organization and they require that conference page will be accessible from their own domain something like.: organization.com/conference2014 Fortunately, Drupal has base\_url parameter and the site is accessible from organization.com/conference2014 domain. BUt, my problem is when I want to access administration interface of Drupal through organization.com/conference2014?q=user/login I get redirected to organization.com site which is administrated by the organization admin. Moreover, when I access again organization.com/conference2014 - it still asks me for the password.

I got adviced to introduce trigger after the user successfully logs in to the site organization.com/conference2014. It does redirect me but the administration interface/overlays is not there. Any ideas how to tackle this problem?

Martin

# Answer
> 0 votes
Try Login Destination , it will redirect you to the destination

> module allows you to customize the destination that a user is redirected to after logging in, registering to the site (7.x), using a one-time login link or logging out (7.x).
>
> The destination can be an internal page or an external URL.
>
> It is possible to specify certain conditions like referring pages or user roles and make the destination depend upon them. You may use PHP snippets to provide custom conditions and destinations.
>
> It is also possible to keep users on the currently visited page after logging in or out.

also take a look at Login Redirect module

---
Tags: redirection, rules, uri
---


# Question
Title: Alter form to have single radio button term reference checked by default
I have a taxonomy reference field and in the node creation form there will be only one value allowed and I guess I use a radio button and I want it to **be enabled** by default.

I thought I can do it with form\_alter but on inspection in krumo I see the default values are set to the concrete term id.

If I would want to set that id (which I do not know) it could look like:

```
 form['field_abteilung'][LANGUAGE_NONE]['#default_value'] = 12345;

```

For various users and their roles there will be other another allowed option in this form and I just want to do sth like

```
 form['field_abteilung'][LANGUAGE_NONE].... My-single-radio-button = checked;

```

**Update**

I saw I can find out the single option by looking into

```
$form['field_sektion'][LANGUAGE_NONE]['#options'][2]

```

I tried it but get an error about missing index 'field\_sektion' which confuses me.

**update 2** It takes some time, I maybe should have mentioned that the field in the end should be the access control field of https://drupal.org/project/workbench\_access , that module also alters the form; I disabled the field's access function first and now need to rebuild all

# Answer
the way I did it now, is following - First I tried to use a hook provided by workbench access itself which supposed to be for that use case, look here https://drupal.org/node/2019473

But it would not work for me, so I did : this results in a select box with only one possibility. Not the best UX style maybe and later I will try to hide the element, maybe with ds module.

```
function workbench_access_crud_by_state_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id != 'hardware_antrag_node_form') {
    return;
  }
  //sdpm($form);
  $option_arr = $form['field_tu'][LANGUAGE_NONE]['#options'];
  // remove 'none'-option
  array_shift($option_arr);

  // look for field for workbench_access and replace options
  $wb_access_field = $form['workbench_access_fields']['#value'][0];
  $form[$wb_access_field][LANGUAGE_NONE]['#options'] = $option_arr;
}

```
> 0 votes

---
Tags: forms, taxonomy-terms
---


# Question
Title: $base_url set to an external domain causes problems when logging in
I am developing a conference site with Drupal 7. The site is hosted at domain1.com. The conference is covered by another organization, and they require the conference page to be accessible from their own domain, something like organization.com/conference2014.
Fortunately, Drupal has the `$base_url` variable and the site is accessible from organization.com/conference2014.

My problem is when I want to access administration interface of Drupal from organization.com/conference2014?q=user/login. After I enter my credentials, Drupal redirects me to the organization.com site which is administrated by the organization administrator. When I access again organization.com/conference2014, it still asks me for the password.

What I need to achieve is, after entering the credentials, being redirected to organization.com/conference2014, and being to perform any administration task.

Do you have any idea on how to tackle this problem?

# Answer
You can set action on after login user.

And that action could trigger through set a perticular trigger.

please use these url to solve this issue in your site.

1. www.example.com/admin/config/system/actions
2. www.example.com/admin/structure/trigger/user

Hope this works for you.

Thanks Sanjay
> 0 votes

# Answer
Have you tried setting $cookie\_domain to example1.com (The domain you're hosting the website on, not the primary access domain of the conference host). And logging in through that domain?

See: https://drupal.org/node/1096962
> 0 votes

---
Tags: configuration, uri
---


# Question
Title: Drupal commerce get All product variation for list of product
I have a color variation for my products... Not every product does have multiple colors.

I would like to let the user know that one item comes in multiple color (or even show every color available), in the product-category view...

If I add the color field in the "node: product list" in the manage display of the product, it only gives me the color of the first added color variation.

How can it be done ?

# Answer
> 0 votes
Try creating a view that shows "commerce products" which by default starts off by showing all products by product ID which includes all variations. Play around with the fields and contextual filters to get it your liking.

# Answer
> 0 votes
If you could provide more information on version of Drupal and if you are using Commerce modules?

We have done this in the past using Commerce Fancy Attributes module to display colors for products : https://drupal.org/project/commerce\_fancy\_attributes

From module page:

Example usage: 0) Enable this module.

1) Create a Color vocabulary, add a text field called "Color" that will hold hex values.

Go to the "Manage Display" screen of that vocabulary, click the tab called "Add to Cart form - Attribute", enable only the color field (with the label hidden, and using the "Color" formatter).

2) Create several terms with matching hex colors (Black: #000000, White: #ffffff, etc).

3) Add a Color taxonomy\_term\_reference field to a product type.

4) When you add the color field on the product type, tick the checkbox "Enable this field to function as an attribute field on Add to Cart forms." and select "rendered term" as option of the "Attribute selection widget".

The Add To Cart form will now show the colors. Of course, imagefields can be used instead of "textfields holding hex values" rendered as images.

---
Tags: 7, commerce
---


# Question
Title: Email users on node creation based on taxonomy reference
I have 2 taxonomy vocabularies (town and topic) which are referenced on both a user and a node. When a node is created, I need to email all users who are referencing any of the terms referenced on the node EXCEPT when the node has been directly assigned to a user (using a User Reference field).

The Subscriptions module works great for notifying users of all new nodes with a particular term, but I cannot find a way to exclude nodes based on other fields (in my case, the User Reference).

I can use Rules to send an email when a new node is created without the User Reference, but I don't know how to define the recipients as "all users with a referenced term which is also referenced on the new node". VBO may be the answer, but I'm lost on how to generate the View from Rules.

Any suggestions? Thanks.

# Answer
Actually, you can pull up all users (or any entity) based on a field value by using the 'Fetch entity by property' action.

Since users (and nodes, and comments, etc) are all entities, you can use this action to pull up a list of users with a certain value in a field.

In your rule, that gets fired upon the update of a node, simply

* add the '**Fetch entity by property**' action,
* select '**User**' as the entity type, and
* in the final screen choose the field (in your case a term reference) you want to check and the specific value you're checking for.
* Feel free to change the name of the entities it will fetch for you. By default they will be called **fetched\_entity**.

THEN, add a loop to your action set after this fetch, to go through each of the found entities. In this loop, we'll check for your second field and exclude the necessary ones. From what I understand, you'll want to exclude the ones whose **uid** matches the user reference field on the edited node.

So here's how:

By now your rule's action set should look like this: You're fetching users by your taxonomy property, then you'll looping through all the found entries (make sure it's pulling as many as you want, because it limits to 10 by default, by the way).

Now, add a component in your rules. Components are used when you need an entirely new rule to execute in your action area. Now that we're looping through users, we need an entirely new rule to call (IF the user doesn't have field x, THEN do y). However, when we're in the action area, we can't call conditions. So that's why we'll create a component that's a rule within itself, and call it from here.

* Go to admin/config/workflow/rules/components or Configuration --\> Workflow --\> Rules --\> Components
* Click to "**Add new component**"
* Select "**Rule**" for the component plug in. We don't want it to be just a condition test or an action, we want it to contain both a condition and action!
* Call it something like "Email non-referenced users" or something like that
* We will pass it two parameters. We need to pass it the user we're currently looping through and the node that has just been changed (that triggered the rule) because we'll compare the user's uid with the node's user reference field.

* Add a condition to your component that is a '**Data comparison**' condition and compare the looped\_user:uid (or whatever you called that incoming parameter) to the user reference field of your updated\_node (or whatever you called that incoming parameter)
* Careful here, make sure to check the '**Negate**' checkbox at the bottom of that condition. We want to let through only those users for whom the two fields DON'T match, i.e. the ones that aren't referenced.

\- As an action in the component, have the system send out the email you want

Voila! Almost done. This component now narrows down our looped users (with the correct terms) to those who aren't referenced and emails them. The one thing we have left to do is to CALL this component in our user loop.

Go back to your original rule, and click 'Add action' **to your loop** (not below it, but on it)

In your list of actions, at the very, very bottom, you will see the names of components you have created. Your new component should be there. Just select it, and pass it the updated node and the 'fetched\_entity' (which is your currently looped users) as the two parameters.

Test!

Hope this helps.
> 7 votes

# Answer
You'll want to create you're own custom rules action in a custom module, using hook\_rules\_action\_info(). http://drupalcontrib.org/api/drupal/contributions!rules!rules.api.php/function/hook\_rules\_action\_info/7

This action should provide a list of email addresses. You can then loop over this list in your rule, sending a message to each one.

The action would look something like this:

```
function mymodule_rules_action_info() {
  return array(
    'mymodule_get_user_emails' => array(
      'label' => t('Get user emails'),
      'parameter' => array(
        'term' => array(
          'label' => t('Term'),
          'type' => 'taxonomy_term',
        ),
      ),
      'provides' => array(
        'emails' => array(
          'label' => t('List of Emails'),
          'type' => 'list<text>',
        )
      ),
      'group' => t('My Module'),
    ),
  );
}

function mymodule_get_user_emails($term) {
  // Do stuff here to get your list of emails based on the term.
  // $emails would be an array.
  return array('emails' => $emails);
}

```
> 0 votes

---
Tags: taxonomy-terms, rules, entities, notifications
---


title: Multisite and alias suffix

text:
# Question
Title: Multisite and alias suffix
I am actualy working on a Drupal multi-site environment and I am stuck within a alias suffix problem.

I made a setup like this in my sites.php file for the multi-site alias names.

```
$sites['example.example.de'] = 'example.example.de';
$sites['tp-ref.example.example.de.vwp'] = 'example.example.de';
$sites['tp-tst.example.example.de.vwp'] = 'example.example.de';
$sites['tp-dev.example.example.de.vwp'] = 'example.example.de';
$sites['tp-local.example.example.de.vwp'] = 'example.example.de';

```

My VHost Config file is the following.

```
<VirtualHost *:80>
  DocumentRoot "C:/seu/xampp/htdocs/iptp"
  ServerName example.example.de
  ServerAlias tp-ref.example.example.de/vwp tp-tst.example.example.de/vwp tp-dev.example.example.de/vwp tp-local.example.example.de/vwp
</VirtualHost>

```

The host file contains the following lines.

```
127.0.0.1 example.example.de
127.0.0.1 tp-ref.example.example.de
127.0.0.1 tp-tst.example.example.de
127.0.0.1 tp-dev.example.example.de
127.0.0.1 tp-local.example.example.de

```

The URL example.example.de works without any problems; when I am trying to open one of the other URLs, I could open the page, but Drupal seems to have a problem with the path. For example, if I want to open the URL "tp-ref.example.example.de/vwp", Drupal trys to load all CSS and JavaScript files from tp-ref.example.example.de, but it should load it from tp-ref.example.example.de/vwp.

I think this is a base path problem. Does Anyone have an idea about how fix this?

The comment shown in the sites.php is the following one. I used it to edit the sites.php file.

```
/*
 * URL: http://dev.drupal.org
 * $sites['dev.drupal.org'] = 'example.com';
 *
 * URL: http://localhost/example
 * $sites['localhost.example'] = 'example.com';
 *
 * URL: http://localhost:8080/example
 * $sites['8080.localhost.example'] = 'example.com';
 *
 * URL: http://www.drupal.org:8080/mysite/test/
 * $sites['8080.www.drupal.org.mysite.test'] = 'example.com';
 */

```

# Answer
As you're loading all these sites from one directory: 'example.example.de'. You only have one site and therefore one settings.php file and ONE base path which defaults to the root domain.

To do what you'd like to do you'd actually need to multisite these with separate directories for each site. To the best of my knowledge anyway.
> 0 votes

---
Tags: multi-sites
---