title: Custom Entity Administration Pages

text:
# Question
Title: Custom Entity Administration Pages
I am trying to create a custom entity with user manageable bundles with very little luck.

I have been using a couple of other modules that do this very successfully like field collection and the latest version of the invite module.

Very simply, there is an event entity which has multiple types. The user should be able to create and manage these multiple types - similar to how users can create and manage multiple field collections.

My entity info is as follows:

```
function enf_entity_info() {
  $return = array(
    'enf_event' => array(
      'label' => t('ENF Event'),
      'entity class' => 'ENFEvent',  // defined - simple
      'controller class' => 'ENFEventController', // defined - simple
      'base table' => 'enf_event', // defined
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'event_id',
        'bundle' => 'event_type',
      ),
      'bundle keys' => array(
        'bundle' => 'event_type',
      ),
      'view modes' => array(      // I don't expect to need these
        'full' => array(
          'label' => t('Default'),
          'custom settings' => FALSE,
        ),
      ),
      'bundles' => array(),
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
      'module' => 'enf',
      'access callback' => 'enf_event_access',  // simply returns TRUE
      'metadata controller class' => 'EntityDefaultMetadataController',
    ),
  );

  $return['enf_event_type'] = array(
    'label' => t('ENF Event Type'),
    'entity class' => 'ENFEventType', // defined - simple
    'controller class' => 'ENFEventTypeController', // defined - simple
    'base table' => 'enf_event_type', // defined
    'fieldable' => FALSE,
    'bundle of' => 'enf_event',
    'exportable' => TRUE,
    'entity keys' => array(
      'id' => 'type_id',
      'name' => 'event_type',
      'label' => 'label',
    ),
    'module' => 'enf',
    // Enable the entity API's admin UI.
    'admin ui' => array(
      'path' => 'admin/structure/enf-event-types',
      'file' => 'includes/enf.admin.inc', // includes the form functions
      //'controller class' => 'ENFEventTypeUIController',
    ),
    'access callback' => 'enf_event_type_access',
  );
  return $return;
}

```

the bundles are then added in in the alter

```
/**
 * Implements hook_entity_info_alter().
 */
function enf_entity_info_alter(&$entity_info) {
  foreach (enf_get_types() as $type => $info) {
    $entity_info['enf_event']['bundles'][$type] = array(
      'label' => $info->label,
      'admin' => array(
        'path' => 'admin/structure/enf-event-types/manage/%event_type',
        'real path' => 'admin/structure/enf-event-types/manage/' . $type,
        'bundle argument' => 5,
      ),
    );
  }
}

```

The admin page seems to work - however, there are manage fields and manage display menu options on the page itself. These go to a

```
/admin/structure/enf-event-types/manage/%25event_type/fields

```

and /admin/structure/enf-event-types/manage/%25event\_type/display

and there are notifications displayed and saving and such errors out.

It is possible to add types - the form is displayed and creates a new type on submit.

However, when clicking through the fields or display links, a 404 comes back

```
/admin/structure/enf-event-types/manage/test/fields
/admin/structure/enf-event-types/manage/test/display

```

It seems like it should really be very simple to do this but something is missing.

Any assistance greatly appreciated...

# Answer
> 1 votes
A little bit late, however, hope this will be of use.

When defining an admin path for each bundle, `path` provides the path that should be used in `hook_menu` for the Field UI´s pages. For resolving the '%event\_type' placeholder in admin paths, you need to provide a loader function that, in your case, should be 'event\_type\_load' and it must return a single type object.

```
/**
 * Event type loader function.
 *
 * param $type string
 *  The name of the event type as it appears in the admin Path placeholder
 *  of a bundle. By convention, all Drupal paths use dashes instead of underscores.
 *
 * return $type stdClass object
 *
 */
function event_type_load($type) {
        $types = enf_get_types();
        // We need to replace dashes that may appear in $type with underscores.
        // By convention, bundle names needs to use underscores, not dashes.
        $type = str_replace('-', '_', $type);
        return isset($types[$type]) ? $types[$type] : FALSE;
}

```

You may need to modify as well the line that reads,

```
'real path' => 'admin/structure/enf-event-types/manage/' . $type,

```

and replace it with the following one:

```
'real path' => 'admin/structure/enf-event-types/manage/' . str_replace('_', '-', $type),

```

NOTE: to be consistent with the name of the module that defines your custom entity, you may want to rename the admin path placeholder '%event\_type' to be '%enf\_event\_type', and thus the loader function would be 'enf\_event\_type\_load'.

---
Tags: 7, entities
---


# Question
Title: How to theme output of node_view_multiple()?
If I want to theme the output of `node_view_multiple()` I can just set the `#theme` element of the renderable array generated by the `node_view_multiple()` function.

But, what if I'm not the one that called the `node_view_multiple()`? Is there a tpl file for that?

A good example would be a taxonomy term page. The `taxonomy-term.tpl.php` allows to theme only the term itself, not the actual list of nodes. So how can I theme that list of nodes?

Note that I don't want to theme individual nodes (that's not the scope of the question). I want to theme the list of nodes.

# Answer
> 1 votes
The return from `node_view_multiple` is supposed to be a dumb collection of node render arrays, it's not meant to be themeable in and of itself (at least not on a generic level, obviously case-by-case you can do it). The function sepecifically *doesn't* get involved with the theming, as that should be up to the caller to determine. So using `#theme` or `#theme_wrappers` on the outer array is the correct thing to do.

There isn't anything you can do to target other modules' use of `node_view_multiple()` in this respect, short of:

1. Patching the module code
2. Patching `node_view_multiple` itself so it has a default theme function, which you can then hook into.
3. Use a broader attack like `hook_page_alter()` to make specific changes to specific arrays when it makes sense to.

---
Tags: 7, theming
---


# Question
Title: How to change path of taxonomy facet search
I am using facet search on my site. The search paths for taxonomy term facets are of the pattern "search/term-name", but I would like them to be of the pattern "search/term-tid".

Is this possible? How can I change this?

# Answer
There is a version for Drupal 6 here: Taxonomy menu with custom path for taxonomy terms

However, it uses `hook_term_path`, which in Drupal 7 has been replaced by `hook_entity_info_alter`.

Too see note of how to convert this from Drupal 6 to Drupal 7, see guidelines on Drupal.org about Converting 6.x modules to 7.x
> 0 votes

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


# Question
Title: Views - How to suppress ajax errors without leaving a log entry in browser
I have a views page that is continually updated using views\_autorefresh. My setup works fine except for the occasional error message:

AJAX Request terminated abnormally

This only happens if the user tries to navigate away from the page during an update. Is there a way to suppress this message? Because I know that this message will happen (repeatedly) I do not want for there to be a log entry of it.

# Answer
This problem is solved by the Prevent JS Alerts module
> 0 votes

---
Tags: 7, views, ajax
---


# Question
Title: Features - Is there a way to push changes back into the database
I have a fairly good understanding of the way that features works:

* Make changes to your test site.
* Create a feature which contains the changes.
* Copy the new module (which was created by features) to live.
* activate the new module.
* Verify that the changes now exist on the live site.

This works great, but is there a way to take the changes that are contained in the new feature module and move them into the live database? My goal is to reduce the number of active modules I have on my live site.

