# Question
Title: How to add facebook like/share button to every new text I post?
I would like to add facebook like/share button to every new post on news site without doing it manually every single time I post new text. Similar question has already been answered, but I wonder if there is solution that doesn't include much code intervention, for example, is it possible to do it just with Facebook Like Button Module or something alike. Thanks in advance.

# Answer
Hope this will help you, You can achieve this with two module views and facebook after enabling both module go to the structure tab of drupal,click on this

put Fcaebook application Id here:

You can create application id from this link on reference to ur facebook account. Than inside Facebook social go to "**Presets**" click on add fill up this form

for like button put only the name and select radio button of "facebook like button plugin" and select your content type, save the form, Go to view to create a new view,

Select respective field of your node and below that select the "Node:Facebook Social plugin", on settings of this field put your preset name as below

Finally you will get the face book like button on every row of your view.
> 2 votes

# Answer
It sound as if like you're looking for the Facebook Like Button module.

From the project page:

> Rather than having to manually copy/paste the Like this on Facebook code for each piece of content you (or your users) create, this module will automatically add that code to the end of each chosen node type. You are able to add a Like button which likes a given URL (static, e.g. your homepage) or/and put a dynamic Like button on your page to like the page you are actually visiting.

(Btw: It looks like you're mentioning this module in your question. If you have a *problem* with using this module, you need to spell out what the problem is.)
> 1 votes

---
Tags: nodes, social-network
---


title: Redirect "edit" tab on single node view

text:
# Question
Title: Redirect "edit" tab on single node view
I created custom node edit pages and I want the edit tab to redirect from

node/2545/edit

to

topic/2545/edit

or

node/2549/edit

to

arts/2545/edit

depending on the content type

This is not an alias this is a custom edit page/view I created, it is NOT the node edit page or an alias of it. it is a completely separate page and I simply want to redirect to this page when I click edit. In other words "I want to redirect to a completely random page when I click "edit"

>

http://screencast.com/t/zHcFsr8I

# Answer
> 1 votes
(Disclaimer: This is not tested, it's been a while since I did a D6 site...)

First, I would implement hook\_menu\_alter and clone the `node/%node/edit` item into `topic/%node/edit` and `arts/%node/edit`. (If you want to use custom page callbacks for the forms, that's fine. You can make all changes you need to the menu items.) At least, you must change the `access callback` property and set it to the function name of your custom access callback (see below). Now you have three similar menu items with three different URL's. All of these should be visible as tabs on all nodes, so we're not done yet.

Second, I would create a custom access callback to hide the tabs with the incorrect URL's. This is described in HowTo: Add / Remove a menu\_local\_task for specific node types. In your case, the access callback should check the type of node on the current page and use it to decide if the tab must be shown or not. Don't forget to also call `node_access()`, because if the user is not allowed to edit that node, the tab must be hidden too.

Sorry I don't have actual code to share, I hope this helps.

# Answer
> 1 votes
What you are looking for is Sub-path URL Aliases

> The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias. For example, if node/1 is aliased to content/alias, this module rewrites the link to the node edit page node/1/edit to use the aliased URL content/alias/edit instead. This also includes Views URLs taking a node as argument (node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal URLs.

---
Tags: 6, forms
---


title: how to put html in a .module php file

text:
# Question
Title: how to put html in a .module php file
I have a input box created with html need to put in the specific block. I saw posts writing there to add the html by function but i cant do it since it is php file Is it right way to do this? what is the exactly way to do this? function firstmodule\_block\_view($delta = ''){

```
$block = array();

switch ($delta) {
    case 'signup':
    $block['subject'] = t('Newsletter signup');
    $block['content'] = myblock();
    break;
}
    return $block;
}

function myblock(){
//html code goes here????
}

```

# Answer
> 1 votes
So first you want to define a block that contains a form. You define the contents of a block in `$block['content']`.

```
/**
 * Implements hook_block_info().
 */
function MYMODULE_block_info() {
  $blocks['your_block_name'] = array(
    'info' => t('Name of your block'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function MYMODULE_block_view($delta='')
{
  switch($delta) {
    case 'your_block_name':
      $block['subject'] = null;
      $block['content'] = drupal_get_form('MYMODULE_form');
      break;
  }
  return $block;
}

```

An after that you need to define your form. In Drupal you use the Form API to build forms. In the example above we fetch the form called MYMODULE\_form. And the form is defined by implementing hook\_form().

```
/**
 * Implements hook_form().
 */
function MYMODULE_form($form, &$form_state) {
  $form['MYINPUTBOX'] = array(
    '#type' => 'textfield',
    '#title' => t('My label')
  );
  return $form;
}

```

---
Tags: 7, blocks
---


# Question
Title: Can't get rid(find) of this margin. Please help!
I isntalled the Professional theme and Content Glider - all very simple. I got rid of titles and all in the glider, but I can't find the code where the blank line or margin is created. Drupal is new for me. Look and you'll see right away: http://www.aironfix.eu The slider content-type has no body just title and image. Please help.

# Answer
> 0 votes
Inside professional\_theme/style.css line no 727 there is css rule,

```
.node {
margin: 20px 0;
}

```

thats create the margin of 20px white margin.

---
Tags: 7, javascript, theming
---


title: Blocks in Panopoly

text:
# Question
Title: Blocks in Panopoly
I'm working with Panopoly as my very first drupal distribution and am concerned about how I'll define persistent items. For example, with core drupal, I could use or create block regions to define special widgets/page elements that would appear on each page.

How would one best do this in a Panel's based environment like Panopoly? Is it possible to use both blocks and panels? concurrently?

# Answer
> 1 votes
You can still display blocks but now you have more control as to their placement.

## How to Find them

1. Click **Customize this page** on the bottom of your screen.
2. Click **+** in the area you want, for example the header.
3. Once the Dialog appears click **Blocks** or **Custom Blocks**

This is the area where you will see all your Blocks appear.

# Answer
> 1 votes
Actually, **Blocks** is disabled by default in Panopoly. Panopoly uses fieldable panels panes instead. So, you probably need to do this first:

1. Enable **Blocks** in your modules list
2. Create your block (if necessary)
3. Enable your block as *allowed* at /admin/structure/panels/settings/panel-page

Now you can place blocks in your panel pages.

Source: https://www.drupal.org/node/1932120#comment-7235572

---
Tags: blocks, panels, distributions
---


title: bootstrap sub theme rendering garland

text:
# Question
Title: bootstrap sub theme rendering garland
I copied the database and source code from my local to another server. On my local I have a bootstrap sub theme set as default which works fine. On the other server (which has the exact same db settings and code) the theme being rendered is Garland despite being disabled and the admin section under appearance stating that my sub-theme is the active one.

When I checked the site after updating the server it had the correct css but when I reloaded the page it reverted back to garland but without any changes to the admin settings.

What are some good steps to take in terms of debugging this.

# Answer
I deleted the garland theme and re-added it. After this everything worked properly. I don't know why this worked!
> 0 votes

---
Tags: theming
---


title: Extremely large Permissions table

text:
# Question
Title: Extremely large Permissions table
Does anyone know if there's an inherent problem with an extremely large permissions table? I'm dealing with a Drupal install with about 50 roles (permissions were set up using taxonomy terms), and there look to be about 800 permissions. So, quick estimates suggests approximately 40000 checkboxes on the permission table. Now, out of all of these, probably only about .1% are actually checked; I know that the role\_permissions table only stores the enabled permissions. I don't know how Drupal is checking the permissions though as it goes; obviously, if it were making DB calls for each checkbox to check its status, that would be horrible.

Obviously, this can't be a good thing, but can someone tell me if it's necessarily a bad thing? The connection seems to be timing out before table gets loaded (or at least I think it's timing out; this is my first time using IIS with Drupal, and it's error message is vague, to say the least.) Does anyone have any suggestions beyond "remove unnecessary roles"? (Not that it's a bad suggestion, and I'll probably end up having to recommend it anyway, I'm just looking for additional options.)

# Answer
> 1 votes
No, Drupal isn't making a single DB call per checkbox - that would be suicide :)

Looking at `user_role_permissions()` should de-mystify the whole thing...all enabled permissions for the given roles (or all roles if none are provided), are lazy-loaded into memory when they're needed, and statically cached for the same request.

It's about as efficient as it can possibly be when you consider how Drupal's permission system works - I doubt you'll be able to squeeze anything more out of it that wouldn't be considered pointless micro-optimising.

As an aside 50 roles is a *lot*. I've never seen a site with anywhere near that many; if you can reduce the number of *those*, you'll be doing yourself a great service.

---
Tags: users
---


# Question
Title: How to delete all but the current revision from the field_collection_item_revision table?
I have a Drupal 7.24 Website making heavy use of field collections.

The field\_collection\_item\_revision keeps getting bigger and bigger (9'000'000 rows) and only 200'000 entries are in field\_collection\_item.

What is the most secure and efficient way to "clean" this table?

PS: A SQL request with nested selects is not an option, it's too slow.

# Answer
(Assuming a MySQL database)

Execute the following MySQL request:

```
DELETE fcir FROM field_collection_item_revision AS fcir
  RIGHT JOIN field_collection_item AS fci
    ON fcir.item_id = fci.item_id
  WHERE NOT fcir.revision_id = fci.revision_id;

```

We delete all revisions that are not present in the field\_collection\_item table under "revision\_id".
> 1 votes

---
Tags: 7, database, entities
---


title: Problems with permanent caching

text:
# Question
Title: Problems with permanent caching
My requirement is to update some params in the script for a some specific nodes. If a set of nodes is attached to an X content type, it should take some params in a script. For this purpose I am running a cron job every 10 min as new contents can be attached to that X content type. In this cron job, I am fetching all nodes belonging to X content type and also from these nodes, I am getting set of nodes attached to each X node. I am storing the corresponding param value for a node in the cache using the function cache\_set().

```
cache_set(node id, X node id, MY_CACHE_NAME, CACHE_PERMANENT)

```

But the problem is that some nodes are not taking the param sometimes. I think that it is setting the cache, but in the cache table something wrong is happening. But when I run 3 or 4 times the nodes which were not taking param started taking. I am not getting what is happening that cache table.

I am not getting where it is writing to the database. How can we test the problems related to these caching?

I am clearing the corresponding MYCACHE before every cron runs.

```
hook_cron {
  cache_clear_all('*', MY_CACHE, TRUE);
  take_params();
}

```

What am I doing wrong?

# Answer
> 0 votes
Your use of the functions `cache_set()` and `cache_clear_all()` does not look right.

First let us look at `cache_set()`. It stores some serialized data in some persistent cache bin.

Its arguments are:

* $cid - a string that identifies the stored data. The same string is stored in the `$cid` field in the database table named by the `$bin` argument.
* $data - the data to cache. This is stored in the `data` field identified by `$bin` and `$cid`, usually as a serialized object.
* $bin - The *name* (a string) of the cache bin to use. This corresponds to a database table with that name. It should either be `'cache'` or start with the string `'cache_'`.
* $expire - when should the item expire. If set to CACHE\_PERMANENT, the item can only be expired by calling `cache_clear_all()`.

You want to cache some parameters attached to some node. To do that, you may use:

```
$cid = 'mymodule:node_' . $nid;
$data = ...; // Set it to hold whatever object you want to cache.
$bin = 'cache';
cache_set($cid, $data, $bin, CACHE_PERMANENT);

```

Note that `$bin` need to be set to the *name* of one of the bins (i.e. cache database tables) that are already defined.

Now, to clear out this particular item, you need to call `cache_clear_all()` with the *same* `$cid` and `$bin` as was you to set the cache. The final parameter to `cache_clear_all()` can indicate that `$cid` is a wildcard (in your case, it is not). I.e.:

```
cache_clear_all($cid, $bin, FALSE);

```

---
Tags: caching
---


# Question
Title: Improve performance by using drush functions instead of Drupal module functions
I am trying to improve the import performance of a drupal website we are working on. The site makes use of the queue api to import individual items. Currently this process is very slow. I have hear it mentioned that one way of improving performance is to process items using drush rather than having Drupal do it directly.

What our site does is read the contents of a text file and then add each item to a queue for processing. The queue worker function just takes the information, performs some processing logic and then saves it as a node.

From what I understand we would want to move this queue worker function out of the current Drupal module and into drush.

I have been searching for general background information on how to do this or some introductory tutorials, but have not been able to find anything about using drush to improve performance of resource intensive tasks. I am a little surprised that there is so little information on this given that it is supposed to improve Drupal performance.

# Answer
The reason you have heard that performance is better under Drush when processing queues is that Drush has a concurrent-execution feature that it uses to run different parts of batch processes in parallel. Running this code on a live server would not necessarily be a good idea, because any "performance gains" that you experienced from using this code would be at the expense of the performance of your front-end. In other words, Drush does not increase the performance of the processing in terms of CPU cycles needed -- it just arranges things so that more of your CPU cycles can be used all at once, so that the task finishes sooner.

I wouldn't even contemplate trying to do this on your live server unless you already have set up a multiple-machine load balancing system, where multiple servers have concurrent access to the same database. (The other alternative would be to run the queue at a time when you don't care about front-end performance -- however, if you have a time when not many people are using the system, you probably don't care when the batch process finishes anyway.) If you do have multiple machines to throw at this problem, you could consider either (a) porting the concurrent-execution functions to a Drupal module (see backend.inc) or (b) making a web service on a separate machine that 'exec's `drush queue-run` as jonhattan describes.

This would be a little complicated to set up, which is probably why no one has done this yet. A better way to increase performance would be to analyze what is going on in your batch processes that is slow, and see if you can find any ways to optimize the code so that it uses fewer CPU cycles. This would result in an actual performance increase, which would be preferable to a complex system that processed a slow batch process efficiently.
> 2 votes

# Answer
Queues are defined within Drupal modules, and you can use drush to run those queues:

```
drush @site queue-list
drush @site queue-run queue_name

```

Changing the *interface* to the import code (queue, batch api or a drush command) won't affect drastically the import time.

I'd review the import code to try and optimize it. For example by caching (in memory) any data you may be loading recurringly from the database.
> 2 votes

---
Tags: drush, performance, queue
---


# Question
Title: How to override subtheme settings (inheritance)?
I am having some difficulty overwriting my subtheme code using my own theme.css file (located in sites\>all\>themes). I can find the code that results in the display of whichever css style property I'm trying to change (e.g., font-family in the header region) easily, using the chrome DevTool, but when I go to target that area in my own css file it seems not to have any effect on the display. Is there any general methodology with which I can go about inheriting my adjustments to the theme styles? FYI I have renamed my subtheme's files so that is not the issue.

Any help would be wonderful.

# Answer
Assuming you've cleared the cache and all that before trying to inspect any changes, it sounds like your base theme (the theme you've based your sub-theme on) is one of those themes where the configuration is for a large part done by means of the administrative interface. This means that edits done to the `.css files`have no effect, as they're overridden by settings the administrative interface.

A number of popular themes has this property, including the *Adaptive Themes* family and *Omega 3*.

To check out if this is the case, navigate to *Administration » Appearance » Settings* for your theme (or sub-theme). If there is a *lot* of settings for fonts, etc., hacking the `.css` files will not help much and you need to use the administrative interface for styling.
> 0 votes

---
Tags: theming
---


# Question
Title: Views Slideshow, white backround when hover
I'm using drupal 7,views slideshow and views slideshow cycle modules, I have a white background color when hover on the slide, I can't remove it or find their css selector in chrome webdeveloper.

Help me please.

# Answer
> 0 votes
finaly I fix ,I found the selector in the omega base theme css file omega-visual.css

```
tr:hover
td,
tr.even:hover td.active,
tr.odd:hover td.active {
/*  background: #FFFEEE;
*/}

```

Thank you so much

# Answer
> 0 votes
As Sohail mentioned, it's really hard to figure this out for you without being able to view the actual web page. It's most definitely a CSS issue and is just a matter of finding the right selector. Can you just use Inspector in Chrome to find the selector that encompasses that area, and then search within the stylesheet it says it's using for that selector with hover? Perhaps just search the stylesheet for #fff to see where white is being used and then see where it is making that area white?

# Answer
> 0 votes
Hope this will help you

active the hover option of chrome inspector, than check on mouse over with which css rule make the background for your slider, find out the path of the css, than you can change the rule as per your requirement, if that rule is unnecessary not use for others also than u can remove that or you can override with your own css rule.

---
Tags: 7, views
---


# Question
Title: Migrate d2d picture migration destination path incorrect
I'm in the process of building a migration module for a d6 to d7 migration using the d2d module.

I'm almost there, but one thing that's holding me back is the DrupalPicture6Migration. After trial and error, this is what I have (using the d2d documentation):

```
/* Register the picture migration */

$picture_arguments = $common_arguments + array(
  'machine_name' => 'abcdPicture',
  'description' => t('Import Drupal 6 picture files'),
  'default_uid' => 1,
  'source_dir' => '/',
  'destination_dir' => 'public://pictures',
);
Migration::registerMigration('DrupalPicture6Migration', $picture_arguments['machine_name'], $picture_arguments);
}

```

source\_dir points to the correct location: /sites/default/files/userPictures.

I'd expect the migration to go like this:

```
'sites/default/files/userPictures/picture-1589309970.jpg  -> public://pictures/picture-1589309970.jpg.

```

But when I perform the migration, the path gets migrated over instead of the pictures. So I end up recieving this error:

```
'The specified file sites/default/files/userPictures/picture-1589309970.jpg could not be copied to public://pictures/sites/default/files/userPictures/picture-1589309970.jpg.

```

The entire path sites/default/files/userPictures/picture-xx.jpg is copied into the public://pictures directory.

I am reading up on using destination\_file but am failing to make the connection on how I'd code this.

Thanks!

# Answer
You may try to specify the destination\_dir in the \__construct() instead of passing the arguments e.g.

```
class FooUserPictureMigration extends DrupalPicture6Migration {

  public function __construct(array $args) {
    parent::__construct($args);

    // Add simple field mappings
    $this->addFieldMapping('source_dir', FALSE)
         ->defaultValue(MIGRATE_D6_USERPIC_SRC_DIR);
     $this->addFieldMapping('destination_dir', FALSE)
         ->defaultValue(MIGRATE_D6_USERPIC_DST_DIR);

```

Where `MIGRATE_D6_USERPIC_SRC_DIR` is your source dir and `MIGRATE_D6_USERPIC_DST_DIR` is your destination dir (e.g. `public://pictures`).

---

Alternatively you can fix the user avatars by the following one-time query:

```
UPDATE users u
SET picture = (SELECT fid FROM file_managed fm WHERE filename = (SELECT SUBSTRING_INDEX(picture, '/', -1) as filename FROM DRUPAL6_DB.users as d6u WHERE name = u.name AND picture <> '' AND fm.filename = SUBSTRING_INDEX(picture, '/', -1)))
  WHERE u.name <> ''
    AND u.name IN (SELECT name FROM DRUPAL6_DB.users WHERE picture <> '')

```

WHERE `DRUPAL6_DB` is your database name for Drupal 6.
> 1 votes

---
Tags: files, migrations
---


# Question
Title: Edit content if (taxonomy) Country = United Kingdom
I have created a user, now I want to give him permissions so that, when he is logged in, he can view/see all the contents, but can't edit/publish/unpublish/delete them.

Of all the contents, he can view/edit/publish/unpublish/delete only those contents, that has United Kingdom as taxonomy term, for example something like.

Logged in user can see all the contents, but If any content has Country -\> "United Kingdom", then give permission to edit/publish/unpublish that particular content?

I have already tried Taxonomy Access Control, but didn't help me. Either I couldn't see any content, or I could edit all of them.

I want to give permission based on Taxonomy term.

I think I will probably need to do bit of coding.

Help?

# Answer
I have used the Taxonomy Access module before and it should work for what you need to do here.

I'm making some assumptions here:

1) You have a vocabulary called "Country" and "United Kingdom" is a term in that list.

2) You have a field of type "Term Reference" on your content type(s) and it using the "Country" vocabulary.

3) You have a field of type "Term Reference" on your account settings - `/admin/config/people/accounts/fields` and it using the "Country" vocabulary.

Now, make sure your permissions are set properly:

1) go to `/admin/config/people/taxonomy_access`

2) "edit access rules" for the "authenticated user" to get to this page:

