# Question
Title: How to determine block module given block delta
Is there a way to determine a block's module given only the block's delta? I'm hoping for a solution that does not require a custom query.

**Use case:**
We are enabling our client to decide which blocks are displayed on a given content type. Those options include blocks created through the block admin interface and blocks created through the views admin. From what I can tell, a regular block and a view's block are rendered differently so psuedo code would be something like.

```
// In preprocessing
if($block_module === 'views') {
    // do view rendering
} else {
    // do normal block rendering
}

```

Any ideas?

# Answer
No, it's not possible without having the module name.

Block deltas only need to be unique *per module*, so any two modules could implement a block with exactly the same delta, and you'd have no way to determine which was which without the module name.

The simplest proof of this in the code is the `block_load()` function, which has this signature:

```
function block_load($module, $delta) {

```

As you can see, even Drupal can't load the details of a block without knowing the module name unfortunately.
> 0 votes

---
Tags: 7, views, blocks
---


# Question
Title: IMCE module is not showing icons on the editor
I installed the IMCE module, but it didn't add any icon to the editor menu toolbar. It manually loads with domain.com/imce.

# Answer
> 0 votes
You need IMCE WYSIWYG bridge module to connect it with WYSIWYG editor.

For CKEditor, configure the editor for your input filter and choose "IMCE" button.

For TinyMCE it is enough to select "Image" button.

# Answer
> 0 votes
You could also use CKeditor instead of the wysiwyg bridge.

---
Tags: 6, media
---


title: Edit Blog Links & Breadcrumb?

text:
# Question
Title: Edit Blog Links & Breadcrumb?
My client would like me to replace the s's with just ' on the links and breadcrumbs of user blogs for user names that end in s.

For example, the breadcrumb and blog links for the user Joe would remain Joe's blog while the breadcrumb and links for user Chris would be Chris' blog (instead of Chris's blog).

I searched for this and although I did find a way to do this inversion 6 it doesn't seem to work in version 7.

How can I do this?

# Answer
Adding to what Suresh commented about only modifying the breadcrumbs on a specific page, you could use either hook\_preprocess\_node or hook\_preprocess\_page to check the post type of your content and then apply the breadcrumb changes:

```
function example_preprocess_node(&$variables, $hook){
    if($variables['node']->type == 'YOUR_CONTENT_TYPE_HERE'){
        $bread = drupal_get_breadcrumb();
        $title = $bread[0];
        $lastCharacter = substr($title, -1);
        $variables['newcrumbs'] = $lastCharacter;
    }
}

```
> 2 votes

# Answer
I had similar, work to be done, in drupal 7.

So, what I did, is, I collected the breadcrumb title, like this,

```
$bread = drupal_get_breadcrumb();
$title = $bread[0];

$lastCharacter = substr($title, -1);

```

$lastCharacter gave whether the breadcrumb title ends in S or not. If it ended, then, I appended, (')at last otherwise, I apended, ('s).I did this by adding a function in template.php file. Also, you can do by making any module, or any other way you wish.
> 2 votes

---
Tags: navigation, breadcrumbs, nodes
---


# Question
Title: How do I alter the output of an existing views handler?
How do I alter the output of an existing views handler?

I want to alter `views_handler_field_user_picture()` to get the link to the user profile, not the themed picture.

See alter existing handlers (handler overrides). I expect a link like this http://cdn.sstatic.net/drupal/img/logo.png.

```
function mymodule_views_data_alter(&$data) {
  $data['users']['picture']['field']['handler'] = 'my_custom_handler';
}

```

module .info

```
files[] = user_picture_formatter.inc

```

and user\_picture\_formatter.inc is like this

```
<?php
class my_custom_handler extends views_handler_field_user_picture {
  function render($values) {
    if ($picture_fid = $this->get_value($values)) {
      $picture = file_load($picture_fid);
      $picture_filepath = $picture->uri;
    }
    else {
      $picture_filepath = variable_get('user_picture_default', '');
    }
    return $picture_filepath;
  }
}
?>

```

# Answer
The short answer is that you can't alter the output of a views handler. But what you can do is:

* Create your own handler that is a subclass the handler you want to overwrite.
* Add a render method - which will generate the output (this is where your alter code is)
* Use `hook_views_data_alter` to make views use your handler instead where needed.

This will get the wanted effect, where you can alter the output of the original views handler, but in reality to make views use your custom handler.

In code it could look something like this.

```
class my_custom_handler extends views_handler_field_user_picture {
  function render($values) {
    ...
  }
}

function my_module_views_data_alter(&$data) {
  $data[...]['handler'] = 'my_custom_handler';
}

```

This code is for Drupal 7, but the method can be used in both Drupal 6 and 7. For Drupal 7 you should create the class in it's own file and add the file to the module's .info file, to make Drupal autoload the file with the class when needed.
> 4 votes

---
Tags: views, users
---


title: Can any function be used as a hook?

text:
# Question
Title: Can any function be used as a hook?
I'm looking to override format\_size(), but I'm not sure if this is possible in a module.
If I implement `myModule_format_size()` or in a theme `myTheme_format_size()` will the hook be called?

# Answer
No. Not all functions invokes a hook in other modules. As we can see in http://api.drupal.org/api/drupal/includes%21common.inc/function/format\_size/7 there is no module\_invoke\_all is called.

Here is how we define module\_invoke\_all

> Invokes a hook in all enabled modules that implement it.

```
function module_invoke_all($hook) {
  $args = func_get_args();
  // Remove $hook from the arguments.
  unset($args[0]);
  $return = array();
  foreach (module_implements($hook) as $module) {
    $function = $module . '_' . $hook;
    if (function_exists($function)) {
      $result = call_user_func_array($function, $args);
      if (isset($result) && is_array($result)) {
        $return = array_merge_recursive($return, $result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    }
  }

  return $return;
}

```
> 1 votes

# Answer
In Drupal, a hook is not a function that is called instead of a function defined from Drupal; it is a function that Drupal, or any third-party module, calls through module\_invoke\_all(), or module\_invoke().
In your case, `mymodule_format_size()` will never called instead of `format_size()`, but it will be eventually called as `hook_format_size()` implementation (whatever purpose it has), if a module invokes that hook.

Since it is not possible to expand `format_size()`, which doesn't invoke any hook, contrary to format\_username(), the only way to change the code executed from `format_size()` is to act on the functions calling it. In other words:

* If `format_size()` is used in a form submission handler, then you could alter that form to remove that form submission handler, and replace it with your own handler, which doesn't call `format_size()`
* If `format_size()` is used from a template file that is used from a theme function implemented in a module, you could override the template file in a theme
* If `format_size()` is used from a theme function, you could override the theme function (in a module or in a theme) with a version of the theme function that doesn't call `format_size()`
> 1 votes

---
Tags: hooks
---


# Question
Title: How do I add a user as a field in Drupal 7?
References claims that it is now deprecated in favor of Entity Reference. But I can't quite connect the dots on how an Entity Reference can point to a specific user. Ideally, I would have this field simply be the user that originally submitted the node.

Basically, all I want is a "File" content type that includes the user who uploaded the file. I feel like I am over-complicating it. Please help.

# Answer
> 0 votes
Is this what you need?

1. Add a field to the File content type. For FIELD TYPE choose "Entity Reference".
2. Save and configure the new field. For Target type choose "User".

---
Tags: entities
---


title: Transform textinput into select-field

text:
# Question
Title: Transform textinput into select-field
I'm trying to transform my textinput into a select-field but I keep stumbling upon `An illegal choice has been detected`-error.

What I try in my `hook_form_alter`is this:

```
$form['distance']['search_distance']['#type'] = 'select';
$form['distance']['search_distance']['#options'] = drupal_map_assoc(array(100 => '100 km', 200 => '200 km'));

```

It looks like he's doesn't like strings to be in the select list, although, the value of the input is an integer...

How can I make this input field accept my modifications?

# Answer
I don't know if this is causing the error, but you're using `drupal_map_assoc()` wrong...

The point of that function is to take a linear array and *convert* it to an associative array with the values of the given array as associated keys. e.g.

```
$form['distance']['search_distance']['#options'] = drupal_map_assoc(array(100, 200, 300));

```

I kind of suspect what you're meaning to do is this:

```
$form['distance']['search_distance']['#options'] = array(100 => '100 km', 200 => '200 km');

```

Your array is already associative, no need to try making it associative all over again :)
> 1 votes

---
Tags: 7, forms
---


title: File_managed URI change not working

text:
# Question
Title: File_managed URI change not working
Is there a way i can make file\_managed URI changes in the database?

I the database i have a list of files and there is append a \_1 or \_2 to the URI file name.i wanted to clean these up and remove the \_number so there will be only one file but when i change it i get an error unable to write row duplicate entry for uri key.

# Answer
Doing this directly in the database can be messy given the way Drupal abstracts its managed files. It is usually better to try and find a solution that works with the Drupal file API directly so you're not forgetting some entry somewhere and leaving extra cruft in your database. You could roll your own solution using the file API and file\_delete() but I would suggest that you're better off doing this using an interface like IMCE and combining that with a solution like this module:

http://drupal.org/project/upload\_replace

which would resolve this problem for you going forwards:

> The problem with drupal is if you have a file called "mydoc.doc" upload it to a node, then make changes to "mydoc.doc" and upload the newer version, the newer version will be renamed to "mydoc\_0.doc" because at the time of upload the old file was blocking the desired path name.
>
> This module solves that problem by swapping the names of the older and newer file so that the newly uploaded file will retain its original name.
> 0 votes

---
Tags: database, uri
---


title: Error 324 (net::ERR_EMPTY_RESPONSE)

text:
# Question
Title: Error 324 (net::ERR_EMPTY_RESPONSE)
Using Drupal 7 and Clean theme and installed Views module. Everything is worked but now, when click Save in Views get this error:

''Error 324 (net::ERR\_EMPTY\_RESPONSE): The server closed the connection without sending any data.''

My site is on MAMP local. Whats this problem?

# Answer
clearing cache might help:

```
truncate table cache;

```
> 1 votes

# Answer
I also got trouble with this.

Setting file permissions of `sites/MYDOMAIN/files` and `sites/MYDOMAIN/files/css` to 777 and hitting F5 key a few times in a row seem to have fixed it for me.
> 0 votes

---
Tags: views, 7
---


title: Download post as text file

text:
# Question
Title: Download post as text file
I wanted to provide functionality in which where user decides to cancel his account, he can download all the post that he has created as txt file. Is there any drupal module that helps to achieve this, or at-least that allows to export node as txt file in Drupal 7.