# Answer
Once the module generated by Features has been activated and the status on the overview page reads "Default" **the changes are in the database**. "Default" means that the database configuration matches the configuration defined in the module. (The status "overridden" indicates that the module generated by Features does **not** match the database configuration.

I think what you want to ask is, "How can I disable a Feature-generated module without losing the configuration that it provided?", which has been asked on this site before.
> 1 votes

---
Tags: 7, database, features
---


# Question
Title: REST Services documentation for end client
After creating a REST services using Services module there is always somebody who develops a client for you endpoint. And this developer must know which services we have, which parameters to pass, which method to use etc.

Is there any automatically generated documentation for Services that are created? (E.g. something like to WSDL document for SOAP.)

# Answer
> 2 votes
There is indeed:

Services Documentation API

> The Services Documentation module generates API documentation for your site’s Services resources. Most of the documentation is generated automatically, using the resource information contained provided by Services. However, this module provides you with the ability to easily extend that documentation.

---
Tags: 7, services
---


# Question
Title: What advantages does Features offer in deploying changes
What advantages does using features to manage deploying changes (versus keeping code updated and data fresh)?

**The Features way (near as I can discern):**

Features takes configuration (which is ‘content’) re-envisions it as code and builds a module for it, and then pushes it up where it continues to live as an object that has to be maintained as code forever.

The next time the developers update their code, (where the best would include updating their dev database to a fresher copy of production), they get these configuration changes that they too have to manage in perpetuity.

**The not really doing anything special way**

The original developer updates the configuration on production, (after ironing out these changes in development), then we are done worrying about that configuration change, forever.

The next time the developers update their code, (where the best would include updating their dev database), the configuration changes are included. No one ever has to worry about overrides and reverting ever.

**Obvious Caveat:**

If the original developer changes 103 individual settings, remembering and setting them all would be nightmarish. In this case I would understand using a configuration packager, which is more or less how Features is used, to set the production system to match. But then what? I don’t understand keeping that project alive after you have updated the settings on prod to match what you did in development. Features as a fire and forget config missile, I get... as code... I don't get maintaining it after the fact.

===================================

I started out this post open to Features, after it was regaled by some incredibly trustworthy Drupal gurus. I had a bad feeling about it, but hoped it would wane. After writing this, again find myself frustratingly opposed to something everyone else seems to think is the best thing since sliced servers.

The features ideals I can’t wrap my brain around:

I have always approached Drupal with a philosophy less eloquently described by one aforementioned gurus as: “Content comes down, code goes up.”

In Drupal 7, configurations for the system and modules is stored in the database. The dotted line I've drawn in my perception demarcates content from code is right on that line; code is stored in files managed in Git, content is entered into the UI and stored in the DB.

Using Features for Structure: On my gut feeling about exports and features, another Guru said: “It’s going to end up in a file one way or another”.

I didn't argue at the time because I wasn't seeing his perspective and wasn't comfortable calling him on it (guru vs. marginally experienced flounder).

I've never thought about it because I wasn't using the paradigm he was thinking about (developer). I had always just imported the structure, because my brain is always in a different paradigm (site builder) when I’m working with structure.

I haven’t ever done it the way he described. It is actually clever, and I can see using that method in certain cases. I realized later when my brain was back in developer mode that I have done something similar this, in a different sort of way; I use Form Builder to build rough forms quickly, then drop them into my code, I don’t export them, because Form Builder gives you access to the code for their construction as you build them out.

This makes me hesitant to say “Features is teh Ahhsumz”

So what am I missing?

# Answer
> 2 votes
You seem to have mentioned the use-case of Features only as a configuration packer, probably with strongarm, or with structure - where you would not use the code once it is run and has made its changes in the database.

But one of the important uses of Features is ctools exportables, such as Views, rules, etc... Here, the settings are much more complex than '103 configuration options' and if you are dealing with multiple developers, a staging site and then production, you can't imagine doing all of this manually on all different servers and instances.

# Answer
> 2 votes
As a Drupal developer, I find that there is a virtual ocean of tricks and tips out there that don't make much sense at first, but then grow on you as you use them. Features is one of them. Here are a few points to keep in mind (you probably know most of this):

* Using Development and Test servers are an absolute must.
* Drupal updates are often complicated and require plenty of trial and error (and advice.)
* Manual Live updates are bad. You won't get it exactly right the first time every time.
* Sometimes manual Live updates are unavoidable, be sure to practice a few times on test.
* Otherwise, have an established method for moving updates from production to test to live.
* Almost all of your (back-end) site updates will change the database in some way.
* Content does indeed move down and changes move up.
* If you don't separate database updates from content, content will (eventually) be lost.
* To minimize loss, take the site off-line and be as quick as possible or...
* If you can separate updates from content, you will not need to download/manage content.
* Features automatically separates database updates from content.
* automatic processes are faster, more accurate and more reliable in the long run.
* It is still important to move content to test to insure that your changes won't break things.
* Features improves to process of adding, storing, sharing and reverting updates.
* If there happens to be a problem with your update, reverting a feature is FAST.
* There are cases were you can publish your update to additional sites using features.
* features is a form of encapsulation and encapsulation is good.

---
Tags: 7, features, deployment
---


# Question
Title: Anyway to clone the shipping services at: admin/commerce/config/shipping
Is there any way to clone Flat Rates shipping services at: 'admin/commerce/config/shipping' ?

The Flat Rates are generated by these modules: commerce\_shipping and commerce\_flat\_rate

I need this because I need to create 50 shipping services (for the 50 Spain provinces/states).

# Answer
> 2 votes
I would do this programmatically. As you will need this to be done only once, you can just run this from `devel/php` or in a custom module.

Zones are just there as an example; prepare an array with two letter zone codes / some other identifier and run the same code:

```
$zones = range(2, 10);
foreach ($zones as $zone) {
  $shipping_service = array(
    'name'            => 'flat_rate_for_zone_' . $zone,
    'title'           => 'Title for zone ' . $zone,
    'display_title'   => 'Display title for zone ' . $zone,
    'description'     => 'Description for zone ' . $zone,
    'rules_component' => TRUE,
    'data'            => array(),
    'is_new'          => TRUE,
    'amount'          => 900,
    'currency_code'   => commerce_default_currency(),
  );
  commerce_flat_rate_service_save($shipping_service);
}

```

Hope this helps.

---
Tags: commerce
---


# Question
Title: field_group: the save button is now in the wrong place
I am using the Field Group module to group my content input fields in my add and edit node pages. After adding a few groups, I noticed that the Save / Preview buttons moved from the bottom of the page, to a position between my un-grouped content and the groups that I have just created. How do I move the buttons back to the bottom of the page?

# Answer
You can change the weight of the Save / preview buttons, and place them at the bottom with form alter.

Weight is used to sort the list of form elements before being output; lower numbers appear before higher numbers.

```
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  // Only change actions container (submit, preview, cancel buttons) weight
  // on node edit forms.
  if (!empty($form['#node_edit_form']) && $form['#node_edit_form'] == TRUE) {
    $form['actions']['#weight'] = 100;
  }
}

```
> 2 votes

---
Tags: 7, entities
---


# Question
Title: Drush up error - unable to untar - Destination already exsists
I have verified that the directory does not exist before attempting an update. The error I get is as follows.

```
Do you really want to continue? (y/n): y
Executing: svn info /home/sites/lg/public_html/drupal-7.26
Executing: bzr root /home/sites/lg/public_html/drupal-7.26
Executing: wget -q --timeout=30 -O /tmp/download_filexptX5V http://ftp.drupal.org /files/projects/drupal-7.26.tar.gz
Downloading drupal-7.26.tar.gz was successful.                                                                                [notice]
Md5 checksum of drupal-7.26.tar.gz verified.                                                                                [notice]
Mime type for /home/sites/lg/public_html/drupal-7.26.tar.gz is application/x-gzip                                                                 [notice]
Executing: tar -C /home/sites/lg/public_html -xzf drupal-7.26.tar.gz
Unable to untar /home/sites/lg/public_html/drupal-7.26.tar.gz.                                                                                [error]
Destination directory /home/sites/lg/public_html/drupal-7.26 already exists.                                                                   [error]
Project drupal was updated successfully. Installed version is now 7.26.

```

I am on a vps using CentOS 6.5 Drush version 5.9 Currently installed version of Drupal is 7.23

# Answer
> 0 votes
There were other problems that accompanied this one. They were:

When trying to untar files on the server I got the following message.

```
tar:: Cannot open: Disk quota exceeded

```

Cpanel started to give these error messages at different file locations in the update script and was not able to complete a full update.

```
 E Failed to download /usr/...
 Retrying download (attempt 2/5)
 E Failed to download /usr/...
 Retrying download (attempt 3/5)
 E Failed to download /usr/...
 Retrying download (attempt 4/5)
 E Failed to download /usr/...
 Retrying download (attempt 5/5)
 E Failed to download /usr/...
 The Administrator will be notified to review this output when this script completes
 E Detected events which require user notification during updatenow. Will send iContact the log

```

I also received the following error from Cpanel updatenow

```
Running `/usr/local/cpanel/scripts/updatenow --upcp --log=/var/cpanel/updatelogs/update.(...).log`
failed, exited with code 12 (signal = 0)

```

The problem was due to inode limits being reached on the vps account. Upon further investigation I realized that every time I used drush to update a site it created a new backup of each site. Multiply that times several sites updating several times and you have a ton of files.

The disk quota error is misleading because I was nowhere close to the disk space limit provided by the host. However inodes are basically a file count limit, and with drupal being basically a bunch of small files ... you know the rest.

In short:

Periodically clean temporary files, logs and backups that are safe to delete.

Use the linux df command to check limits

You may also choose to ask your ISP to increase your inode limit.

# Answer
> 0 votes
I've had a similar problem in the past. It looks like there's already a /home/sites/lg/public\_html/drupal-7.26 (at least based on your post). Make sure you have read / write access to it. Better yet, run drush as root or under sudo.

---
Tags: drush, updating
---


# Question
Title: Perform bulk operations on a custom database table
I have a custom database table. I implemented `hook_views_data()` to make it available with views.

```
/**
 * Implements hook_views_data().
 */
function uploader_views_data() {
  $data = array(
  'texts' => array(
        'table' => array(),
      ),
  );

  $data['texts']['table'] = array(
    'group' => t('Uploaded Texts'),
    'handler' => 'views_join',
  );

  $data['texts']['table']['base'] = array(
    'field' => 'txt_id',
    'title' => t('Texts'),
    'help' => t("Text ცხრილში ინახება ინფორმაცია ტექსტების შესახებ. მაგ: ავტორი, სათაური და ა.შ"),
    'weight' => -10,
  );

  $data['texts']['txt_id'] = array(
    'title' => t('txt id'),
    'help' => t('ცხრილის უნიკალური ID-ი.'), // The help that appears on the UI,
    // Information for displaying the nid
    'field' => array(
      'handler' => 'views_handler_field_node',
      'click sortable' => TRUE,
    ),
    // Information for accepting a nid as an argument
    'argument' => array(
      'handler' => 'views_handler_argument_node_nid',
      'name field' => 'title', // the field to display in the summary.
      'numeric' => TRUE,
      'validate type' => 'nid',
    ),
    // Information for accepting a nid as a filter
    'filter' => array(
      'handler' => 'views_handler_filter_numeric',
    ),
    // Information for sorting on a nid.
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
  );

  $data['texts']['teqstis_saxelcodeba'] = array(
    'title' => t('ტექსტის სახელწოდება'),
    'help' => t('ნაბეჭდი ტექსტის სახელწოდება.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  $data['texts']['xelnaceris_saxelcodeba'] = array(
    'title' => t('ხელნაწერის სახელწოდება'),
    'help' => t('ხელნაწერის სახელწოდება.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  $data['texts']['type'] = array(
    'title' => t('Type'),
    'help' => t('ტექსტის ტიპი.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  return $data;
}

```

I want to create a custom bulk operation on this table.

```
function uploader_action_info() {
  return array(
    'uploader_myaction' => array(
      'type' => 'entity',
      'label' => t('Do my action'),
      'configurable' => FALSE,
      'pass rows' => TRUE, //this will ensure that the entire views row is passed as part of the context in your action callback.
    ),
  );
}

```

The action callback is the following one.

```
function uploader_myaction($cmt, $context = array()) {
   drupal_set_message(t('uploader_myaction was called'));
}

```

When I try to add a field in the view fields, there is no *Bulk operations: Content* option.

# Answer
> 1 votes
I've had a similar problem. It's not ideal behaviour, but when I created the field, save it (selecting no action, or an action at random), then edit it (unselecting the random action, if I did that), then my custom action shows up.

# Answer
> 0 votes
You have to declare the hook\_entity\_info() because:

> VBO only supports entity (base or revision) table Implement hook\_entity\_info() and make your table an entity. Use EntityAPIController so that you don't need to write other boilerplate functions.

Credit: bojanz

Issue: https://drupal.org/node/1282486

---
Tags: 7, views
---


# Question
Title: Convert former embedded PHP code into a custom block module?
Had a Drupal site that used the php filter module. After realizing the security risk I started the process of fixing things up.

Currently the last piece of code is a php snippet I embedded into a view to display the input fields of a content type (called post).

```
<?php
  module_load_include('inc', 'node', 'node.pages');
  $node_form = node_add('post');
  print drupal_render($node_form);
  $form['buttons']['submit']['#value'] = t('Save and add new');
?>

```

This is a view block embedded within a panel. Not 100% sure how to take this and make it a custom module that I suppose cloud be a block for me to embed on the panel page.

**Update:** Attempted to make the module using `hook_block_configure()` but when enabled it is not showing up as a block option for me to embed.

```
<?php

/**
 * Implements hook_block_configure().
 */

function hook_block_configure($delta = '') {

  module_load_include('inc', 'node', 'node.pages');
  $node_form = node_add('post');
  print drupal_render($node_form);
  $form['buttons']['submit']['#value'] = t('Save and add new');

}

```

Is the correct command being used?

# Answer
I don't really think embedding a node form in a node view is good in terms of performance because the entire node form needs to be rebuilt, and it can interferer caching mechanisms as well. Probably a ctools madal form with Ajax will do the job better.

You can define blocks in your site using a custom module. Panels will pick them up without any further integration.

```
function MYMODULE_block_info() {
  $blocks['MYMODULE_post_node_form'] = array(
    'info' => t('Add new'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function MYMODULE_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'MYMODULE_post_node_form':
      module_load_include('inc', 'node', 'node.pages');
      $node_form = node_add('post');
      $node_form['buttons']['submit']['#value'] = t('Save and add new');
      $block['content'] = $node_form; // No need to render() here. Will happen automatically.
      break;
  }

  return $block;
}

```

I'm assuming you know how to create a basic module with an .info file, change "MYMODULE" to the module name of your choice and how to install them. If everything went OK, you will see the "Add new" block in admin/structure/blocks page and in "Add content" form in panels.
> 0 votes

---
Tags: 7, blocks
---


# Question
Title: Adding an OR condition to an existing query
I want to be able to search additional user fields instead of just the standard username. For instance, I would like users to be able to search an attached field with the users' Real Name. The user search query can be found in user\_search\_execute(). I figured I would use hook\_query\_alter() to alter the database query generated by this function.

The problem I am running into is that if I add anything like this:

```
$arguments = $query->getArguments();
$query->condition('n.field_name_value',$arguments[':db_condition_placeholder_0'], 'LIKE');
$query->leftJoin('field_data_field_name', 'n', 'users.uid = n.entity_id');

```

Then drupal adds a "AND" to the list of conditions (instead of an OR).

I have even tried adding something like this:

```
$arguments = $query->getArguments();
$query->condition(db_or()->
  condition('n.field_name_value',$arguments[':db_condition_placeholder_0'], 'LIKE'));
$query->leftJoin('field_data_field_name', 'n', 'users.uid = n.entity_id');

```

However, this produces the same results.

thanks!

# Answer
> 8 votes
Adding new conditions to the query won't overwrite the existing ones, you need to reset the existing array of conditions, build up a new one and add it to the query:

```
// Get the query args and then the search term
$args = $query->getArguments();
$search = array_shift($args);

// Get a reference to the existing query conditions.
$conditions =& $query->conditions();

// Reset the condition array. It needs a default #conjunction for which AND is fine
$conditions = array('#conjunction' => 'AND');

// Build up your condition
$condition = db_or()
  ->condition('users.name', $search, 'LIKE')
  ->condition('n.field_name_value', $search, 'LIKE');

// Add the new OR condition to the query
$query->condition($condition);

// Join the relevant table
$query->leftJoin('field_data_field_name', 'n', 'users.uid = n.entity_id');

```

I've just tested that to work on a local installation.

There is a slight caveat...for users with the 'administer users' permission the default is to also search through users' email addresses. You can cater for this by adding the following lines immediately before `$query->condition($condition);`:

```
if (user_access('administer users')) {
  $condition->condition('mail', $search, 'LIKE');
}

```

It might also be wise to test the `bundle` and `entity_type` columns in the joined field table in case you ever attach the same field to another entity. This way you won't get any false results:

```
$join = "users.uid = n.entity_id AND n.entity_type = 'user' AND n.bundle = 'user'";
$query->leftJoin('field_data_field_name', 'n', $join);

```

**EDIT**

As per Berdir's comment, to maintain as much compatibility as possible with other modules that might also alter this query, you probably want to loop through the conditions, find the one(s) that you need to change and do so on an individual basis.

The above example is pretty rudimentary and works on a 'vanilla' Drupal install, hopefully it'll get you pointed in the right direction.

# Answer
> 2 votes
The db\_or() method should provide what you need. Here's an example, where we get all "blog" nodes that are either authored by uid=1 or are published:

```
$query = db_select('node', 'n');
$query->fields('n', array('nid'))
  ->condition('n.type', 'blog')
  ->condition(db_or()->condition('n.uid', 1)->condition('n.status', 1));
$result = $query->execute();

```

Basically I think you just need to chain your multiple conditions along within the db\_or() method.

Here is some additional reading on the topic:

Edit: Take a look at the conditions() method to retrieve the list of conditions (by reference) and manipulate them - possibly removing them completely and adding them to your db\_or() method.

# Answer
> 0 votes
Instead of manually rebuilding the existing conditions as in the answer from @Clive , you can do this automatically.

```
  // Get a reference to the existing query conditions.
  $conditions =& $query->conditions();

  // Build a new AND condition from the existing conditions.
  $and = db_and();
  foreach ($conditions as $key => $condition) {
    // Skip the '#conjunction' special key.
    if (is_numeric($key)) {
      $and->condition($condition['field'], $condition['value'], $condition['operator']);
    }
  }

  // Reset the conditions.
  // It needs a default #conjunction that will end up being ignored.
  $conditions = array('#conjunction' => 'OR');

  // Create a new condition from the rebuilt conditions OR our new condition.
  $or = db_or();
  $or->condition('foo.my_field', $bar);
  $or->condition($and);

  // Add our new condition.
  $query->condition($or);

```

---
Tags: 7, database
---


# Question
Title: How to sum value of a field of all entries in a View?
## I have a view that displays nodes. These nodes have a field and I need to sum all values of this field for all entries the view is "displaying"(not only the currently visible entries/current page but all entries that match the current Views filter).

So all I want is to add this information into the Views template file. So I have the view object available. I was trying to get rid of the pager so I could get all results but without any success. I was able to re-run the query and everything I needed beside excluding the pager. Any idea how to do this? I tried to unset the pager, change it to another module('none'), manually set offset, limit and such but still no success.

# Answer
Though I have never had this requirement but your question look interesting & I did some googling.

I found two related modules. I think you should try them & see what they offer.

*Note :- This is not an exact answer but helpful for these kind of situations :)*
> 1 votes