3) Under "New" you need to select the term you want to manage access for. Hit the "Add" button.

4) Once added, the term with show under the "Tags" heading in the table. I am using the "Tags" vocabulary here, but yours will say "Country".

5) Now you can modify the permissions for View, Update, Delete, Add Tag and View Tag. There is an explanation of these fields as well as how to manage the permission on the bottom of that page, so I wont include it here.

After you have done this, you can login as an authenticated user and the permissions configured above will control the access to your content.
> 2 votes

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


# Question
Title: Hook_menu() and its page callback: how to redirect users on a condition?
I'm trying to redirect users from an existing path in Drupal 7 to another existing path. I want to implement the following rule:

`comment/reply/123` should redirect to `node/123#comment-form`

But

`comment/reply/123/456` should NOT redirect anywhere and just go where it goes.

I've tried to implement this behavior with hook\_menu(), but here's the problem. When I register an item with the path `'comment/reply/%'` that corresponds to `comment/reply/123`, it automatically includes paths like `comment/reply/123/456`. I know that's intended and changed my code to include this case, but can't figure out how to redirect users only when they hit `comment/reply/123`. Here's my code:

```

function mymodule_menu()
{
    $items = array();
    $items['comment/reply/%/%'] = array(
        'title' => 'bla',
        'page callback' => '_mymodule_redirect',
        'page arguments' => array(2, 3),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function _mymodule_redirect($node_id, $comment_id)
{
    if(isset($comment_id))
    {
        return; //I want to just go to comment/reply/123/456 here, but it gives me a blank page
    }
    else
    {
        drupal_goto('node/' . $node_id . '#comment-form');
    }
}

```