I have gone through Print module, but it does not support txt file and I can not use PDF option, as this will take long time to generate PDF of all usaer created node upon cancellation of account.

Please suggest how can I proceed.

-- Many thanks for your time.

# Answer
> 2 votes
try the views\_data\_export .... it can export to CSV or basic text format. and you could select a users Nodes: title and body at least ... and any other fields you want...

> This module is designed to provide a way to export large amounts of data from views. It provides a display plugin that can rendered progressively in a batch. Style plugins are included that support exporting in the following types:
>
> CSV
>
> Microsoft XLS
>
> Microsoft DOC
>
> Basic TXT
>
> XML

---
Tags: 7, nodes, importing-exporting
---


title: How to disable page link?

text:
# Question
Title: How to disable page link?
I am new to drupal 7. I read the online documentation but, due to less programming skills, I could not figure out the exact solution.

I want to disable pager link. How can I do that?

# Answer
I can understand, its hard for beginer to understand but drupal.org provides full documentation on it. Please, google before you post here.

probably, this would help you.

Drupal support forum page
> 2 votes

---
Tags: 7
---


# Question
Title: Where In or clause for when a variable might not exist
If I were to run a normal mySQL query that selects all nodes I would do this:

```
set @type='node';
select * from actions where type = @type;

```

but what if lets say I set `type` to be something that doesn't exist for example

```
set @type='';
select * from actions where type = @type or 1=1;

```

This will then in return select everything regardless.

How do I do the same with db\_query?

I thought just doing

```
db_query("select * from actions where type = :type or 1=1;", array(':type' => '')).fetchAll();

```

but that doesn't work. Any ideas? (notice that :type is equal to '' just like in the mySQL example)

# Answer
> 2 votes
What you need to do is take that logic out of the SQL query, and instead use the query builder so to create your query; then you can add the `IN` statement conditionally, e.g.

```
// Set up your query
$query = db_select('actions')->fields('actions');

// See if you have data
if (!empty($types)) {
  // IN is the default operator for arrays so there's no need to specify,
  // but for the sake of an example...
  $query->condition('type', $types, 'IN');
}

// Get the results
$results = $query->execute()->fetchAll();

```

---
Tags: 7, database
---


# Question
Title: In editing content, can I show source formatted HTML
Might there be a way to show properly formatted HTML when in CKeditor's `source` view? Is there a way to color code the HTML and Javascript source for my more advanced content editors?

I have turned on Apply Source Formatting which has helped some.

# Answer
Syntax highlighting is your keywords. I uncovered this for you. http://code.google.com/p/ckeditor-syntaxhighlight/wiki/Installation

There is most likely more plugins available but you will need to add a plugin to achieve what you are looking for.
> 1 votes

---
Tags: wysiwyg, nodes
---


# Question
Title: Send email grouped on a commerce line items field
I use commerce a little different than most as I schedule trips as custom line items.

A trip is scheduled by someone else and they can schedule as many trips as they want for however many users they want.

I am trying to send an email to the user that had a trip scheduled.

My problem is that a user can have multiple legs (line items) on a single order. So when I try to loop through the line items, it sends out an email per line item (which it should) but to the user it is a duplicate.

I want to use rules to send an email out once.

Is there a way to group the line items on the user as a result and then just send one email out?

# Answer
I think I found the solution to this. I should be able to load the list of line item entities using VBO and a view grouped on the user. I got the information needed from here:

http://nodeone.se/sv/node/777

Then I just pass the \[commerce-order:order-id\] as an argument.

**EDIT** This worked for me.
> 1 votes

---
Tags: commerce, rules
---


# Question
Title: Multisites placed inside sub site folder?
I have my main plain html site in root folder and drupal site in sub site folder. Now I am wanting to create multisites and wonder if sub sites can reside in drupal sub site sites folder?

www.subdrupal.mainsite.com/subdrupal/sites/sub2drupal etc.

Or must I start again as it can only be www.subdrupal.mainsite.com/sites/subdrupal ?

# Answer
Good question. It is possible to run drupal multisites as a subdirectory even if your Drupal installation is in a subdirectory itself.

> Side note: the /sites/ directory in your examples is not necessary.

Given that your main Drupal install is accesible at `domain.com/drupal` the solution is to use symlinks to tell your webserver that the document root for `domain.com/drupal/multisite` is the same as your main drupal install (`domain.com/drupal`).

1. The first step is to create a directory for the multisite. The syntax is a little different for subdirectory multisites: `domain.com.multisite`. So, inside your `/sites` directory, you will have something like this:

`-|/sites
--|----/all
--|----/default
--|----/domains.com.multisite`
2. Place a copy of `default.settings.php` in `domains.com.multisite` and rename it to `settings.php`.
3. Then create the symlink described above by running the following command from your main website's docroot (not Drupal's docroot, the main website's docroot - usually `public_html` or something similar):

`ln -s [drupal-directory-name] [multisite-directory-name]`

Or, using the names in our example above:

```
ln -s drupal multisite

```

See Drupal's multisite documentation for more information.
> 1 votes

---
Tags: multi-sites
---


# Question
Title: How to create another Front Page and switch between the two? (in dev process)
I am working on creating an alternative front page for an existing site. I do not want to disturb the existing front page but I just want to create another page (which I will later point to as front page - once design is complete).

Question: How do I create a page where I can add Blocks and other items? (I did it from Views - but doing so from Views requires me to add fields).

I do not want to add fields from views - want to do it entirely with blocks (even in the main content area)

# Answer
> 2 votes
You can use context http://drupal.org/project/context to achieve this. You can filter on the path and then add blocks to that specific page.

But you will need a holder page. Sometimes I create a holder content type and then modify the node template to not display anything or just the title. Then I can attach any view/block or w/e to it. So that piece of content is just a "holder".

---
Tags: 7
---