---
Tags: 7, views
---


# Question
Title: A module that allows user to create content anonymously, then if they register, assigns the content to them
I recall a module I came across that was in dev a while back that basically allowed users to create nodes as an anonymous user. Then if they registered on the site, it assigned authorship of these nodes to that user account. Similar to how Drupal Answers works. It helps to lower the threshold for someone to get involved in a site. I just cannot recall the name.

Does anyone know?

# Answer
> 4 votes
You should use Create and Register module.

> This module creates a "lazy registration" which means that the user creates the content first and after this logs in or registers to the site.

# Answer
> 1 votes
In addition to Create and Register (already mentioned by hosszu.kalman), Lazy registration is also possible with Anonymous Publishing.

Disclosure: I am one of the maintainers of Anonymous Publishing.

# Answer
> 0 votes
You will need some module custom programing or using Rules module.

1. Create a custom field on the content type and use Field Permissions.
2. After each content it is created by anonymous user, add to this field special session value.
3. After the user registers assign the content identified with the session value to the user.

---
Tags: 7
---


# Question
Title: Is it necessary to cache data generated by menu_tree_all_data and menu_tree_output called in preprocess_page
In hook\_preprocess\_page in my template.php I'm using this code:

```
// Get the entire main menu tree
$main_menu_tree = menu_tree_all_data('main-menu');
// Add the rendered output to the $mobile_menu variable
$mobile_menu = menu_tree_output($main_menu_tree);

```

To generate the entire menu tree of main menu