So how do I go where I want to go?

**Update:** This is my final solution: I now use `hook_menu_alter()` to rewrite an already defined link and `comment_reply()` to serve standard comment form.

```

function mymodule_menu_alter(&$items)
{
  $items['comment/reply/%node']['page callback'] = '_mymodule_redirect';
}

function _mymodule_redirect($node, $pid = NULL)
{
    if(isset($pid))
    {
         return comment_reply($node, $pid);
    }
    else
    {
        drupal_goto(drupal_get_path_alias('node/' . $node->nid), array('fragment' => 'comment-form'), 301);
    }
}

```

# Answer
If I've understood correctly, you want to serve the comment reply page provided by core when your condition is met.

If that's the case, you just need to use the `comment_reply()` function:

```
if (isset($comment_id)) {
  return comment_reply(node_load($node_id), $comment_id);
}

```
> 0 votes

# Answer
If you are altering a `hook_menu` item that an existing module defines, use `hook_menu_alter`. You will receive all menu items by reference, and you can alter the necessary menu items as necessary.

In a `hook_menu()` implementation, if you define `example` path, `http://example.com/example`, `http://example.com/example/foo`, `http://example.com/example/foo/bar...` and so on will have the same page callback and other properties. However, if you define `http://example.com/example/foo/mine`, that page will use the explicit definition of `example/foo/mine`. There is a negotiation with `MENU_DEFAULT_LOCAL_TASK` too.

PS: If you are trying to redirect comment pages to their node paths, try this module.
> 2 votes

---
Tags: 7, redirection, routes
---


title: Image as form submit

text:
# Question
Title: Image as form submit
I am building a custom form inside a block that has a clickable image as submit.

Here the screenshot of the outcome:

Here is the form code:

```
function my_form($form, &$form_state) {
  $image = '#';

  if (module_exists('my_base') && function_exists('my_base_get_form_settings')){
    $image = my_base_get_form_settings('IMAGE');
    $form['my_text'] = array(
      '#markup' => '<p>'.my_base_get_form_settings('BODY').'</p>'
    );
  }
  $form['submit'] = array(
    '#type' => 'image_button',
    '#src' => $image,
    '#attributes' => array(
                      'style' => 'width:80%',
                      'OnSubmit' => 'my_function();return false;'),
  );
  return $form;
}

```

I want the image to be clickable and to run the javascript, but without the ugly style of the default button. I didn't find any example that matched my needs.

How to I properly build an image submit in drupal 7? This is obviusly not the right way.

# Answer
You could try a modification of this: found it here.

```
<?php
function theme_form_comment_form_alter(&$form, &$form_state, &$form_id) {

  $form['actions']['submit']['#type'] = 'image_button';
  $form['actions']['submit']['#src'] = base_path() . path_to_theme() . '/img/button-off.gif';
  $form['actions']['submit']['#attributes']['title'] = t('Create Comment');
  $form['actions']['submit']['#attributes']['onmouseover'] = "this.src='" . base_path() . path_to_theme() . "/img/button-on.gif'";
  $form['actions']['submit']['#attributes']['onmouseout'] = "this.src='" . base_path() . path_to_theme() . "/img/button-off.gif'";

}
?>

```
> 1 votes

---
Tags: 7, blocks, media, forms
---


title: Granularity of content types

text:
# Question
Title: Granularity of content types
Let's say you want to have a set of multimedia galleries, that contain a texts, photos and some youtube films. At the phase of creating content types, I can imagine few approaches. For example - we can create the whole gallery as a one content type, with few optional multivalue fields, or we can create separately content types for photo gallery, separate content type for texts, and all that would be linked by using taxonomy, or we can go even more granular - with content type for ONE photo, ONE text etc, and all that would be linked with each other by taxonomy. How granular content types should be and what are advantages?

# Answer
As Eugene Fidelin said, we'd really have to have a better feel for the site in order to give you the best advice. It depends - will *each* gallery have the same fields for each entry? Or does one gallery have videos while another does not? However, I will try to do so anyway.

If there are only a few galleries AND they differ in their fields, I would create a content type for each gallery entry and use them to populate a page with a view. I would do this because otherwise you're going to have to create a single content type with each type of field used by every type of gallery entry, and then for each one you're going to end up having a bunch of empty fields since they are used by the other types of entries.

However, assuming each gallery entry across all galleries has the same fields for the most part, I would just create one content type for gallery entries and then use taxonomy terms and then just use radio buttons to specify what type each entry is (so you might have Animals, People, Places, etc.) and then have views for each type that just filters by the taxonomy terms.
> 0 votes

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


# Question
Title: ckeditor in not showing up on one of my drupal site content type
I have installed ckeditor in my Drupal 7 site. It works well on all content types except one. Actually, on one of my content type it doesn't show on Body field when I write content. But when I open that field in structure then I can see ck editor here.

I googled it but didn't find any helpful thing. So anyone of you who knows please help to resolve this issue.

# Answer
I would click on "Configure" for CKEditor in Modules and make sure "Any content type" is selected. In these settings you can specify which content types CKEditor will be available for, so it's possible that that content type is not selected.
> 0 votes

---
Tags: 7, nodes, wysiwyg
---


title: Displaying uploaded files

text:
# Question
Title: Displaying uploaded files
Preface -- I'm a newbie with drupal and have watched too many youtube flicks on jCarousel and slideshows. So totally confused.

My question: I've created a web form in drupal 7 and would like to do a jCarousel of all the images that have been uploaded via the web form. Is there a way to point to a directory and have the jCarousel load the image files. I tried creating a view with show files, but it didn't load the image files.

I'm trying to do this without css or javascript. I don't pantheon service provider will let me add javascript (I think).

Thanks in advance.

# Answer
> 0 votes
I figured out how to display the image file in the jCarousel. In a view add the file:Name field and set the style settings to HTML and add the image source hmtl tag to rewrite results. Example:

---
Tags: views, javascript
---


# Question
Title: An AJAX HTTP error occurred using commerce coupon percentage
I'm able to create coupons with no errors. When I enter coupon code into the field and click on the submit button I get the following error.

```
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /system/ajax
StatusText: Service unavailable (with message)
ResponseText:

```

Drupal version 7.28

Commerce Coupon Percentage 7.x-1.0-beta7

dblog messages

```
// first error
Rules Warning:
  Unable to get a data value.
Error:
  Unable to get the data property code as the parent data structure is not set.
// second error
Rules Warning:
  Unable to evaluate condition commerce_coupon_discount_coupon_codes_exist_on_order.
// second error
PHP Error:
  EntityMetadataWrapperException:
  Unable to get the data property coupon_id as the parent data structure is not set.
  in EntityStructureWrapper->getPropertyValue()(line 438 of /homepages/
  36/d385915579/htdocs/bbp/sites/all/modules/entity/includes/entity.wrapper.inc).

```

# Answer
> 0 votes
This seems an error in Commerce Coupon Percentage module. Your problem comes from the EntityMetadataWrapperException: when processing the AJAx petition something goes wrong and an Exception is throw. This is fatal, so Apache ends the petition with the status 500.

I think this a bug in the module code, so you may go the issue queue for this module and create a new bug report with your problem.

By the way, the Commerce Coupon Percentage is only comptabible with Commerce Coupon 1.x, check your are using a 1.x release.

---
Tags: ajax, commerce
---


title: Unknown User Registered into my system