# Question
Title: How to programmatically create a large taxonomy in Drupal 7?
I need to create a taxonomy with an entry for every living language in the world (nearly 7,000, using ISO 639-3 codes: http://en.wikipedia.org/wiki/List\_of\_ISO\_639-3\_codes). Note that the ISO 639-3 code is stored as a custom field.

In light of this: what is the easiest way to create this list directly via MySQL using a PHP (or other) script?

I have attempted to directly create entries by inserting values directly into MySQL:

```
INSERT INTO taxonomy_term_data (vid, name, description, format) VALUES (2,"Ghotuo","<p><em>Africa</em></p>","filtered_html");

INSERT INTO field_data_field_iso_639_3 (entity_type, bundle, entity_id, revision_id, language, delta, field_iso_639_3_value) VALUES ("taxonomy_term", "language", 3, 3, "und", 0, "aaa");

INSERT INTO url_alias (source, alias, language) VALUES ("taxonomy/term/3", "language/ghotuo", "und");

```

I am obviously missing something, because this entry is not seen by Drupal in the "Languages" taxonomy.

I have looked at this question but am unsure how to set this up as a stand-alone PHP script (not incorporated into the site itself).

Any ideas how to programmatically create this taxonomy? TIA.

# Answer
Myself still learning how to properly write modules, I managed to come up with the following code for saving the terms into separate table named MODULENAME\_data. It may not be perfect - but it apparently worked. I'm open to downvoting, but even more to suggestions on how to improve it.

```
// Make the table name a constant for easier coding
// We will store it's vid as system variable after we have created it
define("MODULENAME_VOCAB_MACHINE_NAME", "iso_639_3_codes_data");

function MODULENAME_enable(){
  // Create the vocabulary.
  $vocab = array(
    'name' => 'Vocabulary name',
    'machine_name' => MODULENAME_VOCAB_MACHINE_NAME,
    'description' => t('Vocabulary of iso 639-3 language codes'),
    'module' => 'taxonomy',
    'hierarchy' => 0,
    'module' => 'MODULENAME',
  );
  taxonomy_vocabulary_save( (object) $vocab);

  // Now that we've created the vocabulary, let's store its vid as a system variable
  $vocab = taxonomy_vocabulary_machine_name_load(MODULENAME_VOCAB_MACHINE_NAME);
  $vid = $vocab->vid;
  variable_set('MODULENAME_vocab_id', $vid);

  // Create custom field.
  $field = array(
    'field_name' => 'field_custom_field',
    'type' => 'text',
    'label' => t('Symbol') // where is that used? I dunno, but API says so ;-)
  );
  field_create_field($field);

  // Create field instance on the vocab
  $instance = array(
    'field_name' => 'field_custom_field',
    'entity_type' => 'taxonomy_term',
    'bundle' => MODULENAME_VOCAB_MACHINE_NAME,
    'label' => t('Custom field'),
    'description' => t('Description'),
    'required' => true,
    'widget' => array(
      'type' => 'text_textfield',
     )
  );
  field_create_instance($instance);

  // Here you would include an include file that provides row data
  // (probably an array) and then iterate over it to populate table
  // such as

      // Save terms.
      foreach ($items as $item) {
        taxonomy_term_save((object) array(
          'name' => $item[0],
          'vid' => $vid,
          'field_custom_field' => array(
            LANGUAGE_NONE => array(
              0 => array(
                'value' => $item[1] ,
              )
            )
          ),
        ));

}

function MODULENAME_disable(){
  // Some system cleanup.

  // Delete vocabulary. This deletes terms and field references too.
  taxonomy_vocabulary_delete(variable_get('MODULENAME_vocab_id'));

  // Delete variable from system.
  variable_del('MODULENAME_vocab_id');
}

```

Word of comment:

1. I'm still not sure whether the `hook_disable()` would be supposed to do what I put into it, but my understanding is that once a module is disabled, the features installed by it would be supposed to be unavailable too. I'm unsure about the field references - not only do they remain in the system in my code, but once we re-enable the module, the references will not be restored due to new IDs.
2. I'm also not sure how one would make the vocabulary i18n-savvy, meaning - when you would like to install the vocabulary along with translations - vocabularies provide several i18n modes and I'm not in the knowledge how to support them programatically.

This is something I would love to learn from someone.
> 3 votes

---
Tags: taxonomy-terms
---


title: posting a comment on cached page

text:
# Question
Title: posting a comment on cached page
I am a bit confused now - is it normal behavior that posting an anonymous comment on cached page invalidates ALL cached pages for whole site for current anonymous user? Beacouse that is exactly what I am experiencing now. Moreover, current anonymous user is not able to cache pages by visiting them in browser. Is it a bug or is it some sort of a cookie? Thank you for answers.

UPDATE1: I created fresh install, set up a few testing nodes with anonymous commenting enabled and it seems that after submitting comment, drupal adds a cookie. In response headers there shows no-cache on all pages.

UPDATE2: I tried @mikeytown's suggestion and tested out alternative database cache http://drupal.org/project/adbc and it turned out to work ok with anonymous comments. After posting a comment on a cached page - all other precached pages are served from database for current anonymous visitor. This is what I expected as default behavior from core drupal cache. As a sidenote - in addition to that I tested content refresh module http://drupal.org/project/content\_refresh which flushes cache of the page immediately where comment is posted, which turned out to be working pretty good.

Next I tested submitting comments using ajax http://www.test.eotazky.sk/admin/config/content/ajax\_comments . This solution created a session which disabled access to cached pages to current anonymous user. Clearing browser's cache helped.

I tested also other forms on cached pages like poll or closedquestion which use ajax to submit forms and it seems to me that all ajax submitted forms set a session that disable access to cached pages for current anonymous user.

# Answer
> 2 votes
You could give Alternative Database Cache a try. Set the minimum cache lifetime and you should see pages cached within the cache lifetime window not being cleared. Clearing the cache when a comment is saved is default behavior; look at the bottom of the comment\_form\_submit function if you wish to see the call to cache\_clear\_all.

As for the cookie, it is most likely being set because of calls to drupal\_set\_message; also noted is comment\_form\_submit calls user\_cookie\_save

---
Tags: 7, comments, caching, debugging
---


# Question
Title: get same result from db_query() as views query
I know I can get a views result programatically with:

```
$view = views_get_view('view_name');
$view->execute();
$response1 = $view->result;

```

I can get this views sql query from the views ui (views-\>settings-\>show sql). If I place this query in a db\_query() and get the results with:

```
$query = "... "; //long sql query from views ui (in my case with left_joins which reference field collections
$result = db_query($query);
$response2 = $result->fetchAll();  //different than $response1 above?

```

the responses returned from $response1 (from views) and $response2 (from db\_query) are different, namely, the $response2 doesn't contain my field data (or at least not all of it). I'm not sure if this has anything to do with the fact that I'm using field collections. It also seems to not work when using the different fetch() functions. If I run this query through phpmyadmin it produces the same limited results as $response2 (from db\_query) so I'm wondering if views runs something aside from the query. I'd like to find out what the method result() does for the views object, but I'm not sure where that is in the docs or where the function is in my views source. If someone can show me where that is, that would also be helpful.

# Answer
Your view most likely has tags getting attached to it, like `node_access`. Or if you're using grouping on the View that may make a difference in the result property.

Like Nikhil suggested to add that hook somewhere in a custom module just to see what `$query` has in it. And if you have the Devel module installed you can pass that query like so:

```
dpq($query);

```

If it ends up being the case that you have tags being added to the views query and need to mimic that, I'd recommend switching over to the dynamic queries and doing an `$query->addTag(...);`
> 1 votes

# Answer
You could try hook\_views\_query\_alter().

> Alter the query before executing the query.
>
> **Parameters**
>
> $view: The view object about to be processed.
>
> $query: An object describing the query.
> 0 votes

---
Tags: views, database
---


title: Add class to links in delete page

text:
# Question
Title: Add class to links in delete page
I want to add a class to the link in my delete content page, currently the 'delete' button itself is styled because it falls under the styling for input\[type=submit\] in my CSS, but the 'cancel' button is just regular text.

I also have the webform edit page with links for 'clone', 'edit' and 'delete' how would I go about adding classes to these as well?

I don't want to just add a class for all links because thats overkill in my scenario

Thanks

# Answer
> 0 votes
Using the FAPI in a `hook_form_alter()` function:

```
$form['buttons']['delete']['#attributes']['class'] = 'my-class';

```

---
Tags: webforms, navigation, theming
---


# Question
Title: Why do I get "Undefined index: mail en comment_form_validate()"?
Is there a way to fix the notice I get?

> Notice: Undefined index: mail en comment\_form\_validate()
> Notice: Undefined index: homepage en comment\_form\_validate()

This appears in my message area with the errors for comments, only if I enable the development snapshot of the module to display errors or warnings (the configuration say I should turn this off in production), but I'm not sure if this is normal.

Should I ignore this? The default comment module doesn't display this bug, with or without the development snapshot settings working. Does anyone have a suggestion?

# Answer
From your error messages it seems you are calling something like this

```
$form['field_name']['en'][0]['value']

```

Or something like that. Which means the array key "en" is not available. If you are not using languages, then I suggest using `LANGUAGE_NONE` as your key selector.

To prevent these types of messages you should perform an `isset` on the array element to make sure it exists before trying to retrieve a value from it.
> 1 votes

---
Tags: comments, forms
---


title: Importing Group Audience data

text:
# Question
Title: Importing Group Audience data
I have a site using OG7 and created groups to let users to access to some content as per the user membership and concent-type membership as well.

Each user has to belong to a group and I can select that group(s) for him/her in the corresponding Group-Audience list box when adding or editing user information. I have also created content-types which should be attached to a group via Group-Visibility and Group-Audience Fields. When creating content, let's say an Event, I just select in the group-audience list the group I want that event to stick to and also I choose private as the group visibility choice.

Now, the problem is that I need to import a huge number or nodes of different content types, say Events, and each one has to be associated to a group. Currently I just import the content-type data using feeds modules (feeds-import) using a CSV file and once in Drupal I do the group associations by hand. I cannot find a way to import the content-type along with group association while importing the data, also I don't know how to do it directly in the database, I tried but it didnt work. Anyone of you know how to import group-audiences? anyone knows which tables are affected when associating a group to a content-type? Thanks in advance for your time in assisting me.

# Answer
> -1 votes
If you want to import a lot of different content types

you might want to check the Migrate Module out

It supports Organic Groups.

Migrate Documentation

// Maybe this can help you some of the way

Migrate Classes: Location CCK to Address Field

Migrate Extras

This might also give you a clue on how to do it. I know its

Migrate OG

---
Tags: organic-groups, feeds, migrations
---


title: Content authoring and CKEditor

text:
# Question
Title: Content authoring and CKEditor
In my drupal 7 site under Configuration » Content authoring

The following are available: Filtered HTML Full Html Plain text PHP code

However, under Content authoring » CKEditor

Only the following profiles are available: Advanced - Filtered HTML Full - Full HTML

Plain text and the PHP one are missing. Is this normal? Why would this be the case? I am happy to uninstall modules or redo whatever I need to in order for this to be as it should be.

Also, should Filtered HTML and Plain text input formats be editable in the Content authoring section?

# Answer
I believe what you see is normal. In any case, having the WYSIWYG editor for Plain text would result in that the output would display the HTML source code. Using the WYSIWYG editor for PHP input format would probably reformat and destroy the PHP code.
> 0 votes

---
Tags: wysiwyg, files
---


title: Text formats all look the same?

text:
# Question
Title: Text formats all look the same?
I am using the CKeditor and IMCE modules.

When in edit mode, I can see the following text formats in the dropdown menu under the body text area:

* Filtered HTML
* Full HTML
* Plain text
* PHP code

I am logged in as an admin, selecting different text formats from the dropdown menu does not change anything on the page. For example, selecting Plain text, doesn't remove the icons at the top of the text area. What am I doing wrong/missing?

Selecting the PHP code option however does change the appearence of the text area in a sense that the icons disappear.

# Answer
> 0 votes
**This is expected behavior.**

The "Text Format" Select List affects the way drupal parses and displays the data **after it has been saved and is being displayed to the end user**; not the way it is saved nor the way it is displayed on the Node Edit form.

## By default:

**Given Input:**

```
<div>
  <h1>Title</h1>
  <img src="foo.fpg" />
  <?php echo 'bar'; ?>
</div>

```

**"PHP Code" filter output**

```
<div>
  <h1>Title</h1>
  <img src="foo.fpg" />
  bar
</div>

```

**"Full HTML" filter output**

```
<div>
  <h1>Title</h1>
  <img src="foo.fpg" />
</div>

```

## "Filtered HTML" filter output

```
<h1>Title</h1>

```

---
Tags: wysiwyg, files
---


# Question
Title: What is best way to integrate external jQuery plugin?
What is best way to integrate external jQuery plugin? can i use it without libraries module?

# Answer
Perhaps the simplest way is to add it to your theme.info file

e.g, in *mytheme.info*

```
scripts[] = js/jquery.cycle.min.js

```

That will add it globally sitewide.

For more selective control, use drupal\_add\_js

e.g, in *template.php*

```
/**
 * Implements hook_preprocess_html
 */
function mytheme_preprocess_html($variables){

  $valid_path = ''; // TODO, check arg(), current_path() etc.. for valid_path
  if ($valid_path){
    drupal_add_js(drupal_get_path('theme', 'mytheme'). '/js/jquery.cycle.min.js');
  }

}

```

An advanced method is to use the Libraries API and hook\_libraries\_info however any of these methods will work.
> 5 votes

# Answer
A jQuery plugin does not make any difference to any other JavaScript file.

The best way is to use the Drupal module, if there is one available. If the jQuery plugin is popular, there is a chance that there is already one module that incorporates it. That way you don't have to care about testing or upgrades, others do.

If there is no module available in Drupal.org, you can create it yourself. Using the Libraries API is not required but encouraged, so that other future modules can make the best use of it as well.

Use the drupal\_add\_js function in your module or theme to include a JavaScript file.
> 1 votes

---
Tags: 7
---


# Question
Title: How to associate an entity view mode with a path? (Commerce product entity)
I created a view mode for a Commerce product entity with http://drupal.org/project/entity\_view\_mode , now I would like to associate this with a path like myproduct/\[entity\_id\] , so I can attach meta tags and everything else to it.

How would I go about this? Essentially, I am trying to avoid using a product display node for a product entity.

# Answer
> 1 votes
You can add your own entity view path with

hook\_menu

e.g, something like

```
/**
 * Implements hook_menu
 */
function mymodule_menu(){
  $items = array()
  $items['myproduct/%myproduct'] = array(
    'title callback' => 'myproduct_page_title',
    'title arguments' => array(1),
    'page callback' => 'myproduct_page_view',
    'page arguments' => array(1),
    'access callback' => 'myproduct_access',
    'access arguments' => array('view', 1),
  );
}

/**
 * My Product page view callback
 */
function myproduct_page_view($myproduct){
  drupal_set_title($myproduct->title);
  $uri = entity_uri('myproduct', $myproduct);
  // Set the node path as the canonical URL to prevent duplicate content.
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Some example to get entity display
  $view_mode = 'full';
  return myproduct_entity_view($myproduct, $view_mode);
}

```

See node\_menu node/%node for example node view implementation.

Nevertheless, I'd recommend using standard product display nodes for product display.

---
Tags: nodes, commerce, uri, entities
---


# Question
Title: Webform Conditional fields showing by default
I am using the Webform Conditional module to control visibility of some webform components until a checkbox has been ticked.

I found recently that the conditional fields were showing by default (they were not doing so previously).

To add to my confusion, the same set of related fields worked just fine on some nodes but not on others.

Then just as suddenly as the problem appeared, it vanished and my conditional fields began working as expected again.

The site is soon to be LIVE and it be really bad if this problem unexpectedly returns.

**Can anyone offer some opinion as to why that happened, especially if it has happened to you before, and how I can make it more stable, please?**

# Answer
> 0 votes
@kine456: My problems with webform conditional were very occasional. I mean sometimes they were there and other times they just disappeared.

I am also using webform template. On the templates, the conditional fields always worked but not so on the webforms inheriting from the template.

Thankfully, conditional fields have been built into webforms. I downloaded and currently use version#7.x-4.0-alpha6. No problems to report so far

---
Tags: webforms
---


# Question
Title: Would be creating menus totally in views reasonable?
Above question is about two situations:

1. Standard, simple menu with 1-2 levels of depth,
2. Catalog on commerce site, with number of products, next to every item (taxonomy term) of menu.

I can imagine, that counting all nodes related to every taxonomy term every time when site is accessed would kill the server (if there is like hundreds of products), but views have some cache option, don't they? Can they cache their output and make menus views driven reasonable?

# Answer
> 0 votes
Yes. That's the point of views, you should not worry about performance at that point, just build the menu and if later you find that performance is worse than expected start taking a look at this question, there is a big amount of information on views caching. If you need more you can also go here to find more information on caching and performance in general.

---
Tags: 7, views, routes, caching
---


# Question
Title: How to make all webform types collapsed by default?
I just installed a Weboform Conditional module as per @PreritMohan recommendation.

Is there a way to make Textfield, textarea, select option, email, number, date, file types Collapsed by Default ?

I am running Drupal 7.19, webform 7.x-3.18 and webform\_conditional 7.x-1.0-beta1

Also, what values should I put in the Options text area? (Key-value pairs MUST be specified as "safe\_key|Some readable option". Use of only alphanumeric characters and underscores is recommended in keys. One option per line. Option groups may be specified with . \<\> can be used to insert items at the root of the menu after specifying a group.)

SImilarly, what should I put in the Values field under the Conditional Rules section? (List values, one per line, that will trigger this action. If you leave this blank, this component will always display.)

# Answer
Firstly, let me recommend you use Weform 7.x-4.0-alpha6. It has conditionals built into it. Webform Conditional is a great module but I had problems with it.

Options, for select components, take the following format:

```
mr|Mr
ms|Miss
mrs|Mrs
doc|Doc

```

The in-built webforms conditionals are very simple and intuitive. Just add a condition and it will display an interface enabling you to hide/show a component when another component is/is-not a certain value.
> 1 votes

---
Tags: webforms
---


# Question
Title: Webform confirmation message alternate source
How can I override the default webform source for the form submission confirmation message and fetch it from a 'CCK' (I still can't remember what they are now called in D7) element instead?

# Answer
You could use an approach similar to that outlined here: http://drupal.org/node/1245298

Steps:

1. Use hook\_menu to create your confirmation page path
2. Set confirmation page in webform ( e.g path is confirmation/%nid/%sid to pass parameters )
3. Load relevant webform and/or submission in menu callback
4. Display confirmation message as required.
> 2 votes

---
Tags: 7, webforms, forms
---


# Question
Title: How do I replace a comma with a line break using feeds tamper?
When trying to import a feed using Feeds and Feeds tamper, I want to insert a new line at the commas (for displaying address in a nice format).

The screenshot shows what I'm trying to achieve:

The result is \n appears in the output

Why is "\n" being inserted rather than a new line?

# Answer
> 2 votes
The problem is to do with single quoted strings and double quoted strings

```
'\n' !== "\n"

```

So when you enter \n in the settings it's getting passed to the preg function as a single quoted string and in php there's no safe way of changing the string from a single quoted to a double quoted string.

https://stackoverflow.com/questions/5241748/php-convert-single-quoted-string-to-double-quoted

Solved this using a plugin,

first make a custom module that adds a ctools feeds\_tamper plugin directory

```
/**
 * @file my_feeds_tamper.module
 */
/**
 * Implements hook_ctools_plugin_directory().
 */
function my_feeds_tamper_ctools_plugin_directory($owner, $plugin) {
  if ($owner == 'feeds_tamper') {
    return 'plugins';
  }
}

```

Then within that module directory create the plugins directory and add the plugin code

```
/**
 * @file plugins/comma_to_newline.inc
 * replaces commas with comma linebreak on import
 */

/**
 * defines the ctools plugin
 */
$plugin = array(
  'form' => 'comma_to_newline_form',
  'callback' => 'comma_to_newline_callback',
  'name' => 'Comma to new line',
  'multi' => 'direct',
  'category' => 'Text',
);

/**
 * Even though there are no settings we still need the form
 */
function comma_to_newline_form($importer, $element_key, $settings) {
  $form = array();
  return $form;
}

/**
 * replaces a comma (followed by 0 or more spaces) with
 * a comma and a linebreak
 */
function comma_to_newline_callback($source, $item_key, $element_key, &$field, $settings) {
  $field = preg_replace("/, */", ",\n", $field);
}

```

I could have made a clone of the preg replace feeds tamper plugin, that replaces \n with "\n", for a more flexible (configurable solution)

# Answer
> 1 votes
Check the field you are inserting the text into is using plain text and not any filter.

---
Tags: feeds
---


# Question
Title: Display user picture in User Relationship block
In my social networking site, i have provided for users to be able to forge relationships between themselves using the User relationship module. This is working fine. I am creating a tab using quicktab to display the user their relations when he or she clicks on them. I assign my tab the block value : My Relationships: All relationships (user\_relationship\_blocks:my-all) which is already available in DRUPAL. However it does not show the picture of the user with whom the relationship is. I thought of using views but in views all relationship are showed. What i need is something like this:

**Followers**

User A (A's Picture) User B (B's Picture)

**Following**

User C (C's Picture) User D (D's Picture)

If this can be done using views or any other way, please advice...thanks

Edit/Update:

I tried using the default block provided: **My Relationships: All relationships (user\_relationships\_blocks:my-all)** This is under structure/blocks...I just enable it and display it...Its showing:

Now i just need that the user picture also appears besides their name...Please advice/help...DO i have to do some changes in this block, if so, then just get me on starting line, i will carry it forward :) Thanks

# Answer
> 1 votes
$view = new view(); $view-\>name = 'user\_freinds'; $view-\>description = 'Shows someone\\'s related users'; $view-\>tag = ''; $view-\>base\_table = 'user\_relationships'; $view-\>human\_name = 'User freinds'; $view-\>core = 0; $view-\>api\_version = '3.0'; $view-\>disabled = FALSE; /\* Edit this to true to make a default view disabled initially \*/

/\* Display: Defaults \*/ $handler = $view-\>new\_display('default', 'Defaults', 'default'); $handler-\>display-\>display\_options\['use\_more\_always'\] = FALSE; $handler-\>display-\>display\_options\['access'\]\['type'\] = 'none'; $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'\] = 'mini'; $handler-\>display-\>display\_options\['pager'\]\['options'\]\['items\_per\_page'\] = '10'; $handler-\>display-\>display\_options\['pager'\]\['options'\]\['offset'\] = '0'; $handler-\>display-\>display\_options\['pager'\]\['options'\]\['id'\] = '0'; $handler-\>display-\>display\_options\['style\_plugin'\] = 'grid'; $handler-\>display-\>display\_options\['style\_options'\]\['grouping'\] = ''; $handler-\>display-\>display\_options\['style\_options'\]\['columns'\] = '5'; $handler-\>display-\>display\_options\['row\_plugin'\] = 'fields'; $handler-\>display-\>display\_options\['row\_options'\]\['inline'\] = array( 'name\_1' =\> 'name\_1', ); $handler-\>display-\>display\_options\['row\_options'\]\['separator'\] = ', '; /\* No results behavior: Global: Text area \*/ $handler-\>display-\>display\_options\['empty'\]\['area'\]\['id'\] = 'area'; $handler-\>display-\>display\_options\['empty'\]\['area'\]\['table'\] = 'views'; $handler-\>display-\>display\_options\['empty'\]\['area'\]\['field'\] = 'area'; $handler-\>display-\>display\_options\['empty'\]\['area'\]\['empty'\] = TRUE; $handler-\>display-\>display\_options\['empty'\]\['area'\]\['content'\] = 'لا يوجد محتوى'; $handler-\>display-\>display\_options\['empty'\]\['area'\]\['format'\] = 'plain\_text'; /\* Relationship: User relationships: Requestee user \*/ $handler-\>display-\>display\_options\['relationships'\]\['requestee\_id'\]\['id'\] = 'requestee\_id'; $handler-\>display-\>display\_options\['relationships'\]\['requestee\_id'\]\['table'\] = 'user\_relationships'; $handler-\>display-\>display\_options\['relationships'\]\['requestee\_id'\]\['field'\] = 'requestee\_id'; /\* Relationship: User relationships: Requester user \*/ $handler-\>display-\>display\_options\['relationships'\]\['requester\_id'\]\['id'\] = 'requester\_id'; $handler-\>display-\>display\_options\['relationships'\]\['requester\_id'\]\['table'\] = 'user\_relationships'; $handler-\>display-\>display\_options\['relationships'\]\['requester\_id'\]\['field'\] = 'requester\_id'; /\* Relationship: User relationships: RTID \*/ $handler-\>display-\>display\_options\['relationships'\]\['rtid'\]\['id'\] = 'rtid'; $handler-\>display-\>display\_options\['relationships'\]\['rtid'\]\['table'\] = 'user\_relationships'; $handler-\>display-\>display\_options\['relationships'\]\['rtid'\]\['field'\] = 'rtid'; /\* Field: User relationship types: Plural name \*/ $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['id'\] = 'plural\_name'; $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['table'\] = 'user\_relationship\_types'; $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['field'\] = 'plural\_name'; $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['relationship'\] = 'rtid'; $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['label'\] = ''; $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['exclude'\] = TRUE; /\* Field: User: Picture \*/ $handler-\>display-\>display\_options\['fields'\]\['picture'\]\['id'\] = 'picture'; $handler-\>display-\>display\_options\['fields'\]\['picture'\]\['table'\] = 'users'; $handler-\>display-\>display\_options\['fields'\]\['picture'\]\['field'\] = 'picture'; $handler-\>display-\>display\_options\['fields'\]\['picture'\]\['relationship'\] = 'requestee\_id'; $handler-\>display-\>display\_options\['fields'\]\['picture'\]\['label'\] = ''; $handler-\>display-\>display\_options\['fields'\]\['picture'\]\['element\_label\_colon'\] = FALSE; /\* Field: User: Name \*/ $handler-\>display-\>display\_options\['fields'\]\['name'\]\['id'\] = 'name'; $handler-\>display-\>display\_options\['fields'\]\['name'\]\['table'\] = 'users'; $handler-\>display-\>display\_options\['fields'\]\['name'\]\['field'\] = 'name'; $handler-\>display-\>display\_options\['fields'\]\['name'\]\['relationship'\] = 'requestee\_id'; $handler-\>display-\>display\_options\['fields'\]\['name'\]\['label'\] = ''; /\* Sort criterion: User relationship types: Plural name \*/ $handler-\>display-\>display\_options\['sorts'\]\['plural\_name'\]\['id'\] = 'plural\_name'; $handler-\>display-\>display\_options\['sorts'\]\['plural\_name'\]\['table'\] = 'user\_relationship\_types'; $handler-\>display-\>display\_options\['sorts'\]\['plural\_name'\]\['field'\] = 'plural\_name'; $handler-\>display-\>display\_options\['sorts'\]\['plural\_name'\]\['relationship'\] = 'rtid'; /\* Contextual filter: User relationships: Requester user \*/ $handler-\>display-\>display\_options\['arguments'\]\['requester\_id'\]\['id'\] = 'requester\_id'; $handler-\>display-\>display\_options\['arguments'\]\['requester\_id'\]\['table'\] = 'user\_relationships'; $handler-\>display-\>display\_options\['arguments'\]\['requester\_id'\]\['field'\] = 'requester\_id'; $handler-\>display-\>display\_options\['arguments'\]\['requester\_id'\]\['default\_action'\] = 'default'; $handler-\>display-\>display\_options\['arguments'\]\['requester\_id'\]\['exception'\]\['title\_enable'\] = TRUE; $handler-\>display-\>display\_options\['arguments'\]\['requester\_id'\]\['default\_argument\_type'\] = 'user'; $handler-\>display-\>display\_options\['arguments'\]\['requester\_id'\]\['default\_argument\_options'\]\['user'\] = FALSE; $handler-\>display-\>display\_options\['arguments'\]\['requester\_id'\]\['summary'\]\['format'\] = 'default\_summary'; $handler-\>display-\>display\_options\['arguments'\]\['requester\_id'\]\['specify\_validation'\] = TRUE; $handler-\>display-\>display\_options\['arguments'\]\['requester\_id'\]\['validate'\]\['type'\] = 'numeric'; $handler-\>display-\>display\_options\['filter\_groups'\]\['groups'\] = array( 1 =\> 'AND', 2 =\> 'AND', ); /\* Filter criterion: User relationships: Relationship status \*/ $handler-\>display-\>display\_options\['filters'\]\['approved'\]\['id'\] = 'approved'; $handler-\>display-\>display\_options\['filters'\]\['approved'\]\['table'\] = 'user\_relationships'; $handler-\>display-\>display\_options\['filters'\]\['approved'\]\['field'\] = 'approved'; $handler-\>display-\>display\_options\['filters'\]\['approved'\]\['value'\] = '1'; $handler-\>display-\>display\_options\['filters'\]\['approved'\]\['group'\] = 1; $handler-\>display-\>display\_options\['filters'\]\['approved'\]\['expose'\]\['operator'\] = FALSE;

/\* Display: Block by type \*/ $handler = $view-\>new\_display('block', 'Block by type', 'block\_1'); $handler-\>display-\>display\_options\['defaults'\]\['use\_ajax'\] = FALSE; $handler-\>display-\>display\_options\['use\_ajax'\] = TRUE; $handler-\>display-\>display\_options\['defaults'\]\['hide\_admin\_links'\] = FALSE; $handler-\>display-\>display\_options\['block\_description'\] = 'Display user\\'s relationships grouped by relationship type';

/\* Display: Block by user \*/ $handler = $view-\>new\_display('block', 'Block by user', 'block\_2'); $handler-\>display-\>display\_options\['defaults'\]\['title'\] = FALSE; $handler-\>display-\>display\_options\['title'\] = 'Related users'; $handler-\>display-\>display\_options\['defaults'\]\['hide\_admin\_links'\] = FALSE; $handler-\>display-\>display\_options\['defaults'\]\['style\_plugin'\] = FALSE; $handler-\>display-\>display\_options\['style\_plugin'\] = 'list'; $handler-\>display-\>display\_options\['style\_options'\]\['grouping'\] = 'name'; $handler-\>display-\>display\_options\['defaults'\]\['style\_options'\] = FALSE; $handler-\>display-\>display\_options\['defaults'\]\['row\_plugin'\] = FALSE; $handler-\>display-\>display\_options\['row\_plugin'\] = 'fields'; $handler-\>display-\>display\_options\['defaults'\]\['row\_options'\] = FALSE; $handler-\>display-\>display\_options\['defaults'\]\['fields'\] = FALSE; /\* Field: User relationship types: Plural name \*/ $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['id'\] = 'plural\_name'; $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['table'\] = 'user\_relationship\_types'; $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['field'\] = 'plural\_name'; $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['relationship'\] = 'rtid'; $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['label'\] = ''; $handler-\>display-\>display\_options\['fields'\]\['plural\_name'\]\['exclude'\] = TRUE; /\* Field: User: Name \*/ $handler-\>display-\>display\_options\['fields'\]\['name'\]\['id'\] = 'name'; $handler-\>display-\>display\_options\['fields'\]\['name'\]\['table'\] = 'users'; $handler-\>display-\>display\_options\['fields'\]\['name'\]\['field'\] = 'name'; $handler-\>display-\>display\_options\['fields'\]\['name'\]\['relationship'\] = 'requestee\_id'; $handler-\>display-\>display\_options\['fields'\]\['name'\]\['label'\] = ''; $handler-\>display-\>display\_options\['fields'\]\['name'\]\['exclude'\] = TRUE; /\* Field: Broken/missing handler \*/ $handler-\>display-\>display\_options\['fields'\]\['updated\_at'\]\['id'\] = 'updated\_at'; $handler-\>display-\>display\_options\['fields'\]\['updated\_at'\]\['table'\] = 'user\_relationships'; $handler-\>display-\>display\_options\['fields'\]\['updated\_at'\]\['field'\] = 'updated\_at'; $handler-\>display-\>display\_options\['fields'\]\['updated\_at'\]\['label'\] = 'Added'; $handler-\>display-\>display\_options\['fields'\]\['updated\_at'\]\['exclude'\] = TRUE; /\* Field: User relationship types: Name \*/ $handler-\>display-\>display\_options\['fields'\]\['name\_1'\]\['id'\] = 'name\_1'; $handler-\>display-\>display\_options\['fields'\]\['name\_1'\]\['table'\] = 'user\_relationship\_types'; $handler-\>display-\>display\_options\['fields'\]\['name\_1'\]\['field'\] = 'name'; $handler-\>display-\>display\_options\['fields'\]\['name\_1'\]\['relationship'\] = 'rtid'; $handler-\>display-\>display\_options\['fields'\]\['name\_1'\]\['label'\] = ''; $handler-\>display-\>display\_options\['block\_description'\] = 'Display user\\'s relationships grouped by user';

# Answer
> 0 votes
Download and enable the module UR-Views

then you will see a view called user-friends with two blocks

1-block by type 2-block by user

select the first and so you could make your own content-panes or blocks for further needs

---
Tags: 7, views, users
---


# Question
Title: redirect multiple nodes on same page in core search results
I'm using drupal's core search module with pathauto module for URL aliasing. I have one testimonials page where different contents under testimonials category get display in this page. Now, in the search results one of these content get display and lead to `node/35` and `node/36` in same search result page.

In URL alias I tried to give /testimonials in each content but it gives error that this URL alias is already in use.

I want to redirect this link on the testimonials page (abcd.com/testimonials). Means

```
node/35 -> abcd/testimonials
node/36 -> abcd/testimonials
node/37 -> abcd/testimonials

```

How can I achieve this? Any suggestions or links will be appreciate.

Thanks in advance...

# Answer
> 1 votes
Finally got solution, but still I think this is not right way to achieve this. First enable the Pathauto module and make some pattern for particular content type. Then install the Redirect module. You can find URL Redirects under URL alias option in edit mode of content type.

click on Add URL redirect and add your desire path (in my case path to page /tesimonials). Thats it. It will redirect particular node to your given redirect path.

Hope this will help you...

# Answer
> 0 votes
Take a look at Customize the search results page. Check for available variables.

also search-results.tpl.php to alter the display.

# Answer
> 0 votes
Hi just write a code block in in template preprocessor or hook\_init() function

```
if((arg(1) = 'node') && (in_array(arg(2), array(35,36,37)))) {
  drupal_goto('abcd/testimonials');
}

```

Hope it will help you.

---
Tags: 7, search, redirection, path-aliases
---


title: Tabledrag with locked children

text:
# Question
Title: Tabledrag with locked children
We use Drupal's tabledrag component in one of our interfaces and we've got this requirement we don't know how to solve.

Basically, we have a tree structure with elements of 2 types - let's call them A and B.

An element of type A can be moved to any location in the tree (we use weight and parent-child relationships). An element of type B **is always a child of an A, and cannot be moved to another A**. It is locked under it's parent A. However, **it can be sorted with sibling As**.

So for a tree like:

```
A1
\- A2
 - B1
 - A3
   \- B2
    - A4
    - B3
    - B4

```

We can move A3 up to be a child of A2, and all it's children (B2..B4) will move along (like normal). However, **B1 can only be moved up and down** (in regards to A2 and A3), as we can change it's weight, but cannot change it's parent: **it's locked under A1**.

I have searched for a while, but have not found any examples of this. Is this even possible with Drupal's core tabledrag ?

# Answer
Ok, found it.

If one includes this code, it will prevent all items with a class "tabledrag-parent-locked" from being dragged into another group, while still being orderable with their siblings.

This code uses a CSS class of 'parent' to target the parent relation field. The actual CSS class would obviously depend on what CSS class you pass to `drupal_add_tabledrag()`.

```
/**
 * @file
 * Override some Tabledrag functionality.
 */

/**
 * If the dragged row has a class of 'tabledrag-parent-locked', check the rows with which it might get swapped.
 * If the row it gets swapped with has a different  parent, block the swap by returning false.
 * This will prevent the locked child from being dragged to another parent.
 *
 * @override Drupal.tableDrag.row.isValidSwap
 */
// Keep the original implementation - we still need it.
Drupal.tableDrag.prototype.row.prototype._isValidSwap = Drupal.tableDrag.prototype.row.prototype.isValidSwap;
Drupal.tableDrag.prototype.row.prototype.isValidSwap = function(row) {
  if (this.indentEnabled && $(this.element).hasClass('tabledrag-parent-locked')) {
    var nextRow;
    if (this.direction == 'down') {
      nextRow = $(row).next('tr').get(0);
    }
    else {
      nextRow = row;
    }

    if (nextRow && $('.parent', this.element).val() !== $('.parent', nextRow).val()) {
      return false;
    }
  }

  // Return the original result.
  return this._isValidSwap(row);
}

/**
 * If the dragged row has a class of 'tabledrag-parent-locked', disable the indentation for the duration of
 * the drag. Store the old indentation setting in _indentEnabled.
 *
 * @override Drupal.tableDrag.dragRow
 */
// Keep the original implementation - we still need it.
Drupal.tableDrag.prototype._dragRow = Drupal.tableDrag.prototype.dragRow;
Drupal.tableDrag.prototype.dragRow = function(event, self) {
  if (self.rowObject && $(self.rowObject.element).hasClass('tabledrag-parent-locked')) {
    if (self.indentEnabled) {
      self._indentEnabled = true;
      self.indentEnabled = false;
    }
  }

  return self._dragRow(event, self);
}

/**
 * Restore the original indentation setting, if needed.
 *
 * @override Drupal.tableDrag.dragRow
 */
// Keep the original implementation - we still need it.
Drupal.tableDrag.prototype._dropRow = Drupal.tableDrag.prototype.dropRow;
Drupal.tableDrag.prototype.dropRow = function(event, self) {
  if (self._indentEnabled !== null) {
    self.indentEnabled = true;
    self._indentEnabled = null;
  }

  return self._dropRow(event, self);
}

```
> 2 votes

---
Tags: javascript
---


# Question
Title: I have a tab in mysite.com/user which I don't know where it's coming from?
I have a tab in mysite.com/user called "Evaluaciones" but I don't know why is there. The link for this tab is `user/1/webform-submissions-por-user` then I guess it is generated by the webform module, but I already disabled this module and the tab is stil there.

How can I trace it? How Can I remove it?

# Answer
You can use Tab Tammer module to hide it.

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
> 1 votes

# Answer
Its coming from the webform module. I believe if you turn off the ability to allow users to view previous submissions it will go away.
> 2 votes

# Answer
You can hide using hook\_menu\_alter() hook.

```
function menualter_menu_alter(&$items) {
unset($items['user/%user/webform-submissions-por-user']);
}

```
> 1 votes

---
Tags: users
---


title: How to remove a region from omega grid

text:
# Question
Title: How to remove a region from omega grid
I need to have a full screen image carousel and I'm using a sub theme of omega.

Ideally, I'd like to render the image through a custom module which I have put in the branding region. Because the images needs to be full width I need to render the branding region outside the grid.

What's the best way to go about removing the branding region from the grid and rendering it outside?

Thanks,

# Answer
This is actually pretty complicated. The major problem is that both the region and the zone that it is in have the grid classes on them.

You need to implement a `template_process_zone()` in your theme, and then remove the grid classes from $variables\["content\_attributes\_array"\]\["class"\]. You then need to implement a `template_process_region()` and remove them from `$variables["classes_array"]`.

Any other regions in that zone will then have grid problems, and the containing zone won't have a grid container definition.

Your other option is to use CSS to override the grid definitions for the zone and region. Depending on your site and the theme, you may be able to get away with using a full zone wrapper around things, and then using positioning on the region to make it appear full width.
> 1 votes

---
Tags: theming
---


# Question
Title: How to make 2 or 3 xml sitemaps in drupal for example for different taxonomies?
I need to generate 4 sitemaps which differ in content included in them according to certain taxonomies! XML sitemap can generate one sitemap. When I try to generate other it displays error: A sitemap with the same context already exists.

# Answer
I suggest installing the Views Data Export module. It will allow you to create XML pages from your taxonomy and as many as you want.

I would create one view and 4 page displays with the varying filters to generate your pages. Then change the output to XML.

I looked over the XML Sitemap, and the error you are experiencing seems to be something they are trying to troubleshoot. You can follow along there, or try some of their methods.
> 4 votes

---
Tags: taxonomy-terms, xml-sitemap
---


# Question
Title: create a menu based on the parent of a drupal book
I've been working with the book module bundled with drupal 7 and have a question. Say i have a book x, and this book contains 4 pages which each have 2 children giving a structure like this:

* Book x
    + Subheading 1
        - Page 1
        - Page 2
    + Subheading 2
        - Page 1
        - Page 2
    + Subheading 3
        - Page 1
        - Page 2
    + Subheading 4
    - Page 1
        - Page 2

What I want to do is create a menu that will sit at the bottom of the page which displays links based on these 4 subheadings, i.e. if you were viewing Subheading 1 the menu would display links to the 2 child pages of the subheading. Is this possible?

# Answer
> 0 votes
I figured out my issue, turns out my theme\_menu\_link function was hiding the book menu block. Once I realised this I placed the block alongside my main menu on the block pages, and used my theme\_menu\_link to style it.

---
Tags: routes, nodes, navigation
---


# Question
Title: Complicated Views query relationships (for me)
So here is what I am trying to figure out how to do. I have a content type of Users and I have a content type of User Programs (Outreach Program, Coaching Program, AA Program, etc) these are being linked by the Entity Reference module as a field on the User content type.

So when I am editing a User, I select the different programs that user is linked to (via the Entity Reference Module). The User Programs content type has taxonomy for the different program categories (Central Sector, North Sector, Western Sector, etc) and you can select multiple categories on the User Programs Node.

What I want to do in Views is this:

```
 Contextual filter: (User NID) = 40

 User: John Doe

 Programs Related to User --

   Central Sector (Taxonomy) -
     Outreach Program

   North Sector (Taxonomy) -
     Coaching Program
     AA Program

```

I know how to do simple views, but this one is starting to go out of my comfort zone, and I am getting kind of confused on how I could do something like this. I've tried an EVA view, but I am not too sure if that's what I am supposed to use. Any help would be greatly appreciated!

TIA!

# Answer
> 0 votes
1. Create your View looking at User records.
2. Add a Relationship under the Advanced section to link to your Taxonomy.
3. You then may have to use some Grouping, or Aggregation

Does that help?

# Answer
> 0 votes
Thanks for the tip with the Aggregation method. I am trying it right now, but the User is getting duplicated a few times, so I have to figure out how to limit that, but I think we're on the right track.

I am trying to simplify this by just doing a vanilla drupal view with Articles being the main query, and querying basic pages, and getting taxonomy terms from the basic pages.

```
Article 1 -
 Basic Page 1
  page tax 1
  page tax 2
  page tax 3

 Basic Page 2
  page tax a
  page tax b

Article 2 -
 Basic Page 1
  page tax I
  page tax II
  page tax III

 Basic Page 2
  page tax 1
  page tax 2

```

Seems like a weird query I know, but I am trying to simplify this process

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


# Question
Title: Lightweight way to check to see if another user has a role
There are lots of examples of seeing if the current user has a particular role. I need lightweight function to see if another user has a particular role.

For comments, I want to highlight comments from users who have a particular role, "Guest Blogger". Using `hook_preprocess_comment(&$variables)` I can load up each user using:

```
$user_fields = user_load($variables['comment']->uid);

```

But this seems rather heavy. All I need to do is see if the user has a role, not load up the entire user object.

Can someone help me out with a function or a query where I pass in the uid and the function/query passes back an array of roles?

# Answer
Something like:

```
function MYMODULE_get_user_roles($uid) {
  $roles = &drupal_static(__FUNCTION__, array());

  if (!isset($roles[$uid])) {
    $query = db_select('role', 'r')
      ->fields('r', array('rid', 'name'))
      ->condition('ur.uid', $uid);

    $query->join('users_roles', 'ur', 'ur.rid = r.rid');

    $roles[$uid] = $query->execute()->fetchAllKeyed();
  }

  return $roles[$uid];
}

```

You might want to add static caching to that if you plan to call it more than once for any single user during a single page build.
> 1 votes

---
Tags: users
---


title: Commerce editing content for products

text:
# Question
Title: Commerce editing content for products
i have a project that is based on a normal drupal, and i have added commerce modules to it, but i can't find the module or setting that changes the way of editing the product from:

to:

can anyone point me to the right direction?

# Answer
> 4 votes
I believe that functionality is provided by the Inline Entity Form module

> Provides a widget for inline management (creation, modification, removal) of referenced entities.
>
> The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form.

Edit: In fact it definitely is, this is an image from the module page:

---
Tags: nodes, commerce
---


# Question
Title: How do I install the Spark distribution using only Drush?
How do I fire up the Spark Distribution via a drush command?

# Answer
> 0 votes
From comments:

Clive: `drush make build-spark.make ~/Sites/spark` \- Building Spark from Drush Make yourself

---
Tags: drush
---


# Question
Title: Use redirect after content creating and use $node
I modified my submit handler to be redirected to a "thank you" page after creating some content. So far so good.

But I want to use some data of the node just created, so how can I transfer the `$node`-data of the just created node to my thank you page?

I created a new block to be shown only on the thank you page and I want to show some `$node`-data in my block...

```
function mymodule_block_view($delta = '') {
  switch ($delta) {
    case 'your_block':
      $block['subject'] = 'Share by mail';
      $block['content'] = mymodule_sharebutton();
      break;
  }

  return $block;
}

function mymodule_sharebutton() {
  $output = '<a href="">share</a>';

  return $output;
}

```

I already tried with passing `$node`, `$form`, `$form_state`,... but with no luck.

# Answer
> 0 votes
Use arg(1); - (nid of the current node) in the hook\_block\_view and pass it in the link

```
function mymodule_block_view($delta = '') {
  switch ($delta) {
    case 'your_block':
      $nid = arg(1);
      $block['subject'] = 'Share by mail';
      $block['content'] = '<a href="">share?nid='.$nid.'</a>';
      break;
  }
  return $block;
}

```

Once you do that, you can make your thank\_you page react on the nid argument by loading the node:

```
$node = node_load($nid);

```

and extracting from it whatever you need

---
Tags: 7, forms
---


title: Adding static images to theme

text:
# Question
Title: Adding static images to theme
In `page.tpl.php`, I add some static images by using :

```
$bolo = path_to_theme() . '/images/bolo.gif';
....
<img src="<?php print $bolo ?>" alt="bolo" width="71" height="125">

```

How I can do the same by using a preprocess function (like `theme_image()` for example) in `template.php` and calling the (image)variable in `page.tpl.php` ? It seems easy, but I can't perform it. Thanks

Bolo

# Answer
> 0 votes
You can to use `hook_prorocess_page` for this.

In the theme's template.php file, add the following function (make sure it doesn't exist. if so, append the function content to the existing file)