Thinking that preprocess\_page is executed on every page (please confirm this if it's true) I cached the above code in this way:

```
$cid = 'ctm_mobile_menu:' . $vars['language']->language;
$mobile_menu = &drupal_static(__FUNCTION__);
if (!isset($mobile_menu)) {
  if ($cache = cache_get($cid)) {
    $mobile_menu = $cache->data;
  }
  else {
    // Get the entire main menu tree
    $main_menu_tree = menu_tree_all_data('main-menu');
    // Add the rendered output to the $mobile_menu variable
    $mobile_menu = menu_tree_output($main_menu_tree);
    cache_set($cid, $mobile_menu, 'cache');
  }
}

```

But my doubt now is: is caching effectively necessary here? or menu\_tree\_all\_data and menu\_tree\_output already does caching by itself?

My concern is that I'm caching already cached data and this can generate bad loops.. I don't know please help me

# Answer
> 3 votes
No need to cache menu\_tree\_all\_data() as it is already cached; which leaves menu\_tree\_output(). This function looks fairly light; but it really depends on how many items are in $main\_menu\_tree. Note that it's not 100% safe to cache menu\_tree\_output() the way you're currently using it as it uses menu\_get\_item(). If you were to use the `tab_root_href` key as part of the cid then that would probably work. If this code only gets called once (my guess as it's in hook\_preprocess\_page()) then the static cache will not help. The important questions are how fast is your cache backend, how many items are in $main\_menu\_tree, and how often does this code get called. Knowing that will tell you what's better.

Questions like this can be answered with some help from microtime(). Example below:

```
// Get current menu item.
$router_item = menu_get_item();
$menu_name = 'main-menu';
// Get the cache ID.
$cid = 'ctm_mobile_menu:' . $vars['language']->language . ':' . $router_item['tab_root_href'] . ':' . $menu_name;

// Try core static cache.
$menu_output = &drupal_static('menu_tree', array());
if (!empty($menu_output) && !empty($menu_output[$menu_name])) {
  $mobile_menu = $menu_output[$menu_name];
}
else {
  // Try cache backend
  if ($cache = cache_get($cid) && !empty($cache->data)) {
    $mobile_menu = $cache->data;
  }
  else {
    // Get the rendered output for the $menu_name variable.
    $mobile_menu = menu_tree($menu_name);
    // Save to the cache bin.
    cache_set($cid, $mobile_menu, 'cache');
  }
}

$time_start = microtime(true);
    // Get the entire main menu tree.
    $main_menu_tree = menu_tree_all_data('main-menu');
    // Add the rendered output to the $mobile_menu variable
    $mobile_menu = menu_tree_output($main_menu_tree);
$time_end = microtime(true);
$time = round($time_end - $time_start, 4);
echo "Did non-cached in $time seconds\n";

$time_start = microtime(true);
    // Get current menu item.
    $router_item = menu_get_item();
    // Get the cache ID.
    $cid = 'ctm_mobile_menu:' . $vars['language']->language . ':' . $router_item['tab_root_href'];

    // Try cache backend
    if ($cache = cache_get($cid)) {
      $mobile_menu = $cache->data;
    }
$time_end = microtime(true);
$time = round($time_end - $time_start, 4);
echo "Did cached in $time seconds\n";

```

---
Tags: 7, caching
---


# Question
Title: Printer, email and PDF - can I use this module to print Views?
I have installed Printer, email and PDF and I am happy with the way it renders nodes. I was wondering if there was a way for it to print views too.

# Answer
> 4 votes
It should be the same idea, but instead of using nid in the URL use Views page path.

**Examples:**

* print view page: `http://www.example.com/print/view-path`
* pdf view page: `http://www.example.com/printpdf/view-path`
* email view page: `http://www.example.com/printmail/view-path`

---
Tags: 7, views, files
---


# Question
Title: Features - Should I go for big or numerous?
I have worked on a few Drupal projects that used features. I am usually perplexed by the way the way functionality is grouped. I'm guessing that most of them were created as needed and by different developers that did not want to meddle with other people's features. The outcome is usually a mess of different naming and grouping schemes. Currently, I have the opportunity to create a site from scratch, and I want to start using a good methodology for creating my feature groups. I am tending towards making a gigantic feature that contains everything, and only rebuilding one feature every time an update is needed. What is good/bad about doing this. Also, I feel more responsible while considering building several different features for each bit of functionality. However, I am not sure how granular to go, or if this is begging for conflicts later. How should I be approaching this issue?

# Answer
> 2 votes
It's all up to you. There are pros and cons to both and it depends on your use case.

Generally one would tend toward decoupled functionality with granular features instead of a giant feature. Especially if you wanted to potentially use these features on other sites.

Some information to help you out.

**One big feature Pros:**

1. It's quick and easy. If you're just using features to track database changes in code and don't care about re usability, you can just stick everything in one big feature.

**One big feature Cons:**

1. If you make one big feature, you can't re use it at all on another site unless that site is almost exactly the same.

**Decoupled features Pros:**

1. You can re use features on other sites.
2. Your features are much more manageable, even it if it takes a bit longer.
3. You can keep custom code which is directly related to the feature in the features module, so you're keeping the feature + custom code in one nice package.
4. This model fits in well with programming in general, taking big problems, breaking them down, abstracting them, using dependencies, etc. It will definitely improve your programming practising separating your code logically like this.
5. Helps the way you think about Drupal components and how they mess together.

**Decoupled features Cons:**

1. Overhead of organizing features structure. This will get easier as
time goes on and you get better.
2. Can be very hard to decide where to decouple, especially for newbies.

# Answer
> -1 votes
> How should I be approaching this issue?

1. Take a holiday
2. Come back when Drupal 8 is released
3. Use that.

;)

On a more serious note, I'd spend some more time learning core Drupal APIs and do as much as you can from an install profile using drush make and the smallest amount of contrib modules as you possibly can.

---
Tags: 7, features, updating
---


title: CSS selectors for specific pages

text:
# Question
Title: CSS selectors for specific pages
I'm working on a custom theme which involves styling specific pages and nodes. At first, to target these specific nodes, I used the selector page-node-##, where ## is the node ID. But this was on my local machine, and when I exported these nodes, I found that the node IDs would be different on both the staging and production servers. Is it better to use the section-XX, selector instead?

I was wondering if there is a recommended CSS selector for this kind of use cases, where the CSS is applied on specific pages/nodes?

# Answer
> 0 votes
A good way to do this using context:

Under conditions select `Path` and input your path

then under Reactions select `Theme HTML`. Here you can select the class you wish to add to the body.

---
Tags: theming
---


title: Show more than 10 location using Gmap

text:
# Question
Title: Show more than 10 location using Gmap
I am using Gmap + location for show my store locations on my page.

I have added near about 50 locations. However on map it is showing only 10 locations.

I want to show more than 10 locations. Can you please let me know how it is possible.\**

Thanks

# Answer
Simply - edit your pager options in view to fit your needs.
> 1 votes

# Answer
down vote accept

Fixed.

When we use Gmap then at that time we create a attachment for show all the locations on the single map. And for show all the locations in Map we need to go under attachment of created view and then set the "Use pager" display all item or any specific number of items.

If we set pager under block or page then it will show the full location in text just below the map. However, marker won't show on page. And for this we need to go with attachment section.

Thanks.
> 0 votes

---
Tags: google-maps
---


# Question
Title: How to override jquery update preprocess page
The objective is to exclude certain javascript files from some sections of the website.

I exclude javascript and css files in this way in the template.php file of the theme:

```
function phptemplate_preprocess_page(&$vars) {
  $scripts = drupal_add_js();
  //PRINT THIS ARRAY AND UNSET THE UNWANTED ARRAY
  // unset($scripts['module']['sites/default/files/js/jquery-min.js']);
  unset($scripts['module']['YOUR_PATH_TO_JS']);
  $vars['scripts'] = drupal_get_js('header', $scripts);
}

```

However it seems that jquery\_update preprocess is executed **after** template.php, so it overrides my changes:

```
function jquery_update_preprocess_page(&$variables) {
      ...
      $variables['scripts'] = drupal_get_js('header', $scripts);
}

```

The code is located in `jquery_update.module`

How would be the best approach to resolve this?

I would prefer not to hack or disable the `jquery_update.module` code if possible.

Any alternative ways to exclude javascript files that doesn't involve touching the template.php file would also fix my problem I think.

# Answer
JSAlter module for D6 should solve your problem..

Project page says

> This module will not be ported to Drupal 7, because Drupal 7 core natively includes a hook\_js\_alter(). Note that the signature and when the hook is invoked is slightly different in Drupal 7 core than it is in this module.
>
> This module adds a hook\_js\_alter() hook that other modules can use to modify the javascript that gets output to the page. The module provides no end-user functionality, but other modules can use this module as a dependency. Check out the JS Registry, JS Debug Helper, and jQuery Form Update modules for examples.
> 1 votes

---
Tags: 6, javascript, theming
---


title: Full name from ldap

text:
# Question
Title: Full name from ldap
Does any know how I can pull the full name of a user from ldap and store it in drupal when a user logs in? Currently the ldap module only store the userid.

# Answer
LDAP module does solve this problem... LDAP user module which comes with ldap module is used to relate, provision (create), and synchronize attributes of LDAP user entries and Drupal users.

Find more documentation related to LDAP user module. For configuration see Ldap User Configuration.
> 0 votes

---
Tags: authentication-authorization
---


# Question
Title: Form is not rebuilding on "Add another item" in unlimited value entity reference field
In a content type I have a field of type **'entity reference'**, **'auto complete'** widget with **unlimited values**.

The whole idea was to give user an option to add referenced node items but only once, Hence selected node items should be excluded for new added fields.

I altered the form to change `#autocomplete_path` of this field. I took care of altering path for all the added fields, But when clicking on 'Add another Item' it is not updating #autocomplete\_path as it should while rebuilding the form. My code could help answer it better way.

In my form\_alter

```
if (isset($form['field_article_test'][LANGUAGE_NONE])) {

  // Loop through all the fields to collect the default set values.
  $selected_nids = array();
  foreach ($form['field_article_test'][LANGUAGE_NONE] as $delta => $field_object) {
    if (is_numeric($delta) && !empty($form['field_article_test'][LANGUAGE_NONE][$delta]['target_id']['#default_value'])) {
      $dval = $form['field_article_test'][LANGUAGE_NONE][$delta]['target_id']['#default_value'];
      $selected_nids[] = substr($dval, (strrpos($dval, '(') + 1), -1);
    }
  }

  //dsm($selected_nids);
  if (count($selected_nids) > 0) {
    // Implode the exsting selected nids so we can pass them in autocomplete custom menu path.
    $nids_hsv = implode('-', $selected_nids);
  }
  else {

    $nids_hsv = '-';
  }
  // Loop through all added fields and get #autocomplete path updated.
  foreach ($form['field_article_test'][LANGUAGE_NONE] as $delta => $field_object) {
    if (is_numeric($delta)) {
      $form['field_article_test'][LANGUAGE_NONE][$delta]['target_id']['#autocomplete_path'] = 'sform/autocomplete/article/' . $nids_hsv;
    }
  }
}

```

In above code, I collect all selected nodes in variable `$nids_hsv` and pass to my custom auto complete menu callback so that I can exclude these nids while fetching nodes as options.

Does the form rebuilds on "Add new item" action, if so, Is this possible to update `#autocomplete_path` of the same field on rebuild of a form?

# Answer
What you are trying to achieve is Selecting Unique values from Multi Value Reference field... I do agree using default widget you may run into duplicates...

I would say consider using below one of the modules which supports entity reference using which you can avoid duplicate entries while adding..

You can choose one from variety of options mentioned in above article which suggests using of

Hope one of the above works for you :-)
> 1 votes

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