text:
# Question
Title: Unknown User Registered into my system
I'm currently doing recruitment system by using drupal 7.. In my system, the user (anonymous) need to register before they can log in into the system. For log in and registration, i use LoginToboggan module. i also use the captcha module to avoid from spam. However, when i look at the people..there is a lot of unknown user.. and it seems like spam. what should i do?

# Answer
These are robot spam registrations. To my eye, they look like they originate from XRumer. XRumer knows how to complete the registration process of LoginToboggan and knows how to solve simple CAPTCHAs, so these measures will not stop XRumer from registering.

The modules I've found to be most effective against *robot* spam registrations are MotherMayI and CAPTCHA Riddler.

Both these are based upon the same idea: To register, the registrant should be able to answer a simple question where the answer is obvious to a human, but not to a robot.

If you site's language is not English, almost any question will work, since robots do not have multi-language skills.

CAPTCHA Riddler lets you set up a "pool" of questions (so a returning robot will face a different question on each visit). MotherMayI only allows one question, but let you set up an RegExp for the answer and also has allows for a longer text to "hint" to a human what is expected. I currently prefer MotherMayI, but check out both.

PS: So far, *no* spam robot has managed to register at any of my 20 sites (all that accepts registrations by the public are protected by MotherMayI).
> 6 votes

# Answer
If Captcha isn't working (and you definitely have it turned on, obviously), I'd recommend using something like Botcha instead:

> BOTCHA is a highly configurable non-CAPTCHA spam protection framework.
>
> *In CAPTCHA, user has to prove he/she is human. Unfortunately, spambots learned to bypass CAPTCHA really well, and real users are frustrated with increasing complexity and burden of CAPTCHA.*
>
> In BOTCHA, we don't abuse our human users - BOTCHA protection is completely transparent to them and non-intrusive.
>
> BOTCHA lets spambots to prove they are bots, and let real users zip by.

Works a lot better than Captcha in my experience, and less intrusive to the user. Bear in mind this is just one spam-prevention tool, depending on how hard your site gets hit you might have to take more drastic measures.
> 4 votes

# Answer
You can also consider using Honeypot or Mollom.

> Honeypot uses both the honeypot and timestamp methods of deterring spam bots from completing forms on your Drupal site. These methods are effective against many spam bots, and are not as intrusive as CAPTCHAs or other methods which punish the user.

So, Honeypot has the same philosophy as Botcha (spam bot centered).

Mollom has Acquia / Dries Buytaert experience of Drupal behind and provides combined features: text analysis, spam database, then CAPTCHA if there is a doubt about the content + hidden honeypot feature. Several plans are proposed (free / paying), depending on the amount of spams and service wished.
> 0 votes

---
Tags: users, advertising
---


# Question
Title: Cannot use my drupal installation after enabling new custom theme
I keep geting this error message on every page request:

```
Fatal error: Allowed memory size of 167772160 bytes exhausted (tried to allocate 36 bytes) in C:\wamp\www\mydrupal2\includes\theme.inc on line 98
Call Stack
#   Time    Memory  Function    Location
1   0.0100  142240  {main}( )   ..\index.php:0
2   0.0220  449448  drupal_bootstrap( ) ..\index.php:20
3   0.2050  3025040 _drupal_bootstrap_full( )   ..\bootstrap.inc:2259
4   0.6290  15508712    drupal_theme_initialize( )  ..\common.inc:5144

```

Increasing memory allowance has not had any effects. I try using drush to disable the offending theme or go back to the last working one, it's the same error message. I can't even use drush for anything else. It reports the same error message. I tried the SQL method on this drupal.org page. Same result.

# Answer
> 0 votes
theme.inc on line 98 is trying to collect theme's ancestors.

My bet is that your custom theme is wrong and it's telling Drupl that is a subtheme of itself, making Drupal the enter in an infinte loop that exhausts memory.

Double check your custom theme configuration or just move it away from Drupal directories so Drupal can't process it.

---
Tags: 7, theming, bootstrapping
---


# Question
Title: Multiple submit buttons: Which one was pressed?
This may be a duplicate of the following: Multiple form submit, but I am unable to figure out how the answer applies to my situation. So here is my go at asking this (I admit) quite similar question:

I have a table with a row of data, each row has a submit button. It may look something like this:

```
$form['f'] = array();
foreach ($rows as $row) {
  $form['f'][$row['nid']] = array();
  $form['f'][$row['nid']]['nid'] = array(
    '#markup' => $row['nid'],
  );
  $form['f'][$row['nid']]['submit'] = array(
    '#type' => 'submit',
    '#value' => t('sumbit'),
    '#submit' =>  array('f_submit'),
  );
}

```

I.e. the form consists of a sequence of rows, extracted from the database, I want to create a submit callback that picks up the value of the corresponding `nid` field and prints out its value. I guess I am asking what to put where the comment below is.

```
function f_submit($form, &$form_state) {
  // Here I want to print the value of the relevant nid field
}

```

# Answer
> 6 votes
Data about clicked button is stored in `$form_state['triggering_element']`. You can get the node ID by looking at `$form_state['triggering_element']['#parents']`. In your case the node ID would be the second item in the parents array. Please note that the name attribute of the field definition needs to be defined and unique. Otherwise the triggering element will point to the last submit button on the form. I would alter your code as follows:

```
$form['f'] = array();
foreach ($rows as $row) {
  $form['f'][$row['nid']] = array();
  $form['f'][$row['nid']]['nid'] = array(
    '#markup' => $row['nid'],
  );
  $form['f'][$row['nid']]['submit'] = array(
    '#type' => 'submit',
    '#value' => t('sumbit'),
    '#name' => 'submit-' . $row['nid'],
    '#submit' =>  array('f_submit'),
  );
}

```

Good way to view `$form_state` is to install the Devel module (for `krumo()`) and then putting `krumo($form_state);drupal_exit();` to top of the submit handler. This will print out a nice structured tree of data.

# Answer
> 1 votes
Set the `#name` property of each submit element to a unique value like your `$row['nid']`. This unique value can be accessed from the submit function through `$form_state['clicked_button']['#name']`.

# Answer
> 0 votes
I was struggling with this for a while and came up with this workaround. I wanted to have two separate submit buttons with slightly different behavior. I also wanted to add and remove them with jQuery.

So, I did this.

Create two buttons with unique names.

```
    $form['edit-submit'] = array(
        '#type' => 'submit',
        '#value' => t('Reclassify Selected'),
        '#name' => 'default-submit'
    );

    $form['classify-submit'] = array(
        '#type' => 'submit',
        '#value' => t('Re-classify'),
        '#name' => 'classify-submit'
    );

```

Hide the button that I want to use dynamically.

```
    $(document).ready(function() {
        // Hide the classify button
        $('#edit-classify-submit').css('display', 'none');
    });

```

Clone that button as needed into other places in the form and page.

```
    $('#edit-classify-submit').clone().appendTo('.my-form').css('display', 'inline-block')

```

It seems that if you don't add the button definition in through the drupal form declaration it won't be in $form\['triggering\_element'\].

---
Tags: forms
---


# Question
Title: Changing numbers of render-blocking JavaScript and CSS
I have a drupal 7 site. I use the Advanced CSS/JS Aggregation module

In the past I asked this question, and tried to improve performance and "*Eliminate render-blocking JavaScript and CSS in above-the-fold content"* as Google Page speed test suggested.

After I got answers to the question I changed the module configuration, and set the Target Number Of CSS & JS Bundles Per Page to be 4.

For some reason, now, when I am running speedtest, I see that I have "*9 blocking script resources and 5 blocking CSS resources"* instead of 4 clocking for CSS and 4 blocking for script.

Why is that happening?
How can I fix it, and make the advagg configuration work?

# Answer
> 1 votes
The bundler works per region, so set it to 2 for JS as you have footer JS and header JS; 2 header + 2 footer + 2 external scripts will give you 6 for desktop and 3 for mobile, as Page Speed Insights seems to only count header JS for mobile. Moving all the JS to the footer might help eliminate all render blocking JS with mobile according to Page Speed Insights Mobile; it will also give you a better score for the Page Speed Insights desktop as more JavaScript files can be combined.

You can disable the bundler as that will give you a better score, but you will have to download a new full sized CSS/JS aggregate if any of the CSS/JS changes per page on your site; so you won't be able to fully take advantage of the browser cache and real world performance will not be as optimal as it could be if you do disable the bundler. It's about tradeoffs.

http://www.webpagetest.org/result/140619\_5M\_134C/ Shows a decent report as well.

---
Tags: theming, performance, 8
---


title: How to cache POST requests with Boost

text:
# Question
Title: How to cache POST requests with Boost
Boost reacts and caches only GET requests. Does anybody know how to force it to cache POST requests too e.g. using specific key param in URL?

Or at least how to call Boost method that caches request and method that check whether this page exists in cache?

**Update :**

Answer below is good and marked it as an answer but i decided that i am not so familiar with Boost and Drupal to go so deep so now i am using Boost for cashing GET requests and my own module to cache POSTs. Boost works faster because it uses redirects within HTACCESS but it requires additional setup. Even though method below is a little slower it allowed me to change execution of my AJAX from 5 seconds to 900 ms in average.

**My module :**

It maybe absolutely wrong so do not think that this is a recommendation, just keep in mind that this is easy enough even without Boost.