```
function THEMENAME_preprocess_page(&$vars) {
  $image = ... // Generate your image's img tag here, optionally wrap with some DIVs.
  $vars['my_image'] = $image;
}

```

Now, you can access this variable as `$my_image`.

---
Tags: theming, media
---


# Question
Title: Display a message when no results are returned from an exposed filter
How do I add a message, or change the view's behaviour when there is no result returned from a view's exposed filter?

# Answer
> 9 votes
When you edit your view (D7), under 'Advanced' you will find an item labelled 'No Results Behavior' which gives you a selection of options. The usual is to select 'Global Text Area' and return a no results found message.

---
Tags: views, search
---


# Question
Title: (How) can I Create products by the square foot?
I have a product that I need to sell by the square foot, where the customer would enter the length and width, and the number of sq ft would be the unit amount on the product line. That unit number should then only be changed by updating the length/width fields (not by direct customer entry). Is there a commerce module or combination of mods for that. I've tried commerce custom product, and tinkered with rules, but can't make it work. Maybe I need a custom module? Any advice appreciated.

# Answer
There isn't a complete solution, but there's a start and an open issue to make it do exactly what you need. I wrote a Physical Fields module that defines a dimensions field you can use to collect the length and width via a line item field exposed to the Add to Cart form. The issue is the dimensions field right now *only* supports collecting all three dimensions: length, width, and height. It needs to be updated to support using a subset of the dimensions, and I've just updated the appropriate issue that you can follow here.