# Question
Title: How to Remove '-None-' option from Select List Field?
How can I remove the default option `-None-` in the Select list? It should not be an option in my select list.

# Answer
Edit the filed and make one of the option as default value in the select list and Make it required field.
> 7 votes

# Answer
If you make the field required None option will go away.. If want to remove none option for optional field follow below solution..

You can override the theme\_options\_none theme function. Follow below example. If you want to replace "- None -" with "SOME TEXT" everywhere, this theme implementation should do the trick:

```
function MYTHEMENAME_options_none($variables) {
  return t('SOME TEXT');
}

```

Place this function in your theme's template.php.
> 0 votes

---
Tags: 7, files
---


# Question
Title: What modules are required to make a seating chart website?
I'm currently working on a site that wants to sell theater seating by section by clicking on a map overview of the seats like the one below. What drupal 7 modules are there or recipes that can be done to create this similar functionality?

# Answer
> 1 votes
Closest things I was able to find are Wysiwyg Image Map and jQuery Map Hilight modules.

Wysiwyg Image Map is *image Map editor for tinymce provided by the Wysiwyg module.*

jQuery Map Hilight *enables the simple addition of mouseover highlighting of hotspots to HTML image maps without requiring the editing of theme files or knowledge of javascript/jquery.*

Together they should give you roughly what you need - but if I were in your situation, I would prefer to code this myself.

---
Tags: 7, commerce
---


# Question
Title: Remove drupal parameters from form submitted via POST
When I submit form created with Form API, the POST variable contains values like form\_token, form\_build and form\_id.

The problem is, I need to send submitted form values to external website. Is it possible to remove such values from POST request?

In particular, I am implementing redirection callback to commerce payment method

This callback is defined within Drupal Commerce. The callback works OK, but how can I remove the mentioned form parameters? (The third party payment service does not accept them in received POST variable).

I am not sure whether I can just unset them in hook\_form\_alter. This callback is just part of the order process and I am not sure if I can just unset it.

# Answer
You can make a call to external website using drupal\_http\_request in form submit handler.. Define extra submit handler using hook\_form\_alter and

```
$form['#submit'][] = 'YOUR_FORM_SUBMIT_HANDLER';

```

For Example

```
// Adds a submit handler/function for your form

function YOUR_FORM_SUBMIT_HANDLER($form, &$form_state) {

    $options = array();
    // Array keys are matching the key that the remote site accepts. URL encoding will be taken care later.
    $options['data'] = array(
        'firstName' => $form_state['values']['firstName'],
        'lastName' => $form_state['values']['lastName'],
        'email' => $form_state['values']['email'],
        'name' => $form_state['values']['name'],
        'phone' => $form_state['values']['phone'],
    );
    $options['data'] = http_build_query($options['data']);
    $options['method'] => 'POST';
    $url = 'https://[url path to external site]';

    // Put your additional headers here. Cookie can be set as well.
    $headers = array('Content-Type' => 'application/x-www-form-urlencoded');

    $options['headers'] => $headers;

    // Submits data to the remote server from the drupal server. User will remain in the Drupal form submission chain.
    $response = drupal_http_request($url, $options);

}

```
> 3 votes

---
Tags: 7, redirection, commerce
---


title: How to make getTree works?

text:
# Question
Title: How to make getTree works?
I want to expose a vocabulary to an external server using services module. I have followed this question How to create test\_endpoint, and checked every checkbox, and enabled the \`REST Server Module.

The only endpoint that I interest is `getTree`. But I don't know how to compose the URL. I can't find any document describing the detail (please tell me if you know).

1. Which HTTP method should I use? GET or POST? I think it should be a GET, but I got nothing
2. how to specify the vid? /taxonomy\_vocabulary/\[vid\]/getTree ? /taxonomy\_vocabulary/getTree/\[vid\] ? or /taxonomy\_vocabulary/getTree?vid=\[vid\]? any other params?

I have try some URL,

`GET [endpoint]/taxonomy_vocabulary/getTree` will response `[false]` (what is this mean?)

`POST [endpoint]/taxonomy_vocabulary/getTree` will response `401 Unauthorized`, but whatever I disable or enable the Session Authorization, I got the same response.

# Answer
you must add {"vid":"1234"} in the body of HTTP POST request and add Content-Type in the header request with "application/json"
> 2 votes

---
Tags: taxonomy-terms, services
---


# Question
Title: Why the meta-tag module add "|" after the site name?
I am building a Drupal 7 site using the Metatag module.

I know that on the settings of the module there are many tokens, and that's great.

For example, the title under 'Global -\> page title' is: "\[current-page:title\] | \[site:name\]".

Here it's great and I like that the "|" between the words.

But, When I am on my home page, I see that my site name the browser tab is

> Site Name |

In all the metatag settings, and in the site information settings I didn't found any token that looks like "\[site:name\] |".

Does someone knows why my site name is "Site Name | "?

# Answer
So by default, the module sets up all pages to use "\[current-page:title\] | \[site:name\]" and then for the front page it uses "\[site:name\] | \[site:slogan\]".

Now I am assuming you do not have a slogan set for your site, which is why it appears like "Sitename | ".

If you navigate to admin\>configuration\>site information, you will probably see the site slogan box is empty.

So you have a few options..

1. Add a slogan to your site
2. change the tokens for the front page.

to change the tokens for the front page, go the the Metatag config page and expand the "Global: Front page" field. You may need to click override to configure it to something other than default.

Click edit to edit the Global Front Page settings. Then remove the token you dont need and the seperator "|".

Hope that helps.
> 2 votes

---
Tags: 7, meta-tags
---


# Question
Title: security report there is no .htaccess file in private:// directory
I have this security report that is constantly saying:

> Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your private:// directory which contains the following lines:
>
> ```
> Deny from all
>
> #Turn off all options we don't need.
> Options None
> Options +FollowSymLinks
>
> #Set the catch-all handler to prevent scripts from being executed.
> SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
>
> <Files *>
>   #Override the handler again if we're run later in the evaluation list.
>   SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
> </Files>
>
> # If we know how to do it safely, disable the PHP engine entirely.
> <IfModule mod_php5.c>
>   php_flag engine off
> </IfModule>
>
> ```

I have this exact file in sites/all/default/files/private. what could be wrong? The private folder has the permissions set to 644.

# Answer
When you say `sites/all/default/files/private` I presume you mean `sites/default/files/private`.

I suggest deleting `sites/default/files/private/.htaccess` and setting the permissions of `sites/default/files/private` to 777 temporarily. Drupal should then be able to recreate the .htaccess file which should be exactly correct.

There are other reasons this can happen, I just can't remember off the top of my head sorry. I've had this same problem before.
> 5 votes

---
Tags: security
---


# Question
Title: Click event not always fireing in Drupal behaviors
I'm having a strange problem with a form. Sometimes I have to click the submit button twice to make it submit my form. It also seems to work if I click outside the form before I click submit. The form is built inside a module with FORM API and is submitted with an ajax request. I have some js attached to the form so I can make some client side validation before the ajax call is run. This is what my js code looks like:

```
(function ($) {

Drupal.behaviors.mymodule = {
attach: function (context ,settings) {

    // Cache the form object
    var $form = $("#mymodule-form", context);
    var $submitButton = $('input[type="submit"]', $form);

    // Use once so we dont attach submit multiple times
    // Use off to remove any existing submit handler
    $form
        .once('mymodule')
        .off('submit')
        .on('submit', function(e){
            e.preventDefault();
            var $form = $(this);

            $(function () {
                $('#mymodule-form').submit(function () {
                    if($(this).valid()) {
                        $submitButton.trigger('submitmyform');
                    }
                });
            });

        });

        $(document).ajaxComplete(function(e, xhr, settings) {
            $('#mymodule-form').resetForm();
            $('#edit-mymodule-submit').replaceWith( "<div id='mymodule-confirmation'>TACK FÖR DIN ANMÄLAN</div");

        });

         // Run validation on $form object.
        jQuery.validator.setDefaults({
            debug: false,
            success: "valid",
        });

        $('#mymodule-form').validate({
            rules: {
                mymodule_name: {
                    required: true,
                },
                mymodule_length: {
                    required: true,
                },
                mymodule_suite: {
                    required: true,
                },
                mymodule_email: {
                    required: true,
                    email: true,
                },
                mymodule_phone: {
                    required: true,
                },
            },
            messages: {
                mymodule_name: {
                    required: "lorem ipsum",
                },
                mymodule_length: {
                    required: "lorem ipsum",
                },
                mymodule_suite: {
                    required: "lorem ipsum",
                },
                mymodule_email: {
                    required: "lorem ipsum",
                    email: "lorem ipsum"
                },
                mymodule_phone: {
                    required: "lorem ipsum",
                },
            },
        });

}

};

})(jQuery);