```
// I am caching AJAX POST requests and thus separate these actions by URL params

function customactions_init() {

    $template = null;
    $cache = isset($_REQUEST['cache']);

    if ($cache) {

        switch (true) {
            case isset($_REQUEST['views']) : $template = json_encode((array) $_REQUEST['views']); break;
            case isset($_REQUEST['nodes']) : $template = json_encode((array) $_REQUEST['nodes']); break;
            case isset($_REQUEST['loaders']) : $template = json_encode((array) $_REQUEST['loaders']); break;
        }

        $cache = DRUPAL_ROOT . '/sites/cache/' . md5($template);

        // if file cache was found - use it and stop everything else

        if (is_file($cache)) {
            die(file_get_contents($cache));
        }
    }
}

// Define some static path - can be moved somewhere to config

function customactions_get_directory() {
    return DRUPAL_ROOT . '/sites/cache/';
}

// Returns path to cached content that was built based on URL params

function customactions_get_key($params) {
    return customactions_get_directory() . md5(json_encode((array) $params));
}

// Clear cache when some node changes

function customactions_node_presave($node) {
    @array_map('unlink', glob(customactions_get_directory() . '*'));
}

```

**Any template file, e.g. page.tpl.php :**

```
<?php

    $nodes = array();
    $ids = array_unique((array) $_REQUEST['nodes']); // Get node IDs from AJAX

    foreach ($ids as $k => $v) {
        $nodes[$v] = drupal_render(node_view(node_load($v))); // Create nodes
    }

    ob_start(); // Start buffering output
?>

<div id="page-node-wrapper" class="page-container">
    <?php print sonifi_render(sonifi_device() . '/header.php') ?>
    <div id="content">
        <?php print implode('', $nodes) ?>
    </div>
    <?php print views_embed_view('footer', 'default'); ?>
</div>

<?php

    $output = ob_get_clean(); // Closing buffer

    // If module and its function are enabled then create cache file

    if (function_exists('customactions_get_key')) {
        file_put_contents(customactions_get_key($_REQUEST['nodes']), $output);
    }

    print $output; // otherwise show content as usual
?>

```

# Answer
You would need to do 2 things. Create your own hook\_init that runs after boost\_init to modify the global $\_boost\['cache\_this'\] value & use hook\_boost\_cookie\_handler\_callback\_alter to write your own boost\_cookie\_handler function that works with POST.

To check if the page exists in the cache the boost\_block\_view\_status() function has the parts needed but it has not been abstracted out so you would need to create your own function to do this.

That will cache POSTs.

If you want to serve from the cache on a POST (ignore the post) in your htaccess file remove `RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR]`.

A lot of things can go wrong if doing this. It's a bad idea 99% of the time.
> 3 votes

---
Tags: ajax, caching
---


title: Get form select field values from view

text:
# Question
Title: Get form select field values from view
I'm struggling to find a working method for populating the key & value pairs of a select field (created with forms api) with data from a view.

e.g.. I have a view of 'location' content types.

In the form I've created I need a drop down showing all these location names and a reference from their content type as the key.

Can anyone suggest the easiest method?

# Answer
In lieu of using Views to handle the query, for performance reasons you are probably better off doing something more direct with the db, just make sure that you follow standards for security when accessing the db via any method. Here is a link to the Writing Secure Code documentation - a must read for anyone delving into this area.
> 0 votes

---
Tags: views, forms
---


# Question
Title: How to set a custom URL for a node without pathauto?
I have a content type that requires me to assemble a URL from several sources - the node title, a taxonomy value, and some fields of a product that are referenced from a product display that this content type references. So:

mynode type
\- title
\- taxonomy value
\- entity ref -\> product display -\> product field

The entity ref can have one or more products, so there is some logic I need to crunch to assemble the right URL. I didn't have luck doing this through pathauto, so it looks like I need to handle this on hook\_node\_presave(), which does set my alias, but I get a 404 on that alias, so it seems I'm missing a step.

My code is:

```
mymodule_node_presave($node) {
    if (empty($node->path['alias'])) {
        $node->path['alias'] = _some_fx_that_figures_out_url();
        $node->path['pid'] = 0;
        $node->path['language'] = LANGUAGE_NONE;
    }
}

```

I guess I'm missing something?

# Answer
> 1 votes
This seems to be a duplicate of this issue

Try using hook\_node\_insert($node) for new content and/or hook\_node\_update($node) for existing content:

```
function mymodule_node_insert($node) {
  if ($node->type == 'mytype') {
    $node->path['alias'] = _some_awesome_pattern_maker($node);
  }
}

function mymodule_node_update($node) {
  if ($node->type == 'mytype') {
    $node->path['alias'] = _some_awesome_pattern_maker($node);
  }
}

_some_awesome_pattern_maker($node) {
  // massage node and return string
}

```

---
Tags: 7, path-aliases
---


title: Node with picture left and text right

text:
# Question
Title: Node with picture left and text right
I have a content type with image and body fields. I am trying to edit the css so that the picture is on the left and the body/text is on the right with all the text staying in a column on the right rather than wrapping around the bottom of the picture. I attached a picture. I want what is show on the bottom. What is shown on the top is what I currently have. I don't want to use a module such as Panels or Display Suite.

Thanks for you input!

# Answer
> 1 votes
This appears to be about primarily about the CSS, and the right answer depends on how the html is structured.

Have you tried any resources like Learn CSS Positioning in Ten Steps?

If there are already some containers, you can float both the containers left and give them specific widths (probably). Or you could use absolute positioning. Do you have to account for the picture potentially NOT being there?

My best suggestion is to use Firebug or Inspector or similar to try out a couple things based on your DOM

# Answer
> 0 votes
are you planning to integrate the wysiwyg editor? with that option you could even control the size of the pictures and you can adapt it with the insert module to make sure that they can only insert certain sizes of the pictures. In that way you can make your users have certain control.

The following link has a conference helped me a lot to integrate the editor, you can create your own classes and help control better how everything is displayed Best practice for wysiwyg editor

# Answer
> 0 votes
Use property inspector or firebug to get the class of id names of your picture and body.

In chrome I just right click the photo, and click Inspect Element.

You should find the dome elements where the photo and the body are siblings.

Then add a `float: left;` to the photo.

Let's say your photo is 300px wide. Add a `margin-left: 310px;` to your body.

I use this all the time. It would look something like this:

---
Tags: 7, theming
---


# Question
Title: JWPlayer in Drupal has container ID starting with Numeric Character
Following up this question on SO, I am looking to change the default DIV container name that JWplayer provides to JWPlayer Div. The problem is that it starts with a numeric and that creates loading problems.

Is there a way, I can customize this JWPlayer ID ?

This is how it looks btw,

```
jwplayer('141ef7fe77391234fc105767808cc0a5').setup({"file":"my_video.mp4",
      "width":"838","height":"383","controlbar":"none",
      "modes":[{"type":"html5"},{"type":"flash","src":"http://path/jwplayer/player.swf"}]});

```

# Answer
> 0 votes
While you're at it, here is a quick solution to it.

Since this is a fix for Drupal JWPlayer Module, do the following:-

* Go to `jw_player` module folder and open `theme` folder.
* Open `jw_player.tpl.php` and add the following line on top (probably where PHP declaration starts).

> ```
> $html_id = "myvideo". $html_id;
>
> ```

It kinda does the job but I am sure you guys have better solutions than this. Please feel free to comment.

## Found a better solution

Don't do upper suggestion. Paste the following code in `jw_player.module` instead.

Find this line `$variables['html_id'] = md5(rand());` (I guess line 308) and uncomment it before pasting the following code instead.

```
while(1) {

      $variables['html_id'] = md5(rand());
      if (ctype_alpha(substr($variables['html_id'], 0, 1))) {
        //echo "First Digit is Alphabet";
        break;
      }

  }

```

Thanks.

---
Tags: files
---


# Question
Title: How to change this "Anonymous's Blog" link to another name?
I am trying out the Education distribution. However, I cannot find where/how to change the "ANONYMOUS'S BLOG" link (shown in red box below) to another name, for example: "BLOGS". Where is the link's name stored?

# Answer
> 2 votes
The link name is derived from the author of that node. The variable should be `$content['links']['blog']['#links']` array, which can be found in `node--blog.tpl.php`. You can manipulate the data at that point, which is best kept as simple as possible, due to being in the tpl file itself.

If you're looking to do complex changes, I would suggest a `_preprocess_node` in your template, which is probably ideal if you're doing anything more than an unset or simple truncation.

More information can be found at https://www.drupal.org/node/1783428 and Preprocess function for node.tpl.php file respectively.

---
Tags: 7
---


# Question
Title: How to deny certain terms from being allowed in autocomplete field?
I'm looking for a way to restrict my users from creating certain terms that do not belong in that particular field. I want them to be able to add terms on the fly, but I also want to deny certain terms from being used.

Some examples of this could be swear words, or more specifically in my case abbreviated words. (MN, WI, MI - I want to force them to use - Minnesota, Wisconsin, Michigan)

# Answer
You should be able to create a custom module that uses taxonomy\_autocomplete\_validate to validate the input on node\_presave and/or node\_save. You would just need to define a list of banned terms, either directly in the module, or from an included file that could be more easily maintained.

You could always go one step further and build an administrative interface within the module, but that's probably veering too far away from your question.
> 0 votes

---
Tags: taxonomy-terms
---


# Question
Title: I try to customize my block id and it doesn't work
I create a block which I want to theme.

My block ID is 1.

In my mind it was simple as create a file block--block--1.tpl.php and make some theming on it, but I didn't see any of my change.

One important point here, is that I'm using Panel. I wanted to drop this block into a panel region.

this is what I see in firebug

```
contextual-links-region panel-pane pane-block pane-block-1

```

Thanks a lot.

# Answer
> 0 votes
You can set your block to a 'system block' from within the Panels pane management interface. It should then pick up on the system level block template files.

This also may be a duplicate of How to use a custom block template when the block is embedded in a panel pane?, but there wasn't a definite 'good' answer there either it seems.

---
Tags: blocks, panels
---


# Question
Title: Drupal 7 - HTTP/AJAX/JSON responses at same URL with Accept Header (like D8)
Drupal 8 has this new amazing in-built functionality for handling requests from browsers and via AJAX at the same URL using the Accept header, which makes the CTools way of adding "nojs" to URLs, and then changing that to "js" in the JavaScript seems like a clever but antiquated hack.