Once you have that field on your line item type and have exposed it to the Add to Cart form, customers will be able to specify their dimensions when they add the product to the cart. With this data in fields on the line item, you can then make calculations based on the value of the field using Rules (or a custom Rules action). You can create a new data value by multiplying the length times the width (should be possible in Rules) and then set the product price accordingly. In such a case, I'd probably make the price of the product be the "sq. ft." price and then just multiply that times the square footage I calculate.
> 1 votes

---
Tags: commerce
---


title: encrypted fields

text:
# Question
Title: encrypted fields
I am using Services to collect data from an application. I will store each user's key on their drupal profile, and want to match that key against a key submitted through services. I would like to store the user key as an encrypted field on the user's profile, then match that to the one being submitted. I'm looking for a contrib module that provides:

* field encryption
* a simple way to match (yes/no) the encrypted field against another entity

Any suggestions?

The closest I've found so far is http://drupal.org/project/encrypt

# Answer
> 2 votes
Look into Encrypted Settings Field to store your field.

> This module adds the "encrypted settings" field through Field API, which has the following two features:
>
> The field can be encrypted before saving to the database
>
> The field can be validated to follow INI format.
>
> This module is ideal to save credential settings information, such as a "Credit Card" field to add to users' profile.

You will likely not find a module that relates and verifies this against another field ... that business logic specific to your application.