```

This is what my code looks like for the submit button:

```
    $form['mymodule_submit'] = array(
       '#type' => 'submit',
       '#value' => t("SEND!"),
       '#ajax' => array(
           'callback' => 'mymodule_form_callback',
           'wrapper' => 'mymodule-form',
           'event' => 'submitmymodule',
        ),
     );

```

Can anyone see what's wrong with this code?

# Answer
> 2 votes
See comments below...

```
      .on('submit', function(e){ // Not correct way of using submit.
                e.preventDefault();
                var $form = $(this); // You have already defined this global variable?

                $(function () { // you dont need to check if the document is ready, thats what behaviours are for.
                    $('#mymodule-form').submit(function () { // Why are you submitting again here?
                        if($(this).valid()) {
                            $submitButton.trigger('submitmyform'); // What are you trying to trigger?
// If the form is already submit, why are you doing anything with the submit button?
                        }
                    });
                });

            });

```

Try this...

```
var $form = $("#mymodule-form", context);

$form.submit(function(e){
  e.preventDefault();
    if($(this).valid()) {
       // Do something else...
    }
});

```

**UPDATE**

You are probably binding to the form before it exists. Bind the event to the document, and pass the form selector...

```
$(document).on('submit', '#mymodule-form', function(e){
    // Do something...
});

```

---
Tags: forms, javascript
---


# Question
Title: Upgrading to 7.26 - Internal Server Error
I recently upgraded from Drupal 7.25 to 7.26 in maintenance mode. The upgrading did not have any errors.

Now when I go to the homepage I get an Internal Server Error.

I added an echo statement to verify that bootstrap.inc was executing.

I haven't been able to log any PHP errors.

This is the first part of my .htaccess file (the other part that includes rewrites isn't allowed by Stackexchange due to links)

```
    # Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Follow symbolic links in this directory.
Options +FollowSymLinks

# Multiviews creates problems with aliased URLs and is not needed for Drupal.
Options -Multiviews

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

# Force simple error message for requests for non-existent favicon.ico.
<Files favicon.ico>
  # There is no end quote below, for compatibility with Apache 1.3.
  ErrorDocument 404 "The requested file favicon.ico was not found.
</Files>

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_initialize_variables() in
# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_flag magic_quotes_gpc                 off
  php_flag magic_quotes_sybase              off
  php_flag register_globals                 off
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

```

# Answer
Always run the update script each time a module / the site is updated.

IE: site.com/update.php

It triggers the update hooks in the modules and lets them deal with any db type changes.

After that flush the Drupal caches (admin/config/development/performance/) to clear out any old references.
> 0 votes

---
Tags: 7, .htaccess, upgrading
---


# Question
Title: What hook should I use to define a class?
If I want to define a class, like the one below, for a custom module, and make it available to all the functions in my module, which hook should I use?

```
class foo {
  public $bar;
  function display_bar() {
    return $this->bar;
  }
}

```

# Answer
You wouldn't use a hook to *define* a class, that doesn't really make sense.

If you're talking about autoloading, you have two options:

1. In-built - you can add a file called, for example, foo.class.inc, in your module's root, and add the following to your module's .info file

```
files[] = foo.class.inc

```

Once you've cleared the caches, any time you request a `new foo()`, the appropriate file will automatically be included.

See Writing module .info files for more information.
2. XAutoload \- PSR-0 & PSR-4 style autoloading. If you're into OO this is a much better option in my opinion.
> 4 votes

---
Tags: hooks
---


# Question
Title: Add another item by multivalued fields directly from node (or entity) view page
I have a file field which can have unlimited number of values. I am using File Entity module. As default, if users want to add more files, they must edit the node.

I'm looking for a solution to give the user the possibility to add another file directly from the node page where the files are displayed/listed. Just like the edit/delete functions from file entity, which the user can edit or delete an existing file directly from the node display using the contextual links hovering the file.

Is there any setting, API function or any hook that I can implement to provide this feature? Any advice will be very helpful.

UPDATE:

I don't want editable fields (Edit or Editable Fields as suggested as an answer. They may provide this functionality, but their main purpose is making fields editable, which is much more than I need and I already have the editing and deleting features through the File Entity module, and I only need this functionality for file fields.

I hope I was clear enough, otherwise I could expand my question and provide some screenshots.

# Answer
> 0 votes
You can able to achieve it using Edit module which supports D7 and file Entities...

Project page says

> In-place editing for fields on any entity. Including WYSIWYG editing powered by CKEditor.
>
> In-place editing through forms will work for any field. For textual fields, "direct" editing is used, powered by contentEditable.

Here is the sample screenshot which shows inline editing of Multiple File Field.. Here is how i can able to achieve it..

1. Install like any other Drupal module.
2. Download Underscore 1.5.x and Backbone 1.x from http://underscorejs.org/ and http://backbonejs.org/, respectively and put them in sites/all/libraries, in a "underscore" and a "backbone" subdirectory, respectively. Either the development or production version will work. Edit module will automatically use the production (minified) version if it's available, because it's more efficient.
3. Grant the 'Access in-place editing' permission to relevant roles.
4. Contextual links on nodes will now have a 'Quick edit' link. Clicking it will start in-place editing of that node!

Seems like editablefields module also provides same functionality..

# Answer
> 0 votes
This would require a bunch of custom code to accomplish this from scratch, but here is one route you may want to explore.

First, assuming that you are using the Field API's default file field display, override theme\_file\_link() in your themes template.php

```
function THEME_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
      'attributes' => array(
          'type' => $file->filemime . '; length=' . $file->filesize,
      ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  return '<span class="file">' . $icon . ' ' . l($link_text, $url, $options) . '</span>';
}

```

Using Drupals Form API you could create a form that upload's and attaches a file to the current node without having to visit 'node/NID/edit'.

You may also want to consider adding some AJAX so that the page doesn't need to be constantly refreshed while managing files.

# Answer
> 0 votes
With field collections you automatically get edit, delete and add buttons on the node page.

# Answer
> 0 votes
I can't add an answer with examples sorry, don't have time. What you need to do is create a form which has an upload field. There are numerous examples for building forms in Drupal. Basically you're going to need 3 functions, one to build the form, one to validate it and one to submit it. Then you're going to to put this form into the page somehow, there are various ways of doing this also (I'd suggest putting the form into a block using a custom block or as a pseudo field using `hook_field_extra_fields`).

In your form builder function load the node object of the current node, maybe using `menu_get_item()`. Store the node id in a custom property on the form like `#nid` so that you can access it in the submit function. Build the form with your file upload field, add the `#submit` and `#validate` properties to add your custom validate and submit functions (google 'drupal fapi').

In your validate function, validate the file upload however you see fit. Then the submit function will run where you can load the node, add the file to it and save it. I'm not sure how to add the file to the node but it will involve some drupal api functions to save the file to the disc, which will return a file address, which you can add onto the multivalue field along with the other properties required for the field.

I don't think it's going to be quick but if this is what you need to do, this is how you would do it. If you have experience, this sort of thing might take an hour.

---
Tags: 7, files
---


# Question
Title: How to create a view that lists all groups and their respective contents?
I have used `organic groups` to implement the 'group' & 'group content' functionality.

I have a *group* content type. And, I have a *group content* content type.

How can I create a view that lists all groups' titles and their respective contents' titles clubbed together with that group?

For eg.

If,

*Group 1* has 2 content types: *C1 & C2*,

*Group 2* has 2 content types: *C3, C4 & C5*,

*Group 3* has 2 content types: *C6*,

*Group 4* has 2 content types: *C7 & C8*,

Then expected result is:

1. Group 1: C1, C2
2. Group 1: C3, C4 & C5
3. Group 1: C6
4. Group 1: C7, C8

# Answer
> 0 votes
* Create a view that lists all content of type "Group Content"
* Add a relationship OG membership: Group Node from OG membership and make it mandatory

\- Add field Group Title and exclude it from display choose relationship above

* Use Group By Option in Display settings and group by Group Title

And the output will be

Find view export below.. Content type names are group and group\_content

```
$view = new view();
$view->name = 'group_group_content';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Group - Group Content';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Group - Group Content';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'title_1',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: OG membership: Group Node from OG membership */
$handler->display->display_options['relationships']['og_membership_related_node_group']['id'] = 'og_membership_related_node_group';
$handler->display->display_options['relationships']['og_membership_related_node_group']['table'] = 'og_membership';
$handler->display->display_options['relationships']['og_membership_related_node_group']['field'] = 'og_membership_related_node_group';
$handler->display->display_options['relationships']['og_membership_related_node_group']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title_1']['id'] = 'title_1';
$handler->display->display_options['fields']['title_1']['table'] = 'node';
$handler->display->display_options['fields']['title_1']['field'] = 'title';
$handler->display->display_options['fields']['title_1']['relationship'] = 'og_membership_related_node_group';
$handler->display->display_options['fields']['title_1']['label'] = 'Group';
$handler->display->display_options['fields']['title_1']['exclude'] = TRUE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'group_content' => 'group_content',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'group---group-content';

```

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