Is there a cleaner way to do this, that could be considered a "best practice" for Drupal 7 going forward, that is more inline with how things are now done in Drupal 8? Also, how does a traditional ajax response versus a json response factor into this?

Code examples would be highly useful here.

# Answer
> 1 votes
I am not sure whether this is clean or "best practice" but I am currently using something like this:

```
  // If the request has the header 'Accept: application/json'
  // return the output in JSON format and stop.
  if ($_SERVER['HTTP_ACCEPT'] == 'application/json') {
    drupal_add_http_header('Content-Type', 'application/json; utf-8');
    print json_encode($strings);
    exit;
  }

```

To see it in the context, here is the whole function:

```
<?php
/**
 * Menu callback: translations/search.
 *
 * Search strings and translations using various filters.
 *
 * If the request header 'Accept: application/json' is set, then
 * the output will be in JSON, otherwise it will be an HTML page.
 * For example:
 *   curl -k -i -H 'Accept: application/json' \
 *        'https://dev.l10n.org.xx/translations/search?lng=sq&words=space'
 */
function btrClient_search() {
  // Get the search parameters from the GET request.
  $params = btrClient_get_search_params();

  // Get the strings that match the search params.
  $btr = btr_user_is_authenticated() ?
    wsclient_service_load('btr') :
    wsclient_service_load('public_btr');
  $result = $btr->search($params);
  $filter = $result['filter'];
  $pager = $result['pager'];
  $strings = $result['strings'];

  // If the request has the header 'Accept: application/json'
  // return the output in JSON format and stop.
  if ($_SERVER['HTTP_ACCEPT'] == 'application/json') {
    drupal_add_http_header('Content-Type', 'application/json; utf-8');
    print json_encode($strings);
    exit;
  }

  // Add the CSS and JS files.
  drupal_add_css(drupal_get_path('module', 'btrClient') . '/editor/editor.css');
  drupal_add_js(drupal_get_path('module', 'btrClient') . '/editor/jquery.worddiff.js');
  drupal_add_js(drupal_get_path('module', 'btrClient') . '/editor/editor.js');

  // Add RTL style if the current language's direction is RTL.
  $languages = btrClient_get_languages();
  $lng = btrClient_get_translation_lng();
  if ($languages[$lng]['direction'] == LANGUAGE_RTL) {
    drupal_add_css(drupal_get_path('module', 'btrClient') . '/editor-rtl.css');
  }

  // Set the title.
  drupal_set_title(t('Search Translations'));

  // Add the filter form.
  $output = array(
    drupal_get_form('btrClient_filter_form', $filter),
  );

  // Output the strings.
  if (empty($strings)) {
    drupal_set_message(t('No strings found. Try adjusting the filter options.'));
  }
  else {
    pager_default_initialize($pager['number_of_items'], $pager['items_per_page']);
    $output[] = drupal_get_form('btrClient_translate_form', $strings, $lng);
  }

  return $output;
}

```