---
Tags: 7, entities, services
---


# Question
Title: Attach a submit handler on an ajax-y form (hook_media_format_form_prepare_alter)
I'm working with media 7.x-2.0-unstable7.

I am attempting to adjust the behavior of the media module's wysiwyg embedded image attribute editor modal dialog (c.f. http://drupal.org/node/835516). It was pretty easy to adjust the contents of this dialog with hook\_media\_format\_form\_prepare\_alter (see: http://drupal.org/node/835516#comment-7075374), and I expected that it would be easy to add a submit handler, and Drupal would jump through the hoops for me to insure that it was called at the right time. If this service is offered, I can't seem to figure out how to make it work.

The only other place I can find that uses hook\_media\_format\_form\_prepare\_alter is media\_crop, and it includes its own ajax POST to send its data back to the server. It's not clear to me how the standard media\_format\_form saves its data. It looks like ctools handles calling the submit handler for similar form, media\_file\_edit\_modal (called for editing image metadata fields for media image files that are entity fields). Is there something similar for hook\_media\_format\_form\_prepare\_alter, or do I have to write my own Javascript and my own data-receive menu, like media\_crop does?

media.api.php did not help clarify.

# Answer
> 1 votes
It always pays to test your assumptions. The media\_format\_form only saves metadata edits into the embedded media tag in the edit text contents; the alt and title information attached to the file object are not adjusted. There is an advantage to this, in that different instances of the same picture embedded in different locations can also have different alt and title text. Unfortunately, though, it also means that if an image is uploaded via the embedded media image tool in a wysiwyg editor, then the alt and title fields will be empty the next time that image is used, whether it is used as an embedded image or attached to a media image file field.