# Question
Title: How to limit number of files uploaded with plupload integrtion module?
I'm using Plupload integration module. In my Form API form I want to use it as simple replacement for file element. However, both `file` and `managed_file` types accept one file. `plupload` accepts any number of files. How to limit it to only defined number of files? Or simply one?

Setting cardinality as FileField Sources Plupload does:

```
'#plupload_settings' => array(
  'cardinality' => 1,

```

does not work, and I wasn't able to find any other parameter for this.

# Answer
> 0 votes
The way I limited it to single file, was to create js file and attach it to the form. In that file, I bound a function to `QueueChanged`, to remove excess files and hide "Add file" button:

```
(function($) {

Drupal.plupload = Drupal.plupload || {};

/**
 * Attaches the Plupload behavior to each Plupload form element.
 */
Drupal.behaviors.download_plupload = {
  attach: function (context, settings) {
    $(".plupload-element", context).once('download-plupload-init', function () {
      var add_button = $(this).find('.plupload_button.plupload_add');
      var uploader = $(this).pluploadQueue();
      uploader.bind('QueueChanged', function() {
        var local_uploader_element = this;
        // Remove files exceeding the cardinality setting.
        if (local_uploader_element.files.length >= 1) {
          var i = 0;
          for (i=0;i<local_uploader_element.files.length;i++) {
            if (i >= 1) {
              $(this).removeFile(uploader.files[i]);
            }
          }
          add_button.hide();
        }
        else {
          add_button.show();
        }
      });
    });
  }
};

})(jQuery);

```

This is a simplified version of js found in FileField Sources Plupload, trimmed, without Field API specific parts, and made to work on all plupload elements.

---
Tags: forms, files
---


title: How to retrieve sumbitted data in modal

text:
# Question
Title: How to retrieve sumbitted data in modal
I want in add content have a link(or button) when user click on lt the popup (modal or any popuping method like dialog,modal,lightbox,colorbox ) will open, in that form I want have some field, like hierarchical select and long text fields, after user submit that form, the submitted values passed back to add content form,

**appreciate any idea**

# Answer
> 1 votes
I'd suggest an approach which is not a solid, but you can get an idea;

* Create modal with Ctools (may be this and this links can help you to create it);
* On form submission store the submitted data as array into $\_SESSION;
* reload the page with `ctools_ajax_command_reload();`

example:

```
// This is must be in ctools modal callback. Read modal.html file in ctools/help directory
if (!empty($form_state['executed'])) {
  $commands = array();
  $commands[] = ctools_ajax_command_reload();
}

```
* Alter the content add form;
* add `#default_value` to the fields, e.g.: `'#default_value' => isset($_SESSION['modal_data']['field_1_value']) ? $_SESSION['modal_data']['field_1_value'] : ''`;
* at the end of the content add form just unset the $\_SESSION data, e.g.: `unset($_SESSION['modal_data'])`;

---
Tags: 7, forms, javascript
---


# Question
Title: In a group content add form, the og_group_ref is empty, except for the "_none" value
This is only for non admin members. Administrators have the field populated, but logging in as anyone that isn't in that role produces an empty field, except for the "\_none" value.

I've tried adding the value manually, like this:

```
if(!isset($form['og_group_ref'][LANGUAGE_NONE][0]['default']['#options']['MyGroup'][$gid])){
  $form['og_group_ref'][LANGUAGE_NONE][0]['default']['#options']['MyGroup'][$gid] = 'current MyGroup';
}

```

This adds the item, but I get an error about an illegal option, so it's not the solution.

Again, the field loads all groups for the admin members, but not for non admins. Is there a special permission that needs to be set?

# Answer
It turns out that organic groups permissions were inadvertently changed, causing the issue, and attempts to fixed this made it only worse. Permissions have been restored, and the system now works as expected.
> 0 votes

---
Tags: nodes, forms, users, organic-groups
---


title: How to redirect to a translatable page

text:
# Question
Title: How to redirect to a translatable page
I have a bilingual site and I want to redirect to a custom page, which has two language versions, upon form submitting. This may be a pretty basic thing, but I am only starting to learn how to code for Drupal in PHP. This is what I tried:

```
$form_state['redirect'] = t('message-sent-successfully');

```

'message-sent-successfully' is the URL for the English version of the page. It has a different URL for the other language the site is using. In whatever language I submit the form, I get redirected to the above URL, i.e. the url doesn't get translated.

# Answer
> 0 votes
Install i18n and enable the Translation Redirect module within.

Install Globalredirect and go to `admin/config/system/globalredirect` and check "Language path checking".

You can then take the user to either source or translated node, and Globalredirect will take the user to the page which is in the currently active language.

---
Tags: uri, redirection, i18n-l10n
---


title: Node tabs leading to related nodes

text:
# Question
Title: Node tabs leading to related nodes
I am using a webform to build a basic person node and other related nodes (contact, address) at once.

I'd like to have node tabs ("Contact Infos", "Address") when showing the person node, which are showing the related nodes using url aruments like "/node/1234/contact" or "/node/1234/address".

Do I have to use the hook\_menu in a custom module or is there another way to do this?

# Answer
I used panels for this. I added a new panel, which has the node with the nid of the webform as only content item in the main content area. I set the menu entry for the panel to "Menu Tab" and set the access rule of the panel to "Show only when node is of type person". This shows the desired tab element when a person node is selected.

For the webform itself I used the `hook_form_alter`with the `$form_id == "webform_client_form_<nid>"` having `<nid>` as the node ID of the webform to set the `#default_value` of the webform field with the data coming from the person node. The ID of the person node I get by using the `arg(1)` function and the loading the node data with `node_load($nid)`.

Hope that helps others.
> 1 votes

---
Tags: nodes
---


# Question
Title: Export the default system email text to code?
Is it possible to move the default system email message text found in the account settings page out of the database and into the code for version control?

Currently using the mimemail module since we use HTML/CSS formatted emails.

# Answer
Settings in files for version control was one of the biggest changes in the 7 -\> 8 jump. Drupal 7 has no built-in way to do it. You may wish to see How to version control data stored in mysql.

If you want Drupal-specific tool, investigate Configuration Management module:

> The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.
> 0 votes

---
Tags: 7, emails
---


title: how to overwrite the search box?

text:
# Question
Title: how to overwrite the search box?
```
<div class="fr_search">
  <form action="/"  accept-charset="UTF-8" method="post" id="search-theme-form">
    <input  name="search_theme_form" id="edit-search-theme-form-1" size="15" value="" class="form-text" />
    <!-- … -->
  </form>
 </div>

```

The above code is generated by the Drupal Search module. I want to add this code to the form.

```
<select class="search_l" onchange="selectSearch(select)">
  <option value="0">whole site search</option>
  <option value="1">google search</option>
</select>

```

How do I do this?

# Answer
I would rather implement `hook_form_FORM_ID_alter()` to alter the form returned by search\_box(). If mymodule.module is the name of your module, then you should add the function `mymodule_form_search_box_alter(&$form, &$form_state)`. You need also to replace the form submission handler with your own.

```
function mymodule_form_search_box_alter(&$form, &$form_state) {
  $form['submit']['#weight'] = 10;

  $form['search_type'] = array(
    '#type' => 'radios',
    '#options' => array(t('Whole site search'), t('Google search')),
    '#default_value' => 1,
    '#weight' => 5,
  );

  // Replace the search.module handler with your own.
  if (in_array('search_box_form_submit', $form['#submit'])) {
    $key = array_search('search_box_form_submit', $form['#submit']);
    unset($form['#submit'][$key]);
  }
  array_unshift($form['#submit'], 'mymodule_search_box_submit');
}

```

You could also show the form field containing the text to search inline with the radios you add.
The code I reported replaces the form submission handler with `mymodule_search_box_submit()` that must be implemented from your own module. This is the code executed from the submission handler implemented by search.module; I report it as reference.

```
function search_box_form_submit($form, &$form_state) {
  // The search form relies on control of the redirect destination for its
  // functionality, so we override any static destination set in the request,
  // for example by drupal_access_denied() or drupal_not_found()
  // (see http://drupal.org/node/292565).
  if (isset($_REQUEST['destination'])) {
    unset($_REQUEST['destination']);
  }
  if (isset($_REQUEST['edit']['destination'])) {
    unset($_REQUEST['edit']['destination']);
  }

  $form_id = $form['form_id']['#value'];
  $form_state['redirect'] = 'search/node/' . trim($form_state['values'][$form_id]);
}

```

As reference, I report here the code of the search.module function that builds the search box form.

```
function search_box(&$form_state, $form_id) {
  $form[$form_id] = array(
    '#title' => t('Search this site'),
    '#type' => 'textfield',
    '#size' => 15,
    '#default_value' => '',
    '#attributes' => array('title' => t('Enter the terms you wish to search for.')),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Search'),
  );
  $form['#submit'][] = 'search_box_form_submit';

  return $form;
}

```
> 11 votes

# Answer
The best way to do this, IMO, would be to simply use hook\_form\_alter().
> 2 votes

# Answer
I think you are better off using hook\_form\_alter() than editing the template (no offense, but that is really bad practice).

You probably want to add a new form element and a submit handler to the search form, so you can handle the submit action and process the value of the new element.
> 1 votes

# Answer
There is a search-block-form.tpl.php template:

https://api.drupal.org/api/drupal/modules!search!search-block-form.tpl.php/7

In that template it's important to have hidden fields. Mine currently looks like:

```
<form action="" method="post" class="search_form">
      <?php print $search['hidden']; ?>
        <input type="text" name="search_block_form" class="input" />
        <input type="submit"  id="edit-submit--3" name="op" value="" class="submit" />
</form>

```
> 1 votes

# Answer
This is great for just the search box but the results displays on the main search page, which I need to override. For that reason I want to be able to use the search-result(s).tpl.php and block files. But I can't seem to get the code correct in my template file. I tried using the code on this page changing obviously the theme template but the changes I made to the tpl.php shows they are not being used. What am I doing wrong?

```
function dove_preprocess_search_results(&$variables) {
  $variables['search_results'] = '';
  if (!empty($variables['module'])) {
    $variables['module'] = check_plain($variables['module']);
  }
  $index = 0;
  foreach ($variables['results'] as $result) {
    $variables['search_results'] .= theme('search_result',
      array(
        'result' => $result,
        'module' => $variables['module'],
        'extra_classes' => $index % 2 === 0 ? ' even' : ' odd',
      )
    );
    ++$index;
  }
  $variables['pager'] = theme('pager', array('tags' => NULL));
  $variables['theme_hook_suggestions'][] = 'search_results__' . $variables['module'];
}

```

I just thought I'd add the reason I need to edit the files is I'm using custom search module which is great but in the result it's giving me the type:allthecontenttypes in the input form plus the search results. U G L Y.
> 0 votes

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


title: openssl key for drush

text:
# Question
Title: openssl key for drush
My server does not allow passwords and requires me to setup an openssl key for access. Drush however requires the server to be more open and I wonder how to setup an openssl key or some other option for using drush update features.

# Answer
By default, Drush runs ssh with the option `-o PasswordAuthentication=no`, which prohibits username/password access and requires that you use a public/private key pair to access your server. This is exactly what you want, and in fact, by default, ssh will use the private key that it finds at $HOME/.ssh/id\_rsa to authenticate you with remote servers.

If you need to use some other private key, though, you can put this line in your drushrc.php file:

```
$options['ssh-options'] = '-o PasswordAuthentication=no -i /home/YOURUSERNAME/.ssh/other_id_rsa';

```

Note that Drush will not automatically evaluate bash shortcuts such as $HOME or ~. If you do not want to hardcode the path to your home folder, you may look it up with `$HOME = drush_server_home();`.
> 0 votes

---
Tags: drush, ssl
---


# Question
Title: Is there an easy way to update img src attributes when moving to a new server?
I recently copied my site from the dev server to a test server, and I noticed that a lot of images which were placed using the Media module have `src=` attributes that point to the old server. Ie., `<img src='http://oldsite.com'...>` I don't see any settings within the configurable options for the Media module which will update the links.

I know that WordPress has a handy link updater plug-in called Velvet Blue, or something like that. Does anyone know of a similar module for Drupal?

# Answer
What you are looking for is the Pathologic module.

> Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server.

Cheers,
> 5 votes

# Answer
I was recently working on Drupal multisite to a single site conversion and ran into the same problem. I solved by running this SQL command

```
update `files` set filepath = replace(filepath,'sites/<my_site_name>/files','sites/default/files');

```

which updated the file paths of my files in the files table. You can do something similar for images used in content. I think you need to target the `node_revision` table and the `body` column. So, something like this:

```
update `node_revision` set body = replace(body,'sites/<my_site_name>/files','sites/default/files');

```

Source
> 0 votes

---
Tags: navigation, migrations, media, updating
---


# Question
Title: How to change html of CAPTCHA module in another module?
I add captcha field to form in this way

```
$form['captcha'] = array(
    '#type' => 'captcha',
    '#title' => 'Simple title',
    '#captcha_type' => 'captcha/Math',
    '#description' => 'Please solve it'
);

```

This element will be rendered as

```
<fieldset class="captcha form-wrapper"><legend><span class="fieldset-legend">CAPTCHA</span></legend><div class="fieldset-wrapper"><div class="fieldset-description">Please solve it</div><input type="hidden" name="captcha_sid" value="102">
<input type="hidden" name="captcha_token" value="bf6179f1c98e4291e1bb2e11c733d991">
<div class="form-item form-type-textfield form-item-captcha-response">
  <label for="edit-captcha-response">Math question <span class="form-required" title="Обов'язкове поле">*</span></label>
 <span class="field-prefix">20 + 0 = </span> <input type="text" id="edit-captcha-response" name="captcha_response" value="" size="4" maxlength="2" class="form-text required" autocomplete="off">
<div class="description">Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.</div>
</div>
</div></fieldset>

```

How to change this html template ?

# Answer
> 2 votes
I guess you could override theme\_captcha. here is the code

```
function bartik_captcha($variables){
  $element = $variables['element'];
  $output='<h2>'.$element['#title'].'</h2>';
  $output.= drupal_render_children($element);
  return $output;
}

```

---
Tags: 7, theming, captcha
---


# Question
Title: What module should I use to save a module settings in a feature?
I am needing some additional power for my Features. I have several modules that have their own settings (like css injector... yeah, I know) which do not appear in teh list of items that can be saved within a feature. I have been told that Strongarm offers a good way to include additional configuration within a feature (above and beyond what Features can normally store.) I have also heard talk of another module that is (commonly?) used with Features which improves its ability to store and transfer configurations. I can not remember the name of this other module. Could someone point me in the right direction?

# Answer
Many modules store their settings in variables, that's what Strongarm is good for : it can help you export those variables with features.

My usual way of finding out which variable to export (and exporting it) :

* see the source HTML of the form where you set the values
* in the "name" attribute you will most often find the name of the variable
* use drush vget \*that\_variable\* to check if it exists
    + `drush vget` is useful because it searches all variables that have a name similar to the string you provide, so sometimes you can do some testing to see other variables that could be useful
* if you confirm the name of the variable, put it into the feature's info file
    + `features[variable][] = that_variable`
* run drush fu your\_feature
    + this will export the variable's value

The other module you heard off might have been Features Extra. Me personally i don't find it that useful anymore.

There is a free video on drupalize.me about features. And an article on d.o.
> 2 votes

---
Tags: 7, features, strongarm
---


# Question
Title: Filter to display only modified content in Views
I created a view that displays the number of nodes modified by each user on a specific month. I check the "modification date". The problem is that I also obtain nodes that have never been modified but have been created on that date.

In the node table, "created" and "changed" fields have the same value when the node is created. How can I only retrieve the nodes that have been modified but not created on a specific month ?

Maybe a way of doing this is to check if node.changed \<\> node.created, but how can I do that in views ?

# Answer
Unfortunately impossible to do it in the current UI.

There are 3 options AFAIK :

A repaired :) attempt to do the alter hook (with help from another answer on this great site) and the add\_where\_expression function :

```
function main_mm_views_query_alter(&$view, &$query) {
  if($view->name == 'admin_views_user') {
    $query->add_where_expression(0,'users.access < users.login');
  }
}

```

This is the view that comes with the module admin views. there are 2 columns - access and login, both are dates and this seems to work :) you will want to do a dpm($query) first, to see your actual query.
> 2 votes

# Answer
In view's `Filter criteria`:

* first filter: `Content: Post date` `Is greater than (or equal to)` `-1 month`
* second filter: `Content: Updated date` `Is less than` `-1 month`
> 0 votes

---
Tags: views
---


# Question
Title: Add a last edited by column to find content results
In the admin area when a user is on the find content page /admin/content I would like to add an extra column to the results table to display the user who last edited the node.

I'm fine with actually querying to get the data I'm just not sure of the best way to add the extra column to the results table.

Thanks

# Answer
You are looking Extra Columns

> This module allows additional columns/data to be added to the node, comment, and user tables in administration area. It provides a list of fields defined in your drupal installation as well as a few custom fields to choose from.

Alternatively you can try Administration Views module.
> 1 votes

# Answer
This can be done with Administration Views

1. Install the module
* Enable it
2. Edit "Administration: Nodes" view
* Add a Relationship
    + Select "Content revision: User"
        + Name it "editor"
    * Add the field to the view
    + Select "User: Name"
        + click "Apply (all displays)"
        + Under relationship, select "editor"
        + Change Label to "Edited-By"
        + click "Apply (all displays)" again
    * Save the view

**Note:** The "Extra Columns" module does NOT give the option to add an "Edited by" column. Also, The Admin Views module is incompatible with Extra Columns module (only one will show up at a time)
> 1 votes

---
Tags: nodes, users
---


# Question
Title: Are there any acceptable uses for $_COOKIE['has_js'] outside of core?
Drupal 7 has a cookie called `has_js`. drupal.js sets this cookie, and it is used by the Batch API and the authorize.php script.

There is a rather old issue about this cookie, backport "$\_COOKIE\['has\_js'\] must die" patch to 7.x, but this cookie still remains in drupal-7.x.

Are there any acceptable uses for this cookie, outside these two cases in core?

# Answer
> 3 votes
I don't think so, for many separate reasons.

1. Given the comment made to 8.x change records Removed has\_js cookie:

> Only Batch API used it as a workaround. A clean solution has been reached avoiding the need for the cookie.

I would extrapolate that any solution that uses it should be considered unclean.
2. There is no page for it on api.drupal.org so it appears it wasn't designed to be used outside and it's not guaranteed to stay unchanged. It's a common in IT to assume one uses undocumented features at his own risk.
3. It can be unset if JavaScript is on, but Cookies are off, so it cannot have a clear meaning.
4. It can be unset if some module will successfully try to make site EU Cookie Law compliant (and user didn't agreed yet)
5. If you read it from PHP, it will be unset if your page is first one loaded after "open in private window" or "clear cookies" click, no matter what are client's JS and Cookie settings.

Reasons in no particular order.

---
Tags: 7, javascript, cookies
---