(Or check it out here: http://cgit.drupalcode.org/btrclient/tree/includes/search.inc

---
Tags: chaos-tool-suite, 8, ajax
---


# Question
Title: Printer Module: Show link base on Content Type
Let say I have content type A, B, C and D. How can I show the Printer Module's Link on B and D only? The one with PDF version, and ePub Version.

# Answer
> 2 votes
Edit the content type and go to **Printer, email and PDF version** and choose to display or not.

---
Tags: nodes
---


# Question
Title: Loading js file for all browsers except IE
I have a requirement to add a js file only for IE (6, 7, 8) browsers. The following script works fine and sometime it doesn't. I cleared the cache several times but has no difference.I don't know where I am going wrong . Is there anything to do with `drupal_add_js` for IE?

```
function mymodule_init() {
  if(strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
    $theme_path = drupal_get_path('theme', 'mythemename');
    $js_path = $theme_path . '/script/modernizr.js';
    drupal_add_js($js_path, 'external');
  }
}

// The code modified to true for all browsers it works for all browsers but not in IE
function mymodule_init() {
  if(1)) {
    $theme_path = drupal_get_path('theme', 'mythemename');
    $js_path = $theme_path . '/script/modernizr.js';
    drupal_add_js($js_path, 'external'); // loading in all browsers except IE
  }
}

```

# Answer
> 0 votes
The problem is, you're using `hook_init` which is not run on cached pages.

Because your cache isn't varying by user agent, you're not getting a consistent response.

An easy solution would be to use something like a conditional IE tag in your theme `html.tpl.php` and add the JS in there:

e.g:

```
<!--[if !IE]>
<script type="text/javascript" src="/sites/all/themes/mytheme/script/modernizr.js"></script>
<![endif]-->

```

# Answer
> 0 votes
As you may be suspected, the original condition is wrong. Here's a related post on how someone was able to find a better condition for checking the user agent for IE:

https://stackoverflow.com/questions/5302302/php-if-internet-explorer-6-7-8-or-9

summary: use this instead:

```
if(preg_match('/(?i)msie [1-8]/',$_SERVER['HTTP_USER_AGENT'])){}

```

# Answer
> 0 votes
Try the Conditional styles module

> Without this module, the only way to have IE conditional stylesheets was to add 37 lines of code (more if you want to add more than one stylesheet) in four horribly-difficult-to-remember function calls to your theme's template.php. Blech. Who wants that?
>
> This module allows Drupal 7 themes to easily add conditional stylesheets to the theme's .info file.

---
Tags: 7
---


# Question
Title: How do I populate an exposed filter with titles of user's content?
I have a view that displays all reviews written by a user. One piece of information that is included in these reviews is the band that the user was playing in at the venue that the review is for. So, I have an exposed filter on the view that allows people to filter reviews by band name.

http://www.gigindie.com/users/jhegg23

However, the exposed filter renders as a text field. I'd like to change this into a select list containing the currently viewed user's bands. So, instead of the user typing in the name of the band that they want to filter the reviews by, they can instead select a band from the list. I know that I can alter the form type within a custom module, so that it renders instead as a select box. However, I also need to populate the options of the filter with the names of the bands that the user is in.

Bands are a content type of their own. Is there a way to do this, with maybe a view or something?

EDIT - As requested in the below comment: It's D7, and it's a view of content (filtered by content type: review). The view is a block appearing in the user's profile, with a contextual filter for author UID from the page url. And yes, there is an entity reference. The user creates their bands, and then when they write a review, they select a band, which creates a reference in the review to the band.

# Answer
Views Reference Filter can be helpful. I you have to create a ER view of node title and then you can use this ER view in your main view exposed filter of type reference.
> 1 votes

# Answer
Hum, If you're ok to build a module, you have to alter the form, like described here for example. Maybe there's a better way with hook\_views\_post\_render.

But in all cases you'll have to build an options array. Thus you can do a db\_select :

```
$result = db_select('field_reference', 'n')
->condition('bundle', 'band')
->fields('n', array('entity_id', 'field_band_nid'))
->execute()
->fetchAll();

$options = array();

foreach($result as $band) {
  $theband = node_load($band->field_band_nid);
  $options[$band->entity_id] = $theband->title;
}

```

I know, the node\_load is a bit heavy, but I can't see how you can have the band title in the select list otherwise...

*Careful, I didn't test it :)*

If you don't want to build a module for that, there's an "ugly" way to do it : build a block with PhP filter, and create a simple HTML form with a dropdown menu created like this, and that leads to the same page, with a new argument like ?band\_nid='n', and use it in a second contextual filter (with the field entity\_reference).

Sorry for the mess, i hope other people have cleaner ways solve your problem.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How can I configure the backend to get a comfortable image insert functionality with captions?
Since Drupal offers many different approaches to inserting images, I am a bit lost. I am looking for a configuration that allows editors to comfortably insert images with captions. My requirements are:

* Works with WYSIWYG editors
* One input form to upload the image and enter the caption
* At most one more step in the workflow to position the image in the text
* Ability to create blocks with several images side-by-side
* Ideally, no code changes (inserting JavaScript or altering PHP) should be necessary in order to retain upgrade capabilities

It seems that many people are using a combination of the wysiwyg module with IMCE and the IMCE wysiwyg bridge. However, I don't see any support for image captions in that toolchain.

The other alternative is the Insert Image With Text module, which is still in beta and rarely discussed anywhere. As far as I understand, this method is not really practical because it limits users to one image per node (or would require several image fields in the respective content type).

Is there any combination of modules and content settings that can fulfil those requirements?

# Answer
You are looking for Insert module.

> Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.

Features

* Support for all major WYSIWYG editors, including tinyMCE, CKeditor, the WYSIWYG project (the recommended approach), and plain text areas.
* Insert images using ImageCache presets
* Maximum width setting for inserted images (for combined use with the Image Resize Filter module)
* Per-field insert configuration

>
> 3 votes

# Answer
Have you tried the Media module? From the project page:

* Add media (images and video) into any textarea (requires Wysiwyg module).
* Use the fields API (formerly CCK) to add fields to any type of media, eg. captions on images.
* Plugins to use remote media from sites like YouTube, Flickr, ...
* A unified interface for adding any type of media as a field to nodes.
* Mass importing of files.
* Drag and drop upload (with Plupload module).
* Responsive image support (with Picture module).
> 5 votes

# Answer
You can achieve that by using the Insert image with text module

> This module extends the functionality provided by the Insert module, by extending the inserted markup for the image, to contain a text below the image. For all available styles, a variation with additional text is added the list of choices, and the entered description text is added to the wysiwyg where it's still editable in its own container. The inserted markup can be overridden by a template.
>
> **Usage**
>
> Install this module and the **Insert** module.
>
> Create an Image field on a node, and check the "Enable Title field" option. In the field settings, at the "insert" section, check the "Enable insert button" field, and select the styles/presets you want to insert. Those with the description enabled, are prefixed with a "With description" text.
>
> Now you can enter text in the field after uploading an image into the field, then select a style/preset with description, and the image will be inserted with the chosen description in the WYSIWYG.
> 0 votes

---
Tags: 7, media, wysiwyg
---


# Question
Title: how to disable and delete correctly the boost module
in the last days Im having serious problems with the module boost, for some reason it is not loading the Javascript files, and CSS files. My site looks horrible for anonymous users its not loading the slider, but if I log in as admin then the site is displayed correctly, also after logout the site works correctly, but after clear browser's chache the sites looks horrible again

this is the errors that the console of Chrome shows me

Im almost sure that this problems are coused by the boost module, I need to reset it, or uninstall it, but need to know the correct steps for delete all the traces of this module that its causing me problems. Thank you

# Answer
> 0 votes
Ok I could fix the problem, the Boost module creates a folder called "cache" in the root of your website, I jsut deleted that folder, and Boost rebuilt it again and the site works ok now

# Answer
> 1 votes
You have to delete the added boost code from .htaccess

In setting up the module you create this.

If you skipped that step you might check the htaccess tab in boost config and add those lines.

If you did not skip that step...

disable and uninstall the module then delete that added htaccess lines and directory.

---
Tags: 7, theming, caching
---


# Question
Title: How do users can login automatically through URL when they click on the link received in Email
In Drupal 7, I am sending E-mail to each user with some content. Here I need to send link to automatically login through URL means when they click on the link they should redirect to the site and submit the form. This form should submitted by only authenticated users. How to generate those Unique URLs. Is there any module for this or give me any ideas please.

# Answer
Try the Login one time module

> Login one time provides the ability to email one-time login links to users. You can also choose the pages they will land on.

Another module is urllogin

> This module provides a way to transparently log users into the web site when they follow a link. The primary use is for mass email where users are send individualized URL’s which take them to a page on the site, in a “logged in” state. Every effort has been made to minimize the potential security risks.
> 1 votes

---
Tags: users
---


title: node_delete and caching

text:
# Question
Title: node_delete and caching
Why is it that node\_delete (which calls node\_delete\_multiple) empties all node cache *even though it has the list of specific nids?*

I have 200K+ records, all of which I would like to cache pre-emptively by entitycache module + Drush Entity Cache Loader (ECL). This is (obv) an expensive operation - but deleting even one node empties entire cache.

I realize that I can simply modify entitycache module to do exactly what I want - but I am just wondering about the rationale behind emptying entire cache.

# Answer
One reason i see is Entity Reference...

For Example -

* A block which lists some nodes part of your delete list.
* A node which has entity reference to your deleted node
* A view page which has some of your deleted nodes

**Reason for clearing all the caches**: When a node is created/updated/deleted there can be many pages in the site which are dependent on the current node in question. It is next to impossible/very difficult identify all the dependencies and clear the caches only for those pages. For this particular reason, to make sure that no stale data is served to the end user drupal by default clears all the caches.

So, It makes sense to Clear the page and block and node\_load\_multiple caches as documented in node\_delete\_multiple function.
> 5 votes

# Answer
**Short Answer** : This is as per design. You are relying on Page Caching and it cannot differentiate whether it is a node page or any other page. So it clears all the caches. But you can override this behavior.

If you want to know more about why it is as per design read my answer Whenever I edit/update a node all the page caches for anonymous user are lost

In the answer I have also included the possible work-around for the same.
> 0 votes

---
Tags: 7, nodes, caching
---


# Question
Title: Select list field type as sorting order criteria
I have a view which uses a custom field called article type as it's sorting criteria to sort articles. This article type field, has the following options:

```
0Editorials|Editorial
2Feature|Feature
5Spotlight|Spotlight
6Special|Portraits
3Perspective|Perspective
8Research in Translation|Research in Translation
7Columns|Column
4Interviews|Interview
1PhotoEssay|Photo Essay
0Introduction|Special

```

The reason I have a number preceding the text in every option is so that, when I use this field as a sort criteria and choose the order as ascending, Views actually looks for the key text and arranges the results in that order (0 to 8 in this case).

Now, I want to achieve this same order without having to tamper with the key|value pairs like I have done. I have heard of Draggable Views, but I'm not sure that solves the issue here, since this view takes a contextual filter value and the results are always dynamic based on the filter value that is passed to it from the URL.

So is there another way to use a select list's options as a sorting criteria, but in an order that we want it to be in?

# Answer
> 1 votes
Looking for approximately the same, but I believe this isn't easily solvable. What you could do is use taxonomy instead and then sort the view by the term weight (create a relation to the taxonomy in the view and you get term weight as sort criteria).

---
Tags: views
---


# Question
Title: Way to allow instantiating derived classes
I have a class called MyService, a function to get the only instance of it custom\_get\_my\_service(), and multiple functions a,b, etc that call the instance getter, as you can see below.

All of this is packaged into my module. Suppose I give this module to another developer, he can't change the code, but he needs to override some of my class methods, and all the custom\_a, custom\_b functions have to use his derived class.

How can I modify my custom\_get\_my\_service() function, in a Drupal best practice way, to allow others to instantiate their derived class instead of my own?

```
class MyService {}

function custom_get_my_service() {
  $service = &drupal_static(__FUNCTION__, NULL);
  if (is_null($service)) {
    $service = new MyService();
  }
  return $service;
}

function custom_a() {
  $service = custom_get_my_service();
  // Do stuff
}

function custom_b() {
  $service = custom_get_my_service();
  // Do stuff
}

```

# Answer
> 0 votes
You can do it however you like, really; however PHP will let you.

Basically you need to make a decision at some point in `custom_get_my_service()` about which class you're going to use. Drupal's paradigm is hooks, so a contrived example might be:

```
function custom_get_my_service() {
  $service = &drupal_static(__FUNCTION__, NULL);
  if (is_null($service)) {
    $service_class = custom_get_service_class();
    $service = new $service_class();
  }
  return $service;
}

function custom_get_service_class() {
  // Default
  $class = 'MyService';

  $modules = module_implements('custom_service_class');
  foreach ($modules as $module) {
    $function = "{$module}_custom_service_class";
    $class = $function();
  }

  return $class;
}

```

Then another module would implement the hook:

```
function another_module_custom_service_class() {
  return 'AnotherClass';
}

```

Obviously that's a very limited example, which will only let one module override the class, has race conditions, no error checking, etc. But that's the basic idea, I'm sure you can extrapolate from there based on what your module is providing.

You could also look at a DI approach, and have modules pass in their implementations of an interface you define into your functions, which then make the necessary use of them. It kind of depends on your level of experience with OO, and your opinions on 'best practice'.

---
Tags: 7
---


# Question
Title: Using field_create_field and field_create_instance to add a checkbox to a content type
I've written the following update hook to add a field to a content type. In an ideal world I'd like that field to be a single on/off checkbox. However, the code I've written outputs three radio buttons - with options for Yes and No, as you'd expect - but one for NA, too. I don't really want my users to have an NA option. Any idea how to achieve this? I'm guessing it's either the widget or display attributes, but I don't know where to find a list of what options are available to me.

---

**Update**:

Marcel's suggestion worked just fine - it doesn't provide a checkbox, but it removes the NA option, and that's good enough for me. Adapted code is below - I've also made some changes to the rest of it that ensure the title and summary text are displayed properly in the editor UI:

```
$field = array(
  'field_name' => 'field_maxy8',
  'type' => 'list_boolean',
  'settings' => array(
    'text_processing' => 0,
  ),
  'widget' => array('type' => 'options_onoff'),
  'settings' => array(
    'allowed_values' => array(
      '0' => 'No',
      '1' => 'Yes',
    ),
  )
);

$field = field_create_field($field);

$instance = array(
  'field_name' => 'field_maxy8',
  'required' => 'true',
  'label' => 'Maxy 8',
  'description' => st('Maxy 8'),
  'entity_type' => 'node',
  'bundle' => 'article',
  'display' => array(
    'teaser' => array(
      'label' => 'hidden',
      'type' => 'hidden',
    ),
    'default' => array(
      'label' => 'hidden',
      'type' => 'hidden',
    ),
  ),
);

field_create_instance($instance);

```

In order to use this you'll need to:

1) Put it in a `<modulename>.install` file

2) Put it in a `hook_update_n` function

3) Save it, and run `UPDB` through Drush

# Answer
This is how you create a single boolean checkbox field and field instance: I have excluded checking whether the field or instance exists, for brevity.

```
field_create_field(array(
  'field_name'  => "my_bool",
  'type'        => 'list_boolean',
  'cardinality' => 1,
  'settings'    => array(
    'allowed_values' => array(
      /*
       * The docs say that this is optional, but without it,
       * the value is never saved to the datbase (tested with Drupal 7.28)
       */
      0 => '',
      1 => '',
    ),
  ),
));

field_create_instance(array(
  'field_name'  => "my_bool",
  'entity_type' => 'taxonomy_term',             // or 'node'
  'bundle'      => 'my_vocabulary_machine_name, // or 'my_content_type'
  'label'       => t('My boolean checkbox'),
  'required'    => false,                       // because not ticking a checkbox omits the value from $_POST
  'display'     => array(
    'default' => array(
      'type' => 'hidden',                       // optional. I want to hide it
    ),
  ),
  'widget'      => array(
    'type'     => 'options_onoff',              // gives you a checkbox
    'settings' => array(
      'display_label' => 1,                     // uses 'My boolean checkbox' as the label next to the actual checkbox
    ),
  ),
));

```
> 5 votes

---
Tags: entities, updating
---


# Question
Title: How Do I improve the performance of my Drupal7 Site?
For somebody who is new to Drupal, I see that there are many resources available on Drupal Caching but I am not sure which of them to use.