It would be helpful if media\_format\_form would save metadata changes back to the file object, just as media\_file\_edit\_modal does. However, it appears that at the moment, that capability is not present in the code.

---
Tags: forms, media
---


# Question
Title: Swap prices in Ubercart based on Attribute price
I am implementing a down-payment/multi-pay option on a higher-priced product, and I want to offer it as an attribute. Let's say the product costs $1,000... I want to be able to offer it at full price like a normal product, but also offer the customer the ability to only pay $500 at the time of purchase. If they choose that $500 option/attribute, their card will be charged for five additional monthly payments ($100 each plus a service fee amount, via the UC Recurring Payments and Subscriptions module) so that they pay the full amount plus fees over that time period.

By default, the Ubercart product attributes simply add their dollar amount to the dollar amount of the product. How can I use the attribute dollar amount ***instead of*** the product's dollar amount when that attribute is selected? One workaround would be to add a "no, I want to pay the entire amount now" attribute and price it with the normal product price, but that would not be ideal.

Thanks!

# Answer
Looks like the Ubercart Ajax Attribute Calculations module will do the trick, at least somewhat... it will change out my product's "$0" base price for the attribute price, but it still does not technically "swap" the prices.
> 2 votes

---
Tags: 6, ubercart
---


title: Editing fields presented in a view

text:
# Question
Title: Editing fields presented in a view
I am looking for a module that allows fields to be edited that are presented\<, preferably by a view. Basically what I am trying to acheive is as follows:

1. I have a content type as Meter Readings
2. Meter reading prepopulates by entity reference\_prepopulate to a parent project ie.Building.
3. Idea is that a building has a meter say Electricity meter that records electricity readings(by Meter Readings Content type) that is presented in a view

I want to add meter readings in the view itself and not let the user to go to another screen,

Any module to do this? Any references would be of great help.

# Answer
One option is to use the field collection. and field collection views

This would automatically create the add edit and delete links to those who have permission to do so both in views as well as node view. It will popup a nice box to make the changes or add items.

I followed the following steps.

1. Added a content type called Meter Reading
2. Added a field collection called Reading with widget embedded made its value as unlimited.
3. Add a field to the field collection.
4. Added a content of the type Meter Reading without entering anything in the reading.

Now when you visit the newly created content you would get something like below image.

Here you will notice the add link this and when you click that you would get a popup something like in the below screenshot.

In the popup you can enter the readings.

This is what I get after entering couple of readings.

By the way you can add field collection with in field collection and it would work the same. So in your case instead creating a content type called Meter reading you can create a field collection called meter reading and then add a field collection with in that called readings and with in that add a field called Reading.

So your entire page would look like this
> 5 votes

# Answer
am looking around D7 options myself- sounds like editable fields would suit your need to - shame it is only alpha - http://drupal.org/project/editablefields
> 3 votes

---
Tags: 7, views
---


# Question
Title: Does anyone know of a module like "Artsy Editor" for Drupal?
I'm looking for a writing interface similar to Artsy Editor which is built for Wordpress.

It's a "distraction-free" wysiwyg that I need for a client's site and thus far I've not been able to find one.

Does anyone have suggestions on an existing editor that I can use, or a way to use existing modules to achieve the same effect?

I'm really looking for a way to have a wysiwyg style interface similar to the new "notes" in the new version of basecamp.

The site in question is a Drupal 7 site.

# Answer
There's no module for Artsy Editor.
But if you mean inline editor, you can use **Edit** for Drupal 7 and 8 - In-place editing for fields on any entity. Including WYSIWYG editing powered by CKEditor or Aloha.
"Edit" is part of Spark \- Drupal distribution which aims to be "the Pressflow of Drupal authoring experience
> 3 votes

---
Tags: 7, wysiwyg
---


title: Menu management options in Drupal 7

text:
# Question
Title: Menu management options in Drupal 7
On node add/edit form, when the navigation menu grows, it becomes harder to find the menu parent in which we want to add the node link. Is there any module through which it becomes little easier?

Secondly, on the menu management page where it displays all the menu items, is it possible to drag multiple menu items? Is there any menu management module like the Taxonomy manager module?

# Answer
Hierarchical Select \- with "hs\_menu" submodule this module allow built "hierarchical" select of parent for menu.
> 1 votes

---
Tags: routes, nodes
---


# Question
Title: Remove <div> tag after form tag in user register form Drupal 7
I have added this code to template.php

```
function mytheme_theme(&$existing, $type, $theme, $path){
  $hooks = array();
   // Make user-register.tpl.php available
  $hooks['user_register_form'] = array (
     'render element' => 'form',
     'path' => drupal_get_path('theme','mytheme'),
     'template' => 'user-register',
     'preprocess functions' => array('mytheme_preprocess_user_register_form'),
  );
  return $hooks;
}

function mytheme_preprocess_user_register_form(&$vars) {
  $args = func_get_args();
  array_shift($args);
  $form_state['build_info']['args'] = $args;
  $vars['form'] = drupal_build_form('user_register_form', $form_state['build_info']    ['args']);
}

```

also I have created user-register.tpl.php with this

```
<span>test</span>

```

but the result is

```
<form class="user-info-from-cookie" enctype="multipart/form-data" action="/user/register" method="post" id="user-register-form" accept-charset="UTF-8">
  <div>
    <span>test</span>
  </div>
</form>

```

How I can remove the div tags between form and span.

Thanks

# Answer
That `<div>` is actually there to ensure XHTML compliance so it shouldn't really be removed.