# Answer
These are notes from my experiences and might vary from what others experience. I predominantly use LAMP stack and have considered the same in my suggestions.

**Thumb rules for caching that I generally follow.**

1. Process Once Use Multiple Times.
2. Live with stale data when possible
3. Clear Caches infrequently and keep it very specific.
4. When possible do the changes at the lowest level in the stack. LAMP - DCCc : Linux, Apache, Mysql, PHP, Drupal Core, Contrib and custom module.

**Improve Performance of a Drupal Site (In the increasing order of complexity)**

5. Keep the core updated, contrib module and themes updated. Yes it matters.
6. Install APC on your server. (Moved to top based on suggestion from Letharion)
7. Page Caching : admin/config/development/performance Difference between Minimum cache lifetime and Expiration of cached pages
8. Block Caching https://drupal.org/project/blockcache\_alter Caching options for all the blocks.
9. Aggregate javascript and css files - Front End Improvements https://www.drupal.org/project/advagg
10. Disable Unnecessary modules. Every module adds to the amount of code that needs to be available for a page load. And it also increases the number of lookups. Wherver possible use a generic module in place of multiple module that does specific functionalities.
11. Cache Views content - Content aware caching for Views https://www.drupal.org/project/views\_content\_cache
12. Disable DB logging - Use https://drupal.org/project/syslog\_ng
13. Reduce 404 Errors - http://www.brokenlinkcheck.com/
14. Fast 404 Responses - https://drupal.org/project/fast\_404 \- Try handling at server level.
15. Client Side Validations - https://www.drupal.org/project/clientside\_validation
16. Compress Image - https://www.drupal.org/project/imageapi\_optimize
17. Lazy Loading of Images - Don’t load unnecessary images - https://www.drupal.org/project/lazyloader
18. Use Sprite Sheets - https://www.drupal.org/project/spritesheets
19. Set Minimum Cache Life Time Value to a higher number and use cache clearing modules to clear the caches for specific pages - Whenever I edit/update a node all the page caches for anonymous user are lost
20. Use Devel Module to watch queries.
21. Rewrite Views Queries / avoid Views if its a overkill.
22. XHProf - https://www.drupal.org/project/XHProf
23. FPM, HHVM.
24. DB Profiling and Tuning - https://www.drupal.org/project/dbtuner
25. **Use Boost**, don't Bootstrap DB if not required. https://drupal.org/project/boost For most of the small to medium sites Boost is good enough and you may not need Reverse Proxies or so.
26. Use CDNs - https://www.drupal.org/project/cdn Its easy to set up.
27. If your cache tables are huge use Memcached - If you can install memcached and set up RAM for it, it is not as complex as it sounds.
28. Etags - Configure Etags properly. https://developer.yahoo.com/blogs/ydnfiveblog/high-performance-sites-rule-13-configure-etags-7211.html
29. **Use Reverse Proxy Server** \- Varnish(at-least for assets). Helps a lot if most of your users are anonymous.
30. Compressed transfer - Enable gzip compression
31. Keep Alive - Use Persistent Connections where possible.
32. Progressive JPEGS -
33. CACHING IN CODE - Eaton’s blog is awesome. http://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7
34. Implement Cache Warming - https://www.drupal.org/project/cache\_warmer \- Cache Warm the pages before the end user hits them.
35. Master Slave DB Config - https://www.drupal.org/project/autoslave makes it easier for you to set up one.
36. Database Clusters - https://stackoverflow.com/questions/1163216/database-cluster-and-load-balancing
37. Load Balancers -http://en.wikipedia.org/wiki/Load\_balancing\_(computing)
38. Use heuristic Cache Warming - https://www.drupal.org/project/cache\_graceful
39. Authenticated User Caching - https://www.drupal.org/project/authcache
> 26 votes

# Answer
The database layer is important. I cover some parts of it and the basics in this presentation http://goo.gl/30yi39
> 5 votes

# Answer
As a companion to Gokul's answer here's the way I would think about what you want to cache in Drupal (not ordered by complexity):

Caching means speeding up repeated activities.

The big repeat actions involved in a Drupal website are:

* Calling a webpage
* Running PHP code to build a webpage
* PHP calling items from the database

**Caching an entire webpage**

The biggest caching gains are to be had from finding a way to cache an entire webpage without ever running the PHP code or calling the database.

You can do this with Varnish or Boost. When a user calls a page they return a copy of the page without ever doing a calculation.

However this won't work if parts of the page have to be different (i.e. users login and their name appears at the top).

In order to get that to work you need to look into Authcache.

**PHP Caching**

You can cache PHP with APC, or if you have version 5.5 or greater then a different cache is built in.

This is done server side and means chunks of your PHP code will be remembered. You're caching PHP for Drupal but you're not technically interacting with Drupal.

**Database Caching**

Calls to grab information from the database are expensive.

The commonest database caching mechanism is memcache.

This caches database objects in RAM, so instead of making a call to a database object on the harddrive, you just pull it from the RAM which is a lot faster.
> 3 votes

---
Tags: 7, caching, performance
---


title: Problem creating path alias in code

text:
# Question
Title: Problem creating path alias in code
I am creating a node and a path alias roughly as follows:

```
<?php
$node = (object) array( 'type' => 'article');
node_object_prepare($node);
$node_wrapper = entity_metadata_wrapper('node', $node);
// ... some more fields get set here...
$node_wrapper->title->set( 'Foo' );
$node_wrapper->save();

// Set the path
$path = array(
  'source' => "node/$node->nid",
  'alias' => "foo/bar",
);
path_save($path);

```

The node is created OK, and the path seems to be created OK, too. I can type `foo/bar` in as the path and I see the new blank page. **However** when I edit that page, the Path Alias is blank?!

I have pathauto installed - could this be something to do with it? Nb. when I edit the page the "Generate path automatically" pathauto checkbox is *not* checked (which is what I'd expect).

# Answer
> 2 votes
Inspecting the differences in the `node` table, I noticed that the node created by my code had an empty `language` field. Updating this to `"und"` fixed the node alias.

This makes sense, because path\_save() defaults to `LANGUAGE_NONE` (i.e. `"und"`).

I had assumed that node\_prepare would do likewise, but it does not.

So the solution is to set `$node->language = LANGUAGE_NONE;` at the point of creation.

Also, this is an easier way to create the alias...

```
$node->path = array('alias' => $path, 'pathauto' => FALSE);

```

---
Tags: 7, path-aliases
---


# Question
Title: Can drush make fetch dependencies for a newly added module, without using it to build the whole site?
If a module includes a drush make file to fetch its dependencies, is it possible to run that make file by itself somehow against a pre-existing site's codebase? In other words, I didn't use `drush make` to build the site, but I'd like to use it just to fetch the new module's dependencies. Is that possible?

# Answer
> 4 votes
Yes, it is possible. Just run the makefile on the current codebase, and specify `--no-core` option from the drupal root:

```
$ drush make --no-core sites/all/modules/mailchimp/mailchimp.make.example

```

Here's the log of a test I did:

```
$ drush dl drupal
$ cd drupal-7.28/
$ drush dl mailchimp
  Project mailchimp (7.x-3.1) downloaded to /tmp/drupal-7.28/sites/all/modules/mailchimp.

$ drush make --no-core sites/all/modules/mailchimp/mailchimp.make.example
  Make new site in the current directory? (y/n): y
  Beginning to build sites/all/modules/mailchimp/mailchimp.make.example.
  libraries-7.x-2.2 downloaded.
  mailchimp downloaded from https://bitbucket.org/mailchimp/mailchimp-api-php/get/2.0.4.zip.

$ ls sites/all/libraries/
  mailchimp
$ ls sites/all/modules/
  libraries  mailchimp  README.txt

```

If any of the projects/libraries declared in the makefile already exists, it will be overwritten.

---
Tags: drush
---


# Question
Title: Standards/recommendations for Drush make files included in contrib modules
What are the standards/recommendations for Drush make files that are included in contrib modules? Specifically, should these make files be included by default (module\_name.make) or not (module\_name.make.example)?

If they should be included, what is the recommended/supported method of overriding/ignoring them? Is there any documentation to point module maintainers to when discussing this in their issue queues?

EDIT: Found this post by jhedstrom from June 2012 recommending naming make files with '.example' suffix. Is this still the recommendation, or have things changed since then? https://drupal.org/comment/6160018#comment-6160018

# Answer
> 1 votes
@jhedstrom recomendation is valid. Modules should not include a `module_name.make` file, to prevent drush make running them on recursion. Adding `module_name.make.example` is desired, and is helpful to build makefiles, specially when the module has several dependencies, including libraries.

OTOH profiles do include makefiles. It is a common practice for a different use case, where discovery and recursion is desired.

# Answer
> 0 votes
Adding an example .make file is the recommended practice, that way when drush make builds the site, the modules all end up in the same directory. For example OpenAtrium puts its contrib modules in `/profiles/openatrium/modules/contrib`, not `/sites/all/modules`. This prevents module conflicts and makes site maintenance easier.

---
Tags: drush
---


title: How to alter and debug views queries?

text:
# Question
Title: How to alter and debug views queries?
I'm trying to find the hook/module which can modify a views query.

The view is from Workbench module which is displaying the draft's of the actual user.

If I *Disable SQL rewriting* in the *Query settings* the display is ok, so something is interfering.

What would be the method to debug?

# Answer
> 1 votes
We can alter a views query using hook\_views\_query\_alter. Try to search in your codebase for this string **views\_query\_alter**, you should get a function in one of the custom module which is implementing hook\_views\_query\_alter.

If it doesn't help, try to enable **query log using devel module**, so you will know what query are being executed for that page. Views also gives the **sql query that a particular display** will run. See if these two sql queries don't match. You can **see the diff** and then try to figure out which module might be adding the additional conditions to that query.

---
Tags: views, hooks, debugging
---