If that's not an issue for whatever reason, you need to override `theme_form()`, which is responsible for adding that `<div>`, and just remove it from the returned markup. The full code is quite short so I'll include it:

```
function MYTHEME_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element['#attributes']['accept-charset'])) {
    $element['#attributes']['accept-charset'] = "UTF-8";
  }
  return '<form' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</form>';
}

```
> 0 votes

---
Tags: theming
---


title: Export menu links with features

text:
# Question
Title: Export menu links with features
I'm trying to export menu links with features but it saves the node id in the feature, but obviously the nid is different in dev, test and production.

I can't use UUID because nodes are created in every environment.

Is there a way to export menu links with alias and not with nids?

# Answer
> 3 votes
http://webwash.net/tutorials/import-and-export-menus-menu-import-module-drupal-7 shows how to use http://drupal.org/project/menu\_import which uses path aliases instead of UUID.

I think this would work.

---
Tags: 7, routes, features
---


title: Filtering output

text:
# Question
Title: Filtering output
I am creating templates using hook\_theme. It works fine, but should I be filtering the output? I am accessing it via \['und'\]\[0\]\['value'\], but this doesn't seem right

Specifically in the code below `$model_name, $description`

```
function dc_car_guide_theme($existing, $type, $theme, $path){
    return array(
        'dc_car_makes' => array(
            'variables' => array('makes' => array()),
            'template' => 'theme/makes'
        ),
        'dc_car_models' => array(
            'variables' => array('models' => array(), 'make' => ''),
            'template' => 'theme/models'
        ),
        'dc_car_model' => array(
            'variables' => array('photos' => array(), 'make' => '', 'model' => '', 'description' => ''),
            'template' => 'theme/model'
        ),
    );
}

function dc_car_guide_model($model_id)
{
    $model = entity_load_single('field_collection_item', $model_id);
    $host_entity = $model->hostEntity();
    $make_node = node_load($host_entity->nid);
    $model_name = $model->field_model_name['und'][0]['value'];
    $description = $model->field_writeup['und'][0]['value'];

    return theme('dc_car_model', array('photos' => array(), 'make' => $make_node->title, 'model' =>$model_name, 'description' => $description));
}

```

# Answer
> 1 votes
PLease, read Rendering Drupal 7 fields (the right way).
So you'll get next:

```
<?php
function dc_car_guide_model($model_id) {
  $model = entity_load_single('field_collection_item', $model_id);
  $host_entity = $model->hostEntity();
  $make_node = node_load($host_entity->nid);

  $field = field_get_items('node', $make_node, 'field_model_name');
  $model_name = render(field_view_value('node', $make_node, 'field_model_name', $field[0])); // Remove render, if you want work with arrays on theme function.

  $field = field_get_items('ENTITY', $model, 'field_writeup');
  $description = render(field_view_value('ENTITY', $model, 'field_writeup', $field[0])); // Not sure is this correct, since I don't have info about your entity.

  return theme('dc_car_model', array('photos' => array(), 'make' => $make_node->title, 'model' =>$model_name, 'description' => $description));
}

```

# Answer
> 1 votes
As an alternative answer, using Entity API module, you could do something like:

```
function dc_car_guide_model($make_node) {
  // Load parent node, allow passed node object or nid
  $make_node = is_object($make_node) ? $make_node : node_load($make_node);
  // Get entity wrapper for easy access to properties and field values
  $make_wrapper = entity_metadata_wrapper('node', $make_node);
  // Fetch field values
  $model_name = $make_wrapper->field_collection_item->field_model_name->value();
  $description = $make_wrapper->field_collection_item->field_writeup->value();
  // Output
  return theme('dc_car_model', array('photos' => array(), 'make' => $make_node->title, 'model' =>$model_name, 'description' => $description));
}

```

As an extra, although the above method is fine for outputting sanitized markup, Drupal provides the following functions for manual sanitizing of variables

See also http://drupal.org/writing-secure-code for information on writing secure code.

---
Tags: 7, entities
---


# Question
Title: How to get taxonomy synonyms working robustly with Search API?
Tag synonyms are a popular, important feature in many sites (used here on StackExchange, for example), and taxonomy synonyms used to be part of Drupal 6's core Taxonomy module, before being dropped in favor of "Roll your own" custom synonym systems made using Field API.

When synonyms work reliably, they are extremely useful in search; for example, to make sure that searches for "America" find content tagged "USA", etc. However, I can't find any leads on what the standard method is for implementing this feature when working with the popular Search API \- Facet API family of related integrated search modules, for Node searches.

"Going with the flow" is important when working with clusters of modules like this, to make sure that systems you implement don't go against the grain of the thinking of the community and module maintainers. When they do go against the grain, they are flakey and risk being broken by future changes to these modules.

What is a reliable/robust/standard/expected method for implementing taxonomy synonyms in D7 for sites using Search API? (in particular, with Search API Solr, but I would hope that Search API's attempts to abstract out the particular search provider would work in this case).

If you have a system for this that seems to work, but it's something you figured out and you aren't sure if it is or isn't against the grain (pretty common in Drupal), please do share it anyway with information from your testing, usage and experience on which features and modules in the Search API-Facet API family it does and doesn't work well with.

Some plausible but potentially flakey options I've found in research:

* There's a D7 Search Synonyms module, but it looks to be little used, and there's no confirmation it works or will continue to work with 3rd party search modules like Search API (it's designed with Drupal core search in mind). **Edit:** also doesn't look to be too reliable in D7 in general.
* It's theoretically possible to add a term reference field called "Synonyms" to a Taxonomy vocabulary, and index this field from the term in Search API with equal weight to the term on the node itself. This would work for text searches, but feels like a shallow MacGuyver-y duct-tape solution rather than something robust that smoothly slots in to the whole Search API family. For example, if a term "United Kingdom" has a synonym "Britain", someone searching on 'Britain' would get results tagged with United Kindgom, but someone typing "Britain" into an autocomplete Taxonomy exposed filter or selecting Britain with a Taxonomy fact would not see any content tagged with "United Kingdom".\*****
* Another similar possibility is adding a multi-value plain text field "Synonyms" to the term vocabulary (or even comma-separated, I guess), and indexing it with the same weight as the term name as above. But this has similar, if not worse, issues to the above in the above example, "Britain" wouldn't even be listed as an option in a facet or exposed filter. There might be some way to create a composite field by combining name and synonyms ( "United Kingdom (Britain, UK)" ), and set facets/exposed filters/etc to use that ... but I can't think of any way to do this that isn't worryingly hacky and that doesn't feel worryingly against the grain. **Edit:** Search API Combined seems designed for something like this, but I'm not sure how heavily tested or integrated it is across the Search API family.
* Then there's the last resort option of just cramming everything into the term name: it should be clear that this isn't desirable and would in many cases make for very ugly lists (e.g. imagine a navigation list of countries that were written out like "North Korea (PRK, DPRK, Democratic People's Republic of Korea)"... ). Or having a "Display name" field that shows the short version, and setting everything except search (all Views, Pathauto, every other contrib/core module that uses the term name) to use this instead of the term name... again, very hacky and very against the grain.
* Apache Solr has a Synonyms feature, where a text file of synonyms is read and these terms are treated as synonymous across searches that use it. However, while possible in a Search API setup that uses Solr, this is considered by the module maintainers to be unsupported 'attempt at own risk' advanced Solr configuration. Also, it's more appropriate for generic synonymy in the *language* of the site than synonymy specifically in the context of a taxonomy. For example, a site with a taxonomy that doesn't discriminate England, Scotland etc from Britain might want to consider them synonymous in the context of tagging, but not synonymous in the context of searches on body text. **Edit:** The head Facet API maintainer warns against this route as Solr integration modules work with terms as TIDs not text.

I'm aware that this is a flawed example because in the case of UK/Britain, and countries in general, people are used to using lists that only have one or the other. There are plenty of less simple cases (e.g. product categories) where people wouldn't think to look for a synonym.

**Update:** Relevant info in a new thread on Drupal.org Facet API queue. Also a (currently unanswered) thread on Search API queue.

(any rules lawyers wondering if it's okay for there to be drupal.org support requests and drupal answers questions on the same topic: yes, it is, in fact it's encouraged to take the pressure off module maintainers)

# Answer
> 2 votes
I have been using bojanz's excellent Synonyms module. It is a complete re-write of the D6 synonyms function, with a number of new bells and whistles. Looks like it might do most of what you need.

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


# Question
Title: What is your way to get the fields information when using Services 3
I have a registration form with 50+ input fields. What is the best way to get form filed information to pass it to iPhone or Android developers to make a form in the mobile app?

Currently i am doing something like inspect the form with firebug and copy/paste the form to make this work.

Recently i have written some code to get the form field information.

This is the idea.

1. In the `hook_formalter` add a `$form['#after_build'][]`
2. Get the keys in `$form['#after_build'][]` and get the basic information.
3. Render the information to a `item` and add it to form so that i can copy/paste

But its not perfect; when the form fields like add custom modules for Registration like Logintoboggan etc i am not getting expected results.

What is your way to do it?

This is the result i expect in case of a select field

```
  Array
         (
                [Title] => Marital Status
                [Field Name] => field_marital_status[und]
                [Type] => select
                [Options] => Array
                    (
                     [151] => Status
                     [154] => -Divorced
                     [155] => -Married
                     [153] => -Never married before
                     [157] => -Separated
                     [156] => -Widowed

                    )

       )

```

# Answer
> 2 votes
As @Clive has suggested in comment its best to write your own service resource for this.

### Approach 1:

But i wouldn't bother to programaticality supply the form field values anymore. Reason being, its usually not cost-effective to spend enough hours trying to figure out every possible field type that has been implemented or may be implemented in the future.

Instead create an API documentation. The implementation details is the liberty of IPad / Android dudes. Make sure you enable version control over the docs and also maintain a well documented change logs.

### Approach 2:

If you do want to supply the form field information via services.

Then create a resource action.

Something like `www.mysite.com/your-endpoint-name/your-resource-name/get-form`

This action should be responsible to provide the field details.

This could be done by calling `drupal_get_form($form_id);` and then passing the $form array through a function that would **filter out** lots of unnecessary data which drupal adds.

Please note that the main difference here is "**We are removing unwanted data from the form definitions**" instead of "**adding necessary field data**". Thus it will help reducing missing fields that might be added later by some modules in to the form.

After you are done with removing you may add additinal information into the form array like API interface Version, timestamp, and some default values that maybe useful for the Ipad/android dudes.

---
Tags: 7, forms, services
---