# Question
Title: Symlinked folder not recognized by file_exists?
A module I'm working on maintains a list of files in the private file system folder in Drupal. I use `hook_file_download` to control access to these files.

I generate links to these files, which end up like: `http://sample.com/system/files/my_folder/file.pdf`

My website path is `/var/www/sample.com/www` and the private folder path is configured to be `/var/www/sample.com/private`.

Now, if the file is placed is `/var/www/sample.com/private/my_folder/file.pdf`, everything works fine and I can properly control access to the file and deliver it. However, if `my_folder` is located elsewhere and symlinked in, then things break. I've tracked part of it down to the PHP function `file_exists` returning false, which is called in `file_download`.

I'm not sure where to go from here. Everything I've searched for thusfar indicates that symlinks should work just fine. The permissions on the symlinked directory are OK - the directory is 755 and the files are 644.

What else could this be?

I've tried this on the latest PHP 5.3 and PHP 5.4 with no difference.

**EDIT**: It's worth mentioning that I can get `file_exists` to return true if I pass the absolute path to the symlinked file. Drupal is passing a stream wrapper though (`private://my_folder/file.pdf`). So looks like it could be related to the streamwrapper somehow?

# Answer
> 1 votes
I kept digging and found it was related to Drupal's stream wrapper implementation, specifically the `getLocalPath` method. There's already a large Drupal issue for this, which I wouldn't have found with my previous search terms.

---
Tags: 7, files
---


# Question
Title: Are there hook_functions to handle submissions from the webforms module in Drupal 6?
I'm asking this question as a possible way to handle another issue I possted about ("Moving webform uploads to a non-public folderspace"). Is there a hook\_function that I can use to handle the submission of a webform in Drupal 6. That is, can I use a `hook` to relocate a file uploaded through a webform ***and*** update the database entry to mark that upload files new place?

# Answer
> 1 votes
Take a look at these three hooks.

---
Tags: 6, hooks, webforms
---


title: Responsive Image Gallery

text:
# Question
Title: Responsive Image Gallery
I want to create a responsive Image gallery block. I have used Views Slideshow Liquid Carousel module for this but that is not working properly, It breaks when the screen is too small. I want a carousel like display of images with responsive skin like http://tympanus.net/Development/Elastislide/, I have also tried this plugin but this plugin is not working properly can't find why. So is there any other way or plugin for this.

# Answer
Trying to use these modules may help you (quotes included are from their project pages):

> ... integrates the Responsive Images library created by Filament Group.
>
> The purpose of this library is to load images in different sizes based upon the resolution of the browser loading the page. This allows for mobile-optimized images.
>
> ... provides a "Responsive Images" image field formatter for which you can select both a small (mobile-optimized) image style as well as a large (for normal screens) image style. The image style configuration options are provided by Drupal core.

> ... solves the problems with images and responsive themes, it allows you to define multiple image style suffixes and their corresponding maximum width.
> 3 votes

# Answer
Drupal 8 module for responsive images will be in the picture module, a Drupal 7 Version exists today: Picture

Using the picture module, instead of the other available alternatives, will probably help in upgrading pages from 7 to 8.
> 1 votes

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


title: Getting hook_menu() to respond to a URN

text:
# Question
Title: Getting hook_menu() to respond to a URN
I have a site that can respond to URNs. For example, I need to be able to serve up a response to

```
http://example.com/urn:myscheme:foo:bar:12345

```

So, I need a router item that can match against the "urn" or "urn:myscheme" portion, and get "foo:bar:12345" as the argument (either exploded or not).

Can `hook_menu()` be configured this way?

I have tried

```
$item['urn'] = array(...);
$item['urn:'] = array(...);

```

without any luck. I can do this with a `hook_url_inbound_alter()` trick, but am curious whether it can be done directly. For the purposes of this question, I can't use path aliases.

# Answer
Would love to be proven wrong, but I don't think that's easily possible using `hook_menu()`.

Core only considers `/` as a separator, and matches on string, so `urn:`, `urn:myscheme` and `urn:myscheme:foo:bar:12345` can only be represented as completely different paths.

The guts of it happens in `menu_get_item()`:

```
$original_map = arg(NULL, $path);

$parts = array_slice($original_map, 0, MENU_MAX_PARTS);
$ancestors = menu_get_ancestors($parts);
$router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();

```

The call to `arg()` splits the path by `/`, which is hardcoded:

```
$arguments[$path] = explode('/', $path);

```

When `menu_get_ancestors()` returns for a path like `urn/myscheme`, it has two elements in the array: 'urn' and 'myscheme'. The same call for `urn:myscheme` returns an array with a single element, 'urn:myscheme'.

Those ancestors are used directly in the query to match the path in `menu_router`, so for the path `urn:myscheme`, you'll get this query:

```
SELECT * FROM {menu_router} WHERE path IN ('urn:myscheme') ORDER BY fit DESC

```

Try the same thing with `urn:myscheme:foo:bar:12345`, and as far as Drupal's concerned, it's a separate path that has to be handled by a different router item, as the query will be:

```
SELECT * FROM {menu_router} WHERE path IN ('urn:myscheme:foo:bar:12345') ORDER BY fit DESC

```

Without resorting to replacing menu.inc (which I think is pluggable if I remember rightly), `hook_url_inbound_alter()` will probably be the best best.
> 1 votes

---
Tags: routes
---


# Question
Title: Organic Groups - Display the Group Name that a peice of content belongs to
I have a view that is listing all of the content tagged with a taxonomy terms (contextual filter). Underneath the note title, I would like to include some meta that says: posted by username who belongs to "**group name**" and link that over to the associated group. Here is a screenshot of my current view:

http://cl.ly/image/0Z103y3q3D1z

Any help is much appreciated. I can't seem to find a "group name" or "group title" field anywhere when attempting to use fields associated with a relationship.

Thanks for any help.

# Answer
> 0 votes
Found the answer with the help of this post: Using Views to List a Member's Organic Groups (7.x-2.3)

Here is a screeshot of my view: http://cl.ly/image/2O1h1x3T3J43

by adding the relationship: "OG Membership: Group Node from OG membership" I was able to use that relationship in a new title field and display.

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


# Question
Title: Improving performance with Field Collections?
I'm using using entity reference, field collection , and field collection table modules on a site that features "courses" and "lessons" as content types. A field collection with unlimited values is embedded in the course content type, and it contains two fields: a text field for "section" and an entity reference field for "lesson". This allows the same lessons to be reused in different courses, while appearing under a different section. (see screen for reference).

This works pretty well, but performance when editing course nodes starts to degrade significantly after about 30 lessons are added to a course. At 100 lessons, it takes about 15 seconds to load a course for editing. With 140 lessons in a course, it takes about 22 seconds to edit a course node. I'm testing locally on a new D7 test site with devel-generated content.

Questions:

(1) Are there any obvious steps I should take to improve performance with field collections?

(2) As an alternative to field collections, would creating a compound field in code likely improve performance significantly?

(3) For testing performance generally, is there a simple profiling tool I can use with Drupal?

Example of a small course with 10 lessons added as field collections:

# Answer
> 1 votes
Update: In the end, I abandoned field collections and created a custom compound field that is attached to the 'course' content type.

This pretty much eliminated the performance problems. Opening a course node with 130 lessons in the field now takes 3-6 seconds, depending on the server.

And because the field is unlimited multivalue, the delta works a sorting mechanism for the lessons in views, etc.

I also added code to add more than one item at a time as seen here:

Slow "Add another item" with unlimited valued fields

When there are a lot of items in the field, adding a new item ends up taking a lot of time.

Good resources:

---
Tags: 7, entities
---


title: Simple way to pull taxonomies

text:
# Question
Title: Simple way to pull taxonomies
I am building a module to that uses taxonomy, I would like to use drupal functions as much as possible vs going to the database directly. In addition I am using the Field Module to add additional information to each of the Taxonomy entities. I would need to be able to dynamically pull back a given set of taxonomies and all fields used. Does anyone have a nice example for doing this. I know there is a function taxonomy\_get\_tree and there is the field APIs just not sure the best way to implement.

Thanks

# Answer
> 0 votes
here is an example of pulling all the terms in a vocabulary

```
$vid = taxonomy_vocabulary_machine_name_load("catalog")->vid;
//print($vid) . PHP_EOL; prints the vocab ID
$terms = taxonomy_get_tree($vid);
//print($terms) . PHP_EOL; prints "Array" if a vocab was grabbed
foreach ($terms as $term) {
   print($term->name) . PHP_EOL;
}

```

---
Tags: taxonomy-terms, entities
---


# Question
Title: How to filter entities in View by all of their taxonomy term reference fields?
Let's say I have a custom entity that has two taxonomy reference fields: **categories** and **tags**. And I want to display all entities that have taxonomy term with id 1. The term is a dynamic value(contextual filter) so it can be either the category or tag.

How can I do that in Views? Right now I can filter categories or tags separately but I need to filter both of them.

If I use two filters they will cancel each other because each of them have, in my case, "Display contents of "No results found"" set.

# Answer
> 0 votes
You can get an argument from url with views.

Use Provide default value in the contextual filter.

Another way (in drupal 7)would be to use this module: https://drupal.org/project/views\_url\_path\_arguments

---
Tags: views, entities, 8
---


title: CKEditor, Media, & Files — oh my

text:
# Question
Title: CKEditor, Media, & Files — oh my
We're relying on the Media module heavily for embedded video throughout our site. When Media is used for a field, it is working beautifully for us.

We ran into problems, however, embedding Media rich text fields. We're using CKEditor, which strips Media tags when using filtered HTML. For security purposes, we want all non-admin users to continue using filtered HTML. There were other complications, too: The UI was a little strange since you had to add the (non Media) image button to allow users to align images. So they'd have two image-y buttons, one to upload and one to style. Finally we decided we could keep rich text pared down to text without images.

However we've also been using Media to upload files (documents/docx/pdf). And we definitely want users to be able to link to files in the editor. Should we use CK Finder? Or is there a way we can expose the view at admin/content/file to non admin users so they could have an inventory of files and copy urls? Or rebuild a similar view, as described here?

I feel like I must be overlooking something obvious, as this seems like a very basic CMS feature... Have I managed to obscure functionality with my permissions and plugins? Thanks!

# Answer
For this functionality, we ended up building custom views. It's actually not very difficult, since file entities (even uploaded through Media) have a slew of fata you can populate the view with. Filter by logged in user, and it works fine.
> 0 votes

# Answer
You should try using the node reference (References) module and create a field on your content type. The node reference will ask you to specify a content type that allows users to select from a list of previously created content. You can also create a view which you can select as the source for the select list.

https://drupal.org/project/references
> 1 votes

---
Tags: files, wysiwyg, media
---


title: How toView attached files from a og

text:
# Question
Title: How toView attached files from a og
my first question here. Drupal 7 OG 7.2

I'm trying to make a view to display a list of attached files to a group. I've made a custom field for the attachments in the content type for posts and in there comments.

I've achieve to display the view, both for private files and public. Ok ! I was very happy after hours of pain.

The problem is that the view is pulling all the files from all groups. What I want it's to see the group files. How do I get the relation between the file and the group ? Any help would be appreciated.

Bellow it's a image of the view, I hope you can understand it. (field\_anexos\_de\_grupo) it's the media field. Note: I'm new to drupal and I'm not a php expert.

Thanks

# Answer
You need to also to add the relation between the file to the current viewed groups with the OG membership relationship. You can have a look how this done in a view called "OG content"
> 0 votes

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


# Question
Title: How Can i control the way the tabels in the admin panel build?
How Can i control the way the tabels in the admin panel build? i want to make the system more comfortable for the people how will be doing all the content edit in my site.

Like change the way this build -

Matan

# Answer
If you just want to style the D7 administrative theme (called "seven") differently, you can create a sub-theme of that theme and then customize. Docs are here: https://drupal.org/node/225125

Once you have a sub-theme, you can add you own css, templates, etc to change the way things look.

Because of the inheritance you get when sub-theming, you only have to add what you need to the new theme. For example, you could just have an .info file and custom css file.
> 0 votes

---
Tags: webforms
---


title: How to pull taxonomy fields

text:
# Question
Title: How to pull taxonomy fields
I am trying to pull out a image field that is attached to a taxonomy term. I have tried using field\_view\_field with no luck. Does anyone have a good working example?

Thanks!

# Answer
> 0 votes
Some thing like this:

```

    $tid = $items[0]['tid'];
    $term = taxonomy_term_load($tid);
    //it turn out that taxonomy_term_load gets empty array for my custom field
    //that's why  after some poking around Drupal API i come up with the following
    $term_page =  taxonomy_term_view($term, $view_mode = 'full');
    $term_url = taxonomy_term_uri($term);
    $image_url=$term_page['#term']->field_client_logo; //this is my custom field name
    $image = theme('image', array(
      'path' => $image_url['und'][0]['uri'],
      'alt' =>  $term->name,
      'title' => $object->title,
    ));
    return l($image, $term_url['path'] , array('html' => TRUE));

```

---
Tags: entities
---


# Question
Title: How to show token value in Webform confirmation
In Webform \> Form settings \> Submission settings \> Confirmation message, how can I show a webform token as part of the confirmation message? Something like:

> Hi `%value[name]`, thanks very much for joining our event!

# Answer
> 3 votes
Use Webform tokens module

> Webform Tokens provides tokens for user form submissions for forms created with the module Webform 3.

Or upgrade to Webform4 which has this feature inbuilt.

---
Tags: 7, webforms, tokens
---


# Question
Title: How to create internal links during user navigation
I would like to allow users to create links between pages within the website. This wouldn't even be a problem if I asked them to edit the page, but I would like to avoid the editing step in order to make their navigation more fluid.

What I have in mind more specifically is an empty field (like a search box) on each relevant page in which the user could just copy-paste an internal URL, which would then be processed by the system to create the link between the two pages.

I have no problem seeing how I could do that once the information is entered, but I have no idea of how I could do to integrate an empty field in my page and use it in the way I described.

Any hint? Thanks! :)

Igor

# Answer
> 0 votes
Relations module was built exactly for use cases like this. But be warned that it has a little steep learning curve.

Relations Add Module can significantly reduce your work and also has an auto-complete feature that is user friendly.

> This module provides a field that can be used to create/delete/update the relations from within the node/entity forms, with a generic autocomplete for each endpoint, and relation fields.

---
Tags: navigation
---


title: Can a batch process be stopped

text:
# Question
Title: Can a batch process be stopped
Is there a way to force a batch process to stop if some kind of error occurs? In particular, I have a batch that starts with saving a record to a database. Each subsequent batch operation depends on the database insert working correctly. I'd like to force the batch to stop if the first batch fails.

The batch is called like this

```
$batch = array(
    'operations' => $operations,
    'finished' => 'mymodule_batch_finished',
    'title' => t('Merging records'),
    'init_message' => t('Starting processing'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Processing has encountered an error'),
    'file' => drupal_get_path('module', 'mymodule') . '/forms/mymodule.inc'
);

```

where `$operations` is the array of functions to call.

Each function uses PDO to update the database. I'm trying to figure out how to stop the subsequent `$operations` from being called if the query in the current operation fails.

```
try {
  $sth = $dbh->prepare($sql);
  $sth->bindParam(':newid',$new_id,PDO::PARAM_INT);
  $sth->bindParam(':id',$id,PDO::PARAM_INT);
  if($sth->execute()) {
    $context['results']['[] = $sth->rowCount();
  }
  else {
    // TODO: stop processing due to an error
  }
}
catch(PDOException $e) {
  // TODO: stop processing due to an error
}

```

If an error occurs, I want to bypass the remaining operations and go straight to `mymodule_batch_finished`

# Answer
> 15 votes
Inside your batch callback, where you do the batch work, you should be able to set `$context['finished']` to `1`, and that will signal to Drupal that the batch is complete.

So, in your case:

```
$error = FALSE;
try {
  $sth = $dbh->prepare($sql);
  $sth->bindParam(':newid',$new_id,PDO::PARAM_INT);
  $sth->bindParam(':id',$id,PDO::PARAM_INT);
  if($sth->execute()) {
    $context['results'][] = $sth->rowCount();
  }
  else {
    $error = TRUE;
  }
}
catch (PDOException $e) {
  $error = TRUE;
}
// If there was an error, immediately complete the batch process.
if ($error) {
  $context['finished'] = 1;
}

```

And, even better, you can pass in an error message in the `$context` as well, which you can check for in your finished callback, then display to the end user in case of failure.

If you want to *immediately* stop processing anything in other callbacks in the `$operations` list, you might also need to check for a static variable at the beginning of each callback, and skip the callback if it's in an error condition. You could try using `variable_get`/`variable_set`, or some other mechanism that persists between page requests. This would definitely be a hackish/last-resort solution, though!

See also:

# Answer
> -1 votes
Can you try below code ?

```
$result = array('status' => FALSE, 'data' => $message);
die(json_encode($result));

```

---
Tags: 7, batch-operations
---


# Question
Title: how to correctly use curl command line with Services module?
I try to use following command to create an user:

```
$ curl -H 'Content-type: application/json'  -d '{"name":"u10", "pass": "123","mail": "user@a.om"}' http://localhost/test/api/user/register

```

return success:

```
{"uid":"11","uri":"http://drupal/daxuebao/api/user/11"}

```

But I try to login:

```
$ curl -H 'Content-type: application/json'  -d '{"username":"u10", "password": "123","mail": "user@a.om"}' http://localhost/test/api/user/login

```

It alert me :

```
["Wrong username or password."]

```

So, How to correctly use curl command line?

# Answer
You need to send only username and password. Mail is not required.. Please check the documentation here...

```
$base_url = 'http://localhost/test_endpoint';
$data = array(
  'username' => 'admin',
  'password' => 'password',
);
$data = http_build_query($data, '', '&');
$headers = array();
$options = array(
  'headers' => array(
    'Accept' => 'application/json',
  ),
  'method' => 'POST',
  'data' => $data
);
$response = drupal_http_request($base_url . '/user/login', $options);
$data = json_decode($response->data);
// Check if login was successful
if ($response->code == 200) {
  // Now recycle the login cookie we recieved in the first request
  $options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
  // Get info about a user
  $data = array();
  $options['data'] = http_build_query($data, '', '&');
  $options['method'] = 'GET';
  $response = drupal_http_request($base_url . '/user/32', $options);
}

```

Below one worked for me

```
curl -H 'Content-type: application/json'  -d '{"username":"admin", "password": "admin"}' http://localhost/d7/testendpoint/user/login

```

In your case it should be

```
curl -H 'Content-type: application/json'  -d '{"username":"u10", "password": "123"}' http://localhost/test/api/user/login

```
> 0 votes

---
Tags: 7, users, services
---


# Question
Title: How to override node clone to its parents node?
I am using node clone 7.x-1.0-rc2 module.It is creating clone for a particular node.Now if i published clone.How to override parent node with clone node. Is there any other way or module for doing this?

I am using workbench and my scenario is that i have three types of user contributor,validator and publisher. only contributor can create node and assign it to validator, now here validator can revert to contributor or assign to publisher.Publisher can publish this node or revert to validator.Now i am creating a clone of this node and again send it to contributor and contributor send it to publisher but when publisher wants to publish this clone so old content get update this clone node's content or delete old one and become this node as a parent node.

# Answer
> 2 votes
It looks that you are trying to implement elaborated workflow using node cloning approach.

I strongly suggest you to use Workflow module instead:

> This module allows you to create arbitrary Workflows, and assign them to Entities.
>
> Workflows are made up of workflow states. Transitions between states can be allowed per role. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type. Only users with role 'chief editor' can set Stories to the published state. You can set up the Workflow to alter states from form, page, comment and a special workflow tab.
>
> Transitions between workflow states can have actions assigned to them. In our example, we could assign an action so that when the story moves from the Draft state to the Review state an email is sent out. Another action could be assigned to the transition from Review to Published so that the node's status is set to Published (and becomes visible on your website).

It is there, it works, and it seems to cover all your needs in one, integrated solution. Even it's example use case is almost exactly like your use case here.

**If you want to configure it at revision level** more easily, there is also Revisioning, *"a module for the configuration of workflows to create, moderate and publish content revisions"*.

> You use it in scenario's like this:
>
> * Authors write content that prior to being made publicly visible must be reviewed (and possibly edited) by moderators. Once the moderators have published the content, authors should be prevented from modifying it while “live”, but they should be able to submit new revisions to their moderators.
> * We shouldn't have to grant these roles “god-like” powers (e.g. D6's "administer nodes" permission) to implement this.

---
Tags: nodes
---


# Question
Title: How do I remove the classes from the pager item-list in Drupal 7?
I am in a Drupal 7 theme development where we need to over write the pager theme where the class "item-list" needs to be removed.

My current item-list HTML

```
<div class="item-list">
<ul class="pager">
    <li class="pager-first first"><a title="Go to first page" href="/node">« first</a></li>
    <li class="pager-previous"><a title="Go to previous page" href="/node">‹ previous</a></li>
    <li class="pager-item"><a title="Go to page 1" href="/node">1</a></li>
    <li class="pager-current">2</li>
    <li class="pager-item"><a title="Go to page 3" href="/node?page=2">3</a></li>
    <li class="pager-next"><a title="Go to next page" href="/node?page=2">next ›</a></li>
    <li class="pager-last last"><a title="Go to last page" href="/node?page=2">last »</a></li>
</ul></div>

```

And I need something like this

```
<div class="pagination pagination-centered">
<ul>
    <li><a title="Go to first page" href="/node">« first</a></li>
    <li><a title="Go to previous page" href="/node">‹ previous</a></li>
    <li><a title="Go to page 1" href="/node">1</a></li>
    <li><a href="#">2</a></li>
    <li><a title="Go to page 3" href="/node?page=2">3</a></li>
    <li><a title="Go to next page" href="/node?page=2">next ›</a></li>
    <li><a title="Go to last page" href="/node?page=2">last »</a></li>
</ul></div>

```

# Answer
> 1 votes
To override the markup of the pager, override the theme\_pager() theme function.

However in your case you want to override the class in the item list so for that you need to also override theme\_item\_list().

For information on overriding theme functions see the beginners guide to overriding themeable output, and for more thorough drupal themeing information see themeing drupal 6 and 7

# Answer
> 0 votes
This could be done in JQuery.

```
$('ul').removeClass('pager');
$('li').removeClass('pager-first pager-item etc.');

```

The issue with this is that it will run on every page, probably unnecessarily. If I were you I would find where the class is being applied to the li and ul tags and just remove it from there.

---
Tags: theming, paging
---


# Question
Title: Display Suite custom function field not firing
I need to add a Display Suite function field to a node. I set up my hook, and my field shows up and I can add it to my content type in display. However, the function isn't getting called, and it looks like it should. I stripped my code down so I can debug this. My custom function is in my .module file.

```
function MYMODULE_ds_fields_info($entity_type)
{

    if ($entity_type != 'node')
        return;

    $fields = array();

    $fields['splittitle'] = array(
        'title' => t('Split product title'),
        'field_type' => DS_FIELD_TYPE_FUNCTION,
        'function' => 'MYMODULE_ds_field_splittitle'
    );

    return array('node' => $fields);

}

function MYMODULE_ds_field_splittitle($field)
{

    return 'test';
}

```

# Answer
> 1 votes
Here is the code that worked for me... My Module name is drup\_custom

```
function drup_custom_ds_fields_info($entity_type)
{
    if ($entity_type != 'node') {
        return;
    }

    $fields = array();

    $fields['test_title'] = array(
        'title' => t('Split product title'),
        'field_type' => DS_FIELD_TYPE_FUNCTION,
        'function' => 'drup_custom_ds_field_splittitle'
    );

    return array('node' => $fields);

}

function drup_custom_ds_field_splittitle($field)
{
  return 'My Content';
}

```

Steps to follow to see results..

* Cleared Caches
* Enabled Layout in Content Type Settings

* Now, you can see your field in disabled list

* Assign the field to which ever region you would like, Save Settings

* I can see the field content in Node View Page

---
Tags: 7, display-suite
---


# Question
Title: ApacheSolr Search results with AJAX (D7)
I've been searching the web for ways to display my search results directly in a block after submitting the input form with AJAX.

Unfortunatly, i haven't found alot of good information on this subject. Can anyone here point me in the right direction? I'm using Drupal 7.

Thanks in advance! :)

# Answer
> 1 votes
Apache Solr AJAX module is available for D6

Project page says

> The Apache Solr AJAX module AJAXifies Apache Solr Search Integration – if you change your query or filters, you see the new result set instantly – no need to reload the full page.

For D7 there exists a Sandbox Project

You can try the module, Download module using below commands,

```
git clone --branch master http://git.drupal.org/sandbox/darthsteven/1116776.git apache_solr_ajax___d7
cd apache_solr_ajax___d7

```

Found an article here Drupal7 AJAXified Solr Search with facets. Search API, Panels and some custom code. you can give a try..

---
Tags: ajax, javascript, search
---


# Question
Title: How to create dependent dropdown in drupal 7 content type?
I have created a 2 custome content type in drupal 7 one is tourname and another one is location. Once I added a tour name in tour content type like tour1,tour2 and so on. In location content type I added location1, location 2 and so on for each tour name. Now I created third content type name it as details in that I need two drop down one is list of tour I have added and another one is list of location I have inserted. Whenever i changed the tour drop down value, the second drop down value will get automatically updated based on the tour name.

Thanks in advance.

# Answer
you need to create a tour and location used **Node reference module**. And automatically change the drop down option value of location based on tour option value that you can use ajax . following url help to u

Dynamic select list in the form (dependent dropdown)

https://api.drupal.org/api/examples/ajax\_example!ajax\_example.module/function/ajax\_example\_dependent\_dropdown/7
> 0 votes

---
Tags: nodes
---


# Question
Title: Print profile2 fields in user-profile.tpl.php
Been trying to print the profile2 fields in the user-profile.tpl. The fields are of type: taxonomy reference field and link field.

The documentation provided in drupal doesn't work.

Workarounds provided in the profile2 issue queue here and here either prints the current users value in every profile or renders it twice.

It'll really great if someone can help me with this. Thanks for your time.

In user-profile.tpl the below renders the fields twice, once within the div and other without it from "print render($user\_profile);"

```
    <div class="athlete-info">
    <?php $user_uid = $elements['#account']->uid;
    $profile = profile2_load_by_user($user_uid, 'athlete');

     print drupal_render(field_view_field('profile2', $profile, 'field_name', 'value'));
     print drupal_render(field_view_field('profile2', $profile, 'field_twitter','value'));
     print drupal_render(field_view_field('profile2', $profile, 'field_facebook', 'value'));
     print drupal_render(field_view_field('profile2', $profile, 'field_role', 'value'));
     ?>
     </div>

```

But this causes an error page on other user roles who don't have to fill up the athlete profile type. :(

EDIT: I am using the profile 2 module to create a profile called athlete with few extra fields like field\_facebook,field\_twitter and assign them to users of a particular role.

# Answer
> 1 votes
If these fields are already a part of `$user_profile` and what you are wanting to do is print them in another place/div on the page, you can do something like this:

```
<?php
  hide($user_profile['field_name']);
  hide($user_profile['field_twitter']);
  hide($user_profile['field_facebook']);
  hide($user_profile['field_role']);
?>
<div class="profile"<?php print $attributes; ?>
  <?php print render($user_profile); ?>
</div>
<div class="athelete-info">
  <?php print render($user_profile['field_name']); ?>
  <?php print render($user_profile['field_twitter']); ?>
  <?php print render($user_profile['field_facebook']); ?>
  <?php print render($user_profile['field_role']); ?>
</div>

```

Eg, hide() the fields you want to print elsewhere, then render() the rest of the profile and then finally render() those specific fields where you want them.

Now, if you are getting an error because these don't exist everywhere, you can do something like this:

```
<?php if (isset($user_profile['field_facebook']): ?>
  <?php hide($user_profile['field_facebook']); ?>
<?php endif; ?>

```

and a similar wrapping around the final printing (ADDITION: this appears to be unneeded as I didn't get any errors when I did a `hide($user_profile['i_got_nothing_to_hide']);` and a quick look at the code for hide and render shows that they pretty smart/sneaky about being passed undefined variables or keys)

Or you could check on the user role, but if this is going to begin to put a lot of php logic into the template, you may want to investigate preprocessing() it and using a special template for the user profile of the users with this/these roles.

# Answer
> 0 votes
With a lot of help from Jimajamma and the snippet here i was able to print the profile2 fields in the user profile template like this.

```
 <?php  $profiles = profile2_load_by_user($account->uid, $type_name = 'athlete' );

 print render($user_profile['profile_athlete']['view']['profile2'][$profiles->pid]['field_facebook']);

```

Thanks a lot. :)

---
Tags: 7, users
---


# Question
Title: How i can add a refresh button in the views?
How i can add a button to refresh new content in views pages or blocks? like new tweets in twitter's timeline.

Thanks

# Answer
> 3 votes
You can use Views Auto-Refresh module..

Project page says

> A module to refresh a view after a specified time interval. Includes advanced options to avoid reloading the whole view, and to avoid causing a full Drupal bootstrap at each refresh.
>
> Suitable for usage on liveblogs, activity streams, comment lists, and any other view where new items are frequently added.

# Answer
> 0 votes
I guess that you don't need any button to refresh the view, every refresh it's cache clear for you unless I'm wrong.

So check if in the twitter's block settings (or view settings) there are any advanced options to say "don't cache" as you can have always fresh contents.

Let me know if it helps.

---
Tags: views, ajax, social-network
---


# Question
Title: how to use drupal 7 module from non drupal php website
I wanted to use drupal 7 five star rating in my non drupal php website. How can i implement it.

I have installed the drupal 7 in my website root and I have added the five star rating module it works fine, If I navigate to localhost/mysite/drupal/ but I want those five star rating functionality to be implemented in my index.php file which is in localhost/mysite/index.php.

# Answer
> 1 votes
The easiest perhaps way to do it is to create a custom module, that calls and returns the rating widget, and display it either in a iFrame, or via REST service. I would probably go with the REST. You will also need to move css and images for styling the REST code from the Fivestar module.

---
Tags: 7
---


title: taxonomy for downloading files

text:
# Question
Title: taxonomy for downloading files
in my e-learning website i sell my tutorials. my files are there in private folder and after paying for each set of files, users have access to download that specific set of files... to implement that; so far i used this module: "**Private files download permission**" = Allows by-user and by-role downloads from private file system directories.
so for each set of files i have to created a separate role!
**my problem:** now i have so many roles and it is getting more difficult to organize them!

---

now i am thinking of other solutions such as using taxonomy!
i can create a form to upload a file to private folder and assign a taxonomy to it!
**1-** any user who pay for it, can get that taxonomy and can download it but i don't have a clear idea how to assign this taxonomy to a user after paying?
**2-** how can i let him download from private folder if that user has the taxonomy? i can do it all by PHP coding and hooks but is there any module which can do half of the job at least? or if there is no module to help me...can i use Rules to check if a user has a certain taxonomy or not?

# Answer
> 1 votes
One easy way of doing this, is to use hook\_preprocess\_node(), and in that function, check for that specific term. And depending on that term, you can actually unset() that file download field in the node, and insert "Please sign up", or something, message in it's place.

---
Tags: files, taxonomy-terms
---


# Question
Title: How to extract images from Statuses(Facebook style publisher) and display in seperate page?
I am using statuses module in my project which is working fine for my requirement. but my new requirement is, i need to extract the user posted pictures(not user profile pictures) in statuses module and need to display in new page along with the author of images posted. If images are more than one it should shown like album or some slide show.

# Answer
I am not sure if it's related to the statuses module at all. It seems it can be a very different story, unrelated to that module. One easy way is to use bridges like janrain (rpx).
> 0 votes

---
Tags: status-messages
---


title: menu icon image is not coming

text:
# Question
Title: menu icon image is not coming
I am using drupal7 with menu icon module. I added a image on Home menu. but this is not showing. Here is my link

I am unable to rectify the problem.

# Answer
Your CSS in style.css line 432 is overwriting the CSS that the module is trying to use. You should probably comment that CSS out or edit/remove it's background property.
> 1 votes

---
Tags: 7
---


# Question
Title: Drush how to sync Database to remote server?
I already use `drush rsync @self @a` push the local file to remote server.

this following is my .drushrc file:

```
$aliases['a'] = array(
  'remote-host' => '115.28.132.217',
  'remote-user' => 'root',
  'root' => '/var/www/daxuebao',
);

```

I try to run this following command to sync database.

```
$ drush sql-sync @self @a

```

But throw me an error:

```
Error: no alias record could be found for target @a                  [error]

```

How to solve it ?

# Answer
You need to specify an alias in a `.drush/aliases.drushrc.php` file:

```
    $aliases['a'] = array(
      'root' => '/path/to/drupal',
      'uri' => 'a.mydrupalsite.com',
    );

```

More info on:
> 1 votes

---
Tags: drush
---


# Question
Title: Ajax HTTP error occured. HTTP Result code: 200
I get Ajax error when I click next button. You can test it here.

I have found out the problem. It is due to the custom module which I have made.

```
<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<?php

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function custom_module_block_info()
{
    $blocks['tag_cloud'] = array(
        // The name that will appear in the block list.
        'info' => t('Custom Moudle'),
        // Default setting.
        'cache' => DRUPAL_CACHE_PER_ROLE
    );
    return $blocks;
}

```

When I remove the first two line (Doctype and meta). It works fine. But If I remove first two lines. It doesn't work on IE. I had to insert these two statements to get it working on IE. Now If I keep these two lines, it causes Ajax error, and if not It doesn't work on IE.

Can anyone help?

# Answer
> 2 votes
You can't just add arbitrary HTML at the top of a module file - Drupal runs through a process to theme the page, and you need hook into that.

You have a couple of options:

1. Override html.tpl.php in your theme, and add the tag to the `<head>` section manually. This is probably the easiest way.
2. Use `drupal_add_html_head()` in your module, e.g.

```
$tag = $element = array(
  '#tag' => 'meta',
  '#attributes' => array(
    'http-equiv' => 'X-UA-Compatible',
    'content' => 'IE=edge',
  ),
);
drupal_add_html_head($tag, 'mymodule:ua_compatibility');

```

Make sure you pick an appropriate hook to do this in (`preprocess_page`, etc), don't just add it to the top of the file or it won't work.

---
Tags: views, ajax, paging
---


# Question
Title: how to catch when node is being promoted?
I would like to take some action when node is being promoted. I tried using node\_validate or node\_presave but none of them is working.

What is the quickest way to do this?

thanks

# Answer
You can do it using hook\_node\_presave ...

Below is the code which works for me... Trick is here you need to make sure if node is new and promoted take action.. If node already promoted that means you are editing a node... You need to check whether original was unpromoted and after edit it is promoted then take action...

```
function YOURMODULENAME_node_presave($node) {
  if ($node->is_new && $node->promote == 1) {
    drupal_set_message("NODE PROMOTED");
    // Take Some Action
  }
  else if ($node->promote == 1 && $node->original->promote == 0){
    drupal_set_message("NODE PROMOTED");
    // Take some action
  }
}

```
> 2 votes

---
Tags: nodes
---


title: can register user control one page

text:
# Question
Title: can register user control one page
How can I make registered user take control (Edit/View/Delete) a piece of content type; a specific page for example. is that even possible?

# Answer
> 1 votes
First decide if this will be role based or user based. If it is Role based you can use the default permission system in Drupal.

If you want it per user consider using Content Access Module in conjunciton with ACL module

# Answer
> 0 votes
Permission is given by administrator to registered user

1. Go to People -\> Permission in admin panel
2. select edit any content for new Edit/View/Delete role

and also you need to used **user permission module**

User Permissions provides an interface for giving additional permissions to individual users without the need to assign them to a special role. When this module is enabled, users with the 'administer permissions' permission can access the 'User Permissions' tab on each user's account.

---
Tags: nodes, users
---


# Question
Title: Product Variation Token to fetch field of Product Display (Commerce)
I am currently trying to automate some stuff, including the product sku as new products are created. For this I am using the AutoSKU module together with Token.

The idea is that every product display has a *Base SKU*, which I want to define once per product display.

So when you add a new variation to that product display, I want AutoSKU to also fetch whatever string has been put into said *Base SKU* field, named `field_device_sku` .

Stuff like `[commerce-product:field-device-sku]` unfortunately does not work, for the field belongs to the product variation's *parent* product display.

Is there any way pulling this off without unnecessarily redefining the 'base SKU' inside every product variation?

**TL;DR**: For pictures famously say more than 117 words, here an admin panel screeny which might make it clearer what I am talking about and struggling with:

Fetching the desired SKU of the coverage and texture is no issue thanks to taxonomy, but the base sku string I just cant figure how to get. I am starting to doubt it's even possible if it's not defined directly in the product variation.

Any help or hints would be highly appreciated!

# Answer
although I solved this issue a while back just by applying the same *Device* term reference field on every variation form, maybe someone else happens to stumble upon this sometime:

just as I was messing with some rules yesterday, I found out about a token that deal with exactly this! I just gave it a shot and it does exactly what I was looking for: refer to fields on the node that was used to create the variation.

the token that does this:

```
[commerce-product:field-product-node:0:

```

so, for example, the token in my case would look like this:

```
[commerce-product:field-product-node:0:field-device-name:field-device-sku]

```

(note that the screenshot in my original post is outdated, as I now determine the device name and SKU via a taxonomy term reference `field-device-name`)

**keep in mind!:**
although this may keep you from having to include the same field on the product variation, I reckon this is less reliable. you may run into trouble, if you happen to create (or edit!) a product variation from a different node that does not have the reference field (or has other input). note that even when editing an already existing product, the SKU will be re-generated on submit. so make sure you only edit the product from within the original node (or any node that has the same field with the same value), if you dont want the value of the token-generated field to change.

however, I could be wrong and it may be just as reliable, if the `field-product-node:0` always references to the same node on which the variation was originally created, regardless of where you edit it later on. – someone will have to test this (and preferably report back) if he/she is interested in the exact behavior of this node reference token. if anyone knows the answer, I would be interested in hearing how this behaves exactly. but since I'm sticking with the extra field in the variation, I do not rely on this method now.

hope this helps someone else in the future. (:
> 0 votes

---
Tags: commerce, tokens
---


# Question
Title: Set default registration type for content type
I created a registration type for a certain content type using the registrations module (https://drupal.org/project/registration). But the user can select or disable a registration type.

Can you force this registration on a certain content type?

# Answer
> 0 votes
Since Registrations are fields make it a required field.

And then from the default values select the type of registration you want to force for a content type.

---
Tags: forms, users, nodes
---


# Question
Title: Add date field to drupal entity registration
I created an event with a fieldset of dates. You're able to register to this event, but I would like to add an extra field with one of the dates of the event.

How can this be done (with the entity registrations module)?

# Answer
Goto `Strcuture->Registrations->YourRegistrationType` and add a new field of type date.

You can use Field Validation Module to make sure that the entered field is between the selected date range of the content type on which you have the registrations enabled.

Note : You could also use the tokens module to make sure that this datefiled in registration type has default value of the starting date of the date field in parent content type.
> 1 votes

---
Tags: forms, entities, nodes
---


# Question
Title: How do I switch node templates based on arbitrary critera
I'm trying to switch the node template file based on a variable, in drupal 6 you could simply set `$vars['template_file'] = 'node-whatever';` from with the preprocess\_node() and name the new node template file node-whatever.tpl.php. I drupal 7 this is gone. I looked through the docs and it appears that in Drupal 7 its `$vars['theme_hook_suggestion'][] = 'node--whatever';` but this is not working for me. Am I doing something wrong? is there a naming convention that I'm missing? The documentation is a little confusing

# Answer
> 6 votes
Indeed, in D7 the template suggestions are an array of suggestions, in the order of importance. You've got 99% of it, but your dashes need to be underscores. Try:

```
function THEME_preprocess_page() {
  $vars['theme_hook_suggestions'][] = 'page__whatever';
}

function THEME_preprocess_node() {
  $vars['theme_hook_suggestions'][] = 'node__whatever';
}

```

Why underscores instead of hyphens? From the Drupal API docs:

```
  // Hyphens (-) and underscores (_) play a special role in theme suggestions.
  // Theme suggestions should only contain underscores, because within
  // drupal_find_theme_templates(), underscores are converted to hyphens to
  // match template file names, and then converted back to underscores to match
  // pre-processing and other function names. So if your theme suggestion
  // contains a hyphen, it will end up as an underscore after this conversion,
  // and your function names won't be recognized.

```

# Answer
> 0 votes
Some Drupal 7 example where you're loading different TPL template based on taxonomy term wich Page has (field\_page\_category):

```
/**
 * Override or insert variables into the node templates.
 *
 */
function phptemplate_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  switch($node->type) {
    case 'page':
      $tid = $node->field_page_category[LANGUAGE_NONE][0]['taxonomy_term']->tid;
      $parents = taxonomy_get_parents_all($tid);
      foreach ($parents as $tid => $term) {
        $category = ereg_replace('[[:space:]]', '-', $term->name);
        // Suggest a theme name, see: https://drupal.org/node/1089656
        $vars['theme_hook_suggestions'][] = 'node__page__'. strtolower($category);
      }
    break;
  } // end: switch
}

```

---
Tags: theming
---


# Question
Title: Two different versions of the same base theme in the same site
I'm wondering if it's possible to get two different branches of the same theme into the same site, both to be used as base themes.

Specifically I'm talking about Omega 7.x-3 and Omega 7.x-4 in the same site, but I guess the question applies to any theme.

Rationale: We're using Omega 4.x for the main theme (because of the nice front end stack), but for commerce sites (which this is), we also like to include Omega Kickstart as the admin theme. It's an improvement over Seven for very little work and clients seem to like it.

However, Omega Kickstart uses Omega 3.x as its base theme, and so conflicts with the newer version that's installed.

Short of taking a copy of one of the Omega versions, renaming it and all its internal functions, and then building a sub-theme from *that*, is there any way to get this sort of workflow?

**UPDATE**

Ok, er, so I made a bit of a mistake. I actually want to use the Shiny theme, not Omega Kickstart. Whoops.

But let's say I didn't, and definitely wanted to use Omega 3.x and 4.x in the same site...how might that go?

# Answer
Themes, like modules, are identified by their names. The version number is never really used (except for updates obviously).

Anyway, i found myself facing a similar problem sometimes, and running a find&replace on the theme directory to change every occurrence of the name with another inside the files never lead to unexpected behaviors.

well, i also had to manually rename the .info file, so it's not a completely automatic procedure, but still nothing that caused problems of any sort.
> 1 votes

---
Tags: theming
---


title: Admin log in on site with no logins

text:
# Question
Title: Admin log in on site with no logins
I'm working on a site that, in production, will have no logins. We've gone with Drupal to facilitate the creating and editing of content by non-experts.

My question is, in this scenario, what's the best practice for allowing an administrator to log in? Since there no login on the main site, how does an admin access it?

I know there's the standard page mysite.com/user or mysite.com/user/login. Leaving that out there where knowledgeable users could find it seems less than ideal to me.

Is that how people do it? Or is there another way?

# Answer
> 2 votes
Those pages are, by default, blocked in the Drupal generated robots.txt file meaning that it's very unlikely a "regular user" will stumble on them.

Someone would have to know you were using Drupal, and then type in that URL. You're right though: many people will know how to do that.

However, it's not a big deal. Your admin account password should be strong enough that it cannot be guessed at. Drupal is quite secure. You have nothing to fear about leaving that login form where it is unless your passwords are really, really bad.

The amount of effort to re-create the login pages elsewhere does not make any sense in this case.

---
Tags: users
---


# Question
Title: Theme UberCart catalog page to use custom html
Working with Ubercart 3.x on Drupal 7.

I want to theme the /catalog/1 page, where it shows my products. I want to use completely custom html that has divs nested with tables nested with divs.

I know that I can override with my own view, but I have no idea how to get the data that the existing view is using? I want to make my own tpl.php file that will loop the products for that catalog, but I don't know which variables to access, or what functions to call.

Thank you

# Answer
> 0 votes
Your theme's files will override the module's files.

You should install the "Devel" and "Theme Developer" modules.

https://drupal.org/project/devel\_themer

WHen you have these installed and configured, it will show you the template names to use for specific pages/blocks/views/etc.

---
Tags: views, theming, ubercart
---


title: Login form inaccessable?

text:
# Question
Title: Login form inaccessable?
When I go to mysite.com/user I see the login form. But it is not accessable. I cannot click in either of the text boxes and the button does not click.

This is true in Firefox, Chrome, and recent IE. It does work in IE8 for some reason.

Anyone have a clue why this should be? I tried moving it to other regions. I looked at the HTML and it appears to be fine. Maybe I'm missing some crucial Javascript?

Any ideas would be appreciated.

# Answer
> 2 votes
It sounds like there is some invisible HTML over the top of your form.

Inspect one of the form elements with Firebug and see what it actually selects, then fix the HTML / CSS.

# Answer
> 0 votes
With firebug or chrome dev tools, right click on the form, and 'Expect element'. Then you will see what element gets on top over it and blocks it. Often it's an ill-terminated div, or a bad float. Or your form is floated and some clearfix is missing.

---
Tags: users
---


title: Using Webform with tokens in drupal 7

text:
# Question
Title: Using Webform with tokens in drupal 7
I have a custom content type "Project" which has two fields "Completed Projects" and "WIP Projects". I have added some of my project as completed and rest of them are wip.

Using webform, I wanted to create a form, which can show ONLY my WIP projects (Not completed projects) in check box option. So that check box entries can be generated dynamically and user can select WIP projects.

# Answer
You dont have to use tokens there. You can use hook\_form\_alter to add the correct node titles to the form at that stage. You write a custom query, and populate the empty list.
> 1 votes

---
Tags: webforms
---


title: Creating nodes directly by SQL

text:
# Question
Title: Creating nodes directly by SQL
I am creating (content/nodes) directly by SQL , I am inserting following tables : node node\_revision body\_field

everything looks ok . But when I use FLAG module it does'nt show anything on the bookmarked view . Am i missing any other table which should be updated ?

Thanks pks

# Answer
> 5 votes
Every time you create a node in SQL, God kills a kitten. There are multiple hooks that fire on node creation, that make sure that a new node is processed corectly. The correct way to create a node is with a node\_save() function. It will fire the correct hooks, and register the node where it should. Please refer https://drupal.org/node/1388922

---
Tags: nodes, flags, database
---


# Question
Title: Uploading an image from a form in my custom module
I am creating a custom module where the user uploads and image to the Drupal DB using a form. All the data except for the file is being put into the DB though. The only thing that shows in the 'image' field is "\[BLOB - 0 B\]" The only instructions/tutorials that I can find are for uploading files to a directory, not a table in the db.

```
function new_floor_map_form($form, &$form_state) {
    $form['new'] = array(
        '#type'     => 'markup',
        '#markup'   => '<h2>'.t('Start a new floor map:').'</h2>',
    );
    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['file'] = array(
        '#type'     => 'file',
        '#title'        => t('Choose a file'),
    );
    $form ['name'] =array(
        '#type'     => 'textfield',
        '#title'        => t('Name:'),
    );
    $form['active'] = array(
        '#type'     => 'checkbox',
        '#title'        => t('Set as current floor map?'),
    );
    $form['submit'] = array(
        '#type'     => 'submit',
        '#value'    => t('Submit'),
    );

    return $form;
}
function new_floor_map_form_submit($form,&$form_state) {
    if(isset($form['file']) && (!empty($form['name']))){
        $insert = db_insert('floor_map_images')
            ->fields(array (
            'image' => $form_state['values']['file'],
            'name'      => $form_state['values']['name'],
            'active'        => $form_state['values']['active'],
            ))
            ->execute();
    }

 }

```

# Answer
> 2 votes
You shoud use Drupal file managing system. When Drupal is aware of a file, its data is stored in the file related tables. If you need to do something with a file you only need its identifier, called fid.

So, in your form upload the file using Drupal Form API, and store the fid in your table. Whenever you need to do something with the file use the fid to get all the file information.

This question may be very interesing for you: Managed file: the file used in the field may not be referenced

Check also the file\_managed Form API element: https://api.drupal.org/api/drupal/developer!topics!forms\_api\_reference.html/7#managed\_file

---
Tags: forms, database, files
---


# Question
Title: Drupal 7 & Facebook Connect - Connect Button Problem! Help please?
I installed the module Drupal For Facebook. So far it was working perfectly, I enabled Facebook Connect and put the Facebook Connect login block in a sidebar. It was great until I went into configure the Facebook Connect login block and changed text in the body. Now the CONNECT button no longer appears and only text appears saying the words "Connect." I've tried every mix of plain text, full html, and filtered html to include the suggested enter of: Connect to no avail. The only thing I see is the word Connect in plain text every time.

I need to reset this module to default or learn how to properly add the button back. But I am very new to Drupal and have no idea how to do it.

# Answer
I have the same issue, FB Connect will do this when your site tries to connect to an FB App and cannot. Check your API and Secret keys first, other possible problems are the URL settings which should match in both FB and Drupal/FBConnect. Lastly in my case, everything was working until I reset an auth key in FB which I should not have done and it created issues for me.
> 1 votes

---
Tags: 7, blocks, social-network
---


# Question
Title: How can add a textfield to user/register page form in drupal 7?
I want modify and adding a textfield in my Drupal 7 user/register page. I know that the form is generated by the function `user_register_form()`

Can i add a textfield in this way?

```
function bartik_copy_user_login($form, &$form_state) {
  global $user;

  // If we are already logged on, go to the user page instead.
  if ($user->uid) {
    drupal_goto('user/' . $user->uid);
  }

  // Display login form:
  $form['name'] = array('#type' => 'textfield',
    '#title' => t('Username'),
    '#size' => 60,
    '#maxlength' => USERNAME_MAX_LENGTH,
    '#required' => TRUE,
  );

  $form['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
  $form['pass'] = array('#type' => 'password',
    '#title' => t('Password'),
    '#description' => t('Enter that accompanies your username.'),
    '#required' => TRUE,
  );
$form['address'] = array('#type' => 'textfield',
    '#title' => t('Your address'),
    '#size' => 60,
    '#maxlength' => 125,
    '#required' => TRUE,
  );

  $form['#validate'] = user_login_default_validators();
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('Log in'));

  return $form;
}

```

# Answer
I would rather implement hook\_form\_FORM\_ID\_alter() to add the form field.

```
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['address'] = array('#type' => 'textfield',
    '#title' => t('Your address'),
    '#size' => 60,
    '#maxlength' => 125,
    '#required' => TRUE,
  );
}

```

In this way, the form field will be added to the registration form.
> 7 votes

# Answer
Drupal 7 provides the ability to add custom fields to the User through `admin/config/people/accounts/fields`. This functionality should already be in core.
> 10 votes

# Answer
Example on how to programatically add fields to the user profile and how to avail them, or not, into the User Registration form.

```
function MYMODULE_enable() {
  // Check if our field is not already created.
  if (!field_info_field('field_myField')) {
    $field = array(
      'field_name' => 'field_myField',
      'type' => 'text',
    );

    field_create_field($field);

    // Create the instance on the bundle.
    $instance = array(
      'field_name' => 'field_myField',
      'entity_type' => 'user',
      'label' => 'My Field Name',
      'bundle' => 'user',
      // If you don't set the "required" property then the field wont be required by default.
      'required' => TRUE,
      'settings' => array(
        // Here you inform either or not you want this field showing up on the registration form.
        'user_register_form' => 1,
      ),
      'widget' => array(
        'type' => 'textfield',
      ),
    );

    field_create_instance($instance);
  }
}

```
> 4 votes

# Answer
You may use hook\_form\_FORM\_ID\_alter() for adding new fields to the registration form in Drupal 7.

Here is example of adding additional e-mail confirmation field including the validation callback.

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function foo_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['mail_confirm'] = array(
    '#type' => 'textfield',
    '#title' => t('Confirm e-mail address'),
    '#maxlength' => EMAIL_MAX_LENGTH,
    '#description' => t('Please confirm your e-mail address.'),
    '#required' => TRUE,
  );
  $form['#validate'][] = 'foo_user_register_form_validate';
}

/**
 * Implements validation callback.
 */
function foo_user_register_form_validate(&$form, &$form_state) {
  if ($form_state['values']['mail'] != $form_state['values']['mail_confirm']) {
    form_set_error('mail_confirm', 'The email addresses must match.');
  }
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: Control the data facebook fetch and post on "share"
I am building a drupal 7 site using Addthis module, Meta tag module and Open Graph meta tag module

When clicking on the facebook share button - facebook fetch the relevant image properly, but a lot of text data.

Some data is duplicated data.
For example, the author name is fetched twice (e.g. "Admin Admin")

In addition, the labels of the field are fetch as well.
For example: "description: text text text".
I prefer without the label: "text text text".

How can I control the text data / fields that facebook fetch?
prevent duplicated data?
prevent fetching the labels?

# Answer
> 0 votes
Ok, so the problem was that on the admin -\> configuration -\> Metatag -\> open-graph.
I had the token \[node:summary\] on the description field. I do not have a field on my site called summary. This token just fetch a lot of information from the content / view and post it.

I removed it, change it to tokens I wanted, add some text to make the output more readable, and that's it.

After that, it took time for the site to update with the changes..

---
Tags: social-network, meta-tags
---


# Question
Title: What's the usual practice for providing several CMS-editable content in pages, particularly the home page?
I need to create a home page with several content areas containing text and images (e.g. welcome text, welcome image on a different section of the same page, a second welcome text on a different section of the same page, a third text content area, etc). All of these, of course, is in the same page as some other regions and blocks.

My googling led me to these options:

* Create a content type for each of those content. I think this option is a bit overkill since the content type will only be used for one instance of the content type. Doing this will also require creating a block specifying the particular instance of the content type.
* Create a system settings page using `hook_admin` a make each of the content sections a system variable. This also sounds incorrect since those content aren't really system variables. This method also isn't applicable since there is no sense of authorship and doesn't work with the workflow modules.

So what's the usual practice for doing this?

# Answer
You can try to use Views and make little blocks of content type flagged to the front page if you want.

Another options is Panels or Panelizer and using custom content in Panelizer to layout your frontpage however you want.

Or if you're really brave `hook_page_build`.

I've used your 2nd option on sites; if Workflows is an issue for you, you will want to try either Views or Panelizer as those tools play more friendly with workflows (it's all about the UX and how much you want to empower your site maintainers).
> 3 votes

---
Tags: theming, nodes
---


title: How to install PHP library using Drush

text:
# Question
Title: How to install PHP library using Drush
My module depends on a PHP library (sites/all/libraries/xyz/xyz-library.php). It doesn't install unless the external library `libraries/xyz/xyz-library.php` is in place. Is there a way to install the library using Drush first and then install the module?

# Answer
> 1 votes
You can actually use drush make for this purpose. Drush make files can add in third-party dependencies which can be useful for just this kind of thing. Unless you intend to share this module with the community, in which case, you can issue a wget from the module itself similar to how other contrib modules do it. (See JW Player for an older example of that)

This is a good post on the topic by basically a Drupal genius. (Not me, I swear)

http://davehall.com.au/blog/dave/2011/05/17/drush-make-and-module-dependencies

---
Tags: drush
---


# Question
Title: How do I change the layout of the fields used in a node?
I have a content type which has a large number of fields, for example:

* first name
* last name
* company

By default, when a user adds a new node, these fields will appear one under the other. I want to change the layout, and place the "last name" field to the right of "first name."

Can you tell how I can implement this? Is there a module I can use?

# Answer
> 1 votes
Here is a great tutorial on how to theme a node edit/add form in Drupal 6: Theme a CCK input form for CCK2 & CCK3

# Answer
> 1 votes
You can use Panels Module for this. Using Panel you can entirely modify the way a node should look like when viewed or edited.

For that:

1. Install panel module
2. Go to panel dashboard(admin/build/panels/dashboard).
3. Click on Node template and select the content type.
4. Inside that arrange the fields, the way u want to show it.

# Answer
> 0 votes
There are multiple layout options for your fields.

You have view modes for selecting which fields are shown in which mode.

You can use CSS overrides in your theme to float right or left the fields.

Design Suite is specifically created to arrange fields within the content area of a page, like, into columns, or rows.

Yes, Panels is overkill for such a small task, but it gives you a very rich environment with a future. Panelizer is the easiest panels way to duplicate the Design Suite functionality of arranging fields in columns

# Answer
> 0 votes
You can use Display suite to arrange the layout of your fields in a predefined or custom layout. The effect will be similar to the panels above.

However, for this particular use case, you don't really want to use layout regions, but you want to merge these fields *inline*.

This can be done with custom formatters or with display suite custom fields. The basic idea is that you have one "field" on display level, that displays the values from both fields from the database level.

I will not elaborate much further, because there is already an excellent answer over here: https://drupal.stackexchange.com/a/41167/2974

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


title: FetchObject() only return one result

text:
# Question
Title: FetchObject() only return one result
Select query will always return a result set object of one record.. There are several ways to then retrieve data from that result set, depending on the use case.

```
   user's flaged entity id:

  $query = db_select('flagging', 'f');
  $query->condition('f.uid', $data['uid'], '=');
  $query->fields('f', array('entity_id'));
  $result = $query->execute()->fetchObject();

```

and also used following query statements

```
         $query->__toString()

         SELECT f.entity_id AS entity_id  FROM {flagging} f WHERE  (f.uid = :db_condition_placeholder_0)

```

I replace the **db\_condition\_placeholder\_0** with specify uid.
It return me the right result (2 results).

```
   **$query->execute()->fetchAssoc()**`, return one result.

```

# Answer
In Drupal 7, there are fetch methods that can help to avoid loops like that. From http://drupal.org/node/310072:

```
<?php
  // Retrieve all records into an indexed array of stdClass bjects.
  $result->fetchAll();
 // Retrieve all records into an associative array keyed by the field in the result specified.
  $result->fetchAllAssoc($field);

  // Retrieve a 2-column result set as an associative array of field 1 => field 2.
  $result->fetchAllKeyed();
 // You can also specify which two fields to use by specifying the column numbers for each field
  $result->fetchAllKeyed(0,2); // would be field 0 => field 2
  $result->fetchAllKeyed(1,0); // would be field 1 => field 0

  // Retrieve a 1-column result set as one single array.
  $result->fetchCol();
  // Column number can be specified otherwise defaults to first column
  $result->fetchCol($column_index);
 ?>

```
> 6 votes

---
Tags: 7, database
---


# Question
Title: Creating breadcrumbs based on content type relationships
Currently I have 3 different content types: Program, Chapter, Item. A program contains multiple chapters and a chapter contains multiple items. These are related to one another using node reference field types.

On the item page I would like to have a breadcrumb listing: Program --\> Chapter that is related to that specific item node.

I've looked into Custom Breadcrumbs and Page Breadcrumbs, but can't seem to figure out how to pull in the chapter and program that it is related to.

# Answer
For the time being I was able to figure it out by adding node reference fields to each of the content types. Then referencing my items to the chapters. I then found the Corresponding Entity Reference Module and used that to link them up. Using Custom Breadcrumbs I could use the reference tokens to create my breadcrumb.

Only downside is that I had to go into each item node. Took some time!
> 1 votes

# Answer
Try achieving it by Hansel Breadcrumb module. I don't have experience with situation of your kind but it works well for rule based breadcrumb. Module page describe :

> * Rules can be organized in a hierarchical structure.
> * Possible to leave breadcrumbs as is for specific sections.
> * Other modules can add switch types and breadcrumb actions by implementing the hansel\_switch\_types and hansel\_action\_types hooks.
> * An import / export module is included.
> * Export configuration in DOT format for visualisation (new).
> * Test functionality is available where you can see which steps are executed to get the actual breadcrumbs for a given path.
> * Integration with forum module (new).
> * Integration with token module.
> * Integration with domain module.
> * Integration with og module (new).
> * Integration with realname module.
> * Settings for trimming of titles and whole breadcrumb items.
> 0 votes

---
Tags: 7, breadcrumbs
---


# Question
Title: Using db_insert with a reserved keyword as the column name
It appears that db\_insert() (Drupal 7) fails when I try to specify a column name which is one of the reserved keywords (in this case, `insert`). I tried finding a way to use the back tick syntax which works with a direct SQL command, `insert`, but it still does not seem to work.

Googling so far has only confirmed this problem and returned suggestions to change the column name.

Is this the only solution, or is some other way to get db\_insert to work (there's a good reason why the column is called `insert` in our application)

thanks!

# Answer
You can try to pass column name in \`parenthesis\` to db\_insert. Just be sure you escaped them if needed, as they have their own meaning in php itself. If this does not work, well, you can:

* fill a bug against core, or post in existing one.
* use good old db\_query
* Or use thesaurus to get rid of reserved words from your app. There is always a "good reason" to use them, of course there is for any common word, but word-oriented languages simply have to reserve some words.
> 1 votes

# Answer
Use '\`parenthesis\`' inside single qoute. It worked for us.
> 1 votes

---
Tags: database
---


# Question
Title: Site dead after Devel Module and Library sethtmldom
After installing Devel Module (and Library simplehtmldom), the Drupal7 site is completely dead. Have already set the module to 0 on System table in database, and the module files removed by FTP. But still no recovering. How to remove simplehtmldom Library? What else to recover the site? Thanks.

# Answer
> 0 votes
You can try using Registry Rebuild

Project page says..

> THIS IS NOT A MODULE. YOU CAN'T ENABLE IT. FOLLOW THE INSTRUCTIONS.
>
> Make a backup of your database before running this. It won't break your database, but we can't improve this unless we have broken databases that it doesn't quite do the job for.
>
> There are times in Drupal 7 when the registry gets hopelessly hosed and you need to rebuild the registry (a list of PHP classes and the files they go with). Sometimes, though, you can't do this regular cache-clear activity because some class is required when the system is trying to bootstrap.
>
> When would you need Registry Rebuild? You might get something like:
>
> PHP Fatal error: Class 'EntityAPIControllerExportable' not found in ...sites/all/modules/rules/includes/rules.core.inc on line 11

# Answer
> -1 votes
Look in the error log to see an actual error. Put the modules you deleted back in the folder. Try uninstalling them with Drush.

Also, Drush can help you diagnoze - it can print error messages even if the whole site goes WSOD.

Basically, devel + htmldom won't ruin your site, unless you are tight on memory. If that's try, set max memory in php.ini to 256M or 512M.

And on the contrary, you can try deleting these modules folder manually and seeing of the site runs. Also, you can try to remove all the contrib modules folder as a whole and seeing if that helps.

Some more things - check if error messages are disabled (should be enabled) for development in php.ini. I fyou have little memory and no error messages enabled, that any case like htis will be a nightmare ;)

---
Tags: debugging
---


# Question
Title: How to include a view in a specific region defined in a custom layout?
I defined a set of views that I would like to include in specific regions ordered in a particular way through a custom layout. However, the block menu does not allow me to select these regions. All I can do is to give an order (1, 2, 3, etc.) to these views, which does not solve my problem because I need the views' outcomes to show up in these specific areas of the page.

I've looked up in many places but I couldn't find any answer to that question. Someone could give me a hint?

Thanks a lot! Igor

# Answer
> 0 votes
You can embed views anywhere with php with views\_embed\_view(). Please refer https://api.drupal.org/api/views/views.module/function/views\_embed\_view/7

---
Tags: views, blocks
---


# Question
Title: Omega Theme Renders a Container inside of a Container
I currently have a view listing a set of products via rendered entities as Teasers. However the Omega Theme is taking each teaser and adding the container-24 class to it eliminating the ability for me to have the teasers display inline. Below is an image attached, why is Omega doing this?

http://i.imgur.com/H1izEsp.jpg

# Answer
> 0 votes
Yeah, I have seen that before with Omega 3 - its presuming too much :) What you can do to work around this, is get the node template file, and create a template file for a teaser mode, and reference it in template.php. One sample of doing that is here: What is the template suggestion for node 'teaser' view mode?

---
Tags: theming
---


# Question
Title: jquery date picker in views exposed filter changes the date values
I have a node type "tasks" and created a view so that current logged in user can see his/her assigned tasks. I have used a "time ago" formatter in the field "deadline" which shows the remaining time to the deadline correctly. I have also created a filter for "deadline" and expose this filter. The selected options are as follows

The filter is correctly working if I choose "Select" in "Date selection form element" under settings for the "deadline" filter as can be seen below

However, when I change the "Date selection form element" to either "Plain" or "Popup", the duration in "Due In" field changes by a day that means if today is 5th March and the task is due on 6th March 2014 by 14:00, the "Due In" field will show 13 hours xx minutes (see image below)

I really don't understand what is the problem. Any suggestions?

# Answer
> 0 votes
This is a known issue (bug) of Views. You can find details here: Exposed grouped filter for date not working.

---
Tags: 7, views, datetime
---


# Question
Title: How to automatically load block--[blockname].tpl.php to region--[regionname].tpl.php
I have multiple customized blocks with different content (eg. Advertisements, Quotes, Youtube videos, etc..)

```
block--apple.tpl.php
block--pineapple.tpl.php
block--orange.tpl.php

```

Question: How can I automatically assign these blocks from different regions for example:

```
block--apple to sidebar_first region
block--pineapple to sidebar_right region
block--orange to region--myCustomRegion

```

Is there a theme function that automatically fills my target REGIONs with these BLOCKs without using the dashboard. I just want all blocks is ready when my theme is installed. Thank you very much in advance.

# Answer
There is no *theming* function to do this, and there cannot be, because assigning block to regions is more logic than theming matter. So you should do it at module level.

When you are implementing `hook_block_info()`, you can specify default region, like this:

```
$blocks['example_empty'] = array(
  'info' => t('Example: empty block'),
  'status' => TRUE,
  'region' => 'sidebar_first',
  'visibility' => BLOCK_VISIBILITY_LISTED,
  'pages' => 'node/*',
);

```

You can also use `hook_block_info_alter()` to provide default regions for blocks not defined in your module.

See Examples for developers, block example for more details and samples.
> 2 votes

---
Tags: blocks, theming
---


title: How to add a form_token to a login form

text:
# Question
Title: How to add a form_token to a login form
For security purposes, I need to add a form\_token to the login form. However, when (in hook\_form\_alter) I use the same code Drupal uses in form.inc for other forms, the validation fails because the token calculated during validation is different from the one calculated originally.

The code I'm using is:

```
if (!isset($form['#token'])) {
  $form['#token'] = $form_id;
  $form['form_token'] = array(
    '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
    '#type' => 'token',
    '#default_value' => drupal_get_token($form['#token']),
    // Form processing and validation requires this value, so ensure the
    // submitted form value appears literally, regardless of custom #tree
    // and #parents being set elsewhere.
    '#parents' => array('form_token'),
  );
}

```

I'm calling the form with drupal\_render(drupal\_get\_form('user\_login')). I'm aware that Drupal is not using the form\_token on the login page because it is often cached, but I have disabled the cache for that page in hook\_init with:

```
$GLOBALS['conf']['cache'] = FALSE

```

How can I add and validate a form\_token in the login form? I'm using Drupal 7.

Some extra info as to why I need this. The request to secure login forms against CSRF came up during a security scan and although I do not agree with the explanation for the request (easier to setup a brute force attack, despite auto blocking logins in such cases), there is a good explanation on stackoverflow as to why this still can be a good idea: Do login forms need tokens against CSRF attacks?

# Answer
I ended up (as suggested) adding a token to all unsecured forms with hook\_form\_alter.

Seemed efficient to use drupal\_get\_token() for this, but that did not work because the session ID (used by drupal\_get\_token() to generate a token) alters when an (anonymous) user logs in.

I therefore stored the first session id (when displaying the login page) in $\_SESSION so I could retrieve it when validating. But putting something in $\_SESSION apparently prevents Drupal from regenerating the session\_id. And now that the session id is preserved during login, drupal\_valid\_token() also works as expected so I did not have to write a special token validation function.

This is the code I ended up with:

```
function MY_MODULE_form_alter(&$form, $form_state, $form_id) {
    // add a custom csrf token for forms that do not have one
    if ($!isset($form['#token'])) {
        $form['anon_token'] = array(
            '#type' => 'token',
            '#default_value' => drupal_get_token()
        );

        $form['#validate'][] = 'MY_MODULE_validate_anon_token';

        // store current session id
        // touching $_SESSION alone seems to preserve the session id after login
        $sess_id = session_id();
        if (isset($_SESSION))
            $_SESSION['anon_session_id'] = $sess_id;
        else
            $_SESSION = array('anon_session_id' => $sess_id);
    }
}

function MY_MODULE_validate_anon_token($form, &$form_state) {
    $token = '';
    if (isset($form_state['values']['anon_token']))
        $token = $form_state['values']['anon_token'];

    if (!drupal_valid_token($token)) {
        // not a valid token!
        $path = current_path();
        $query = drupal_get_query_parameters();
        $url = url($path, array('query' => $query));

        // Setting this error will cause the form to fail validation.
        form_set_error('form_token', t('The form has become outdated. Copy any unsaved work in the form below and then <a href="@link">reload this page</a>.', array('@link' => $url)));
    }
}

```
> 4 votes

# Answer
Usually the forms are built with token only for authenticated users. Tokens are session-bound and forms displayed to anonymous users are cached in cache\_form table, and a token cannot be assigned for them. If you need a different token for a different purpose, then you can add one by yourself without using the `#token` key. Try using `$form['my_special_token'] = some_token`. Then add a validation function to check if the special token is valid.

In any case, your question needs more information about the "security reason" for adding a token. Perhaps then we can have a better idea of what to be done.
> 2 votes

# Answer
I also had the same use case come up in a previous project, where we needed form tokens attached to forms for anonymous users to ensure they were legitimate submissions from our site.

I used the following **hook\_form\_alter** code to add a token:

```
  if(!isset($form['#token'])) {
    $form['#token'] = $form_id;
    $form['form_token'] = array(
      '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
      '#type' => 'token',
      '#default_value' => mymodule_generate_token($form['#token']),
    );
  }

```

Then I used this custom function to generate the token for me:

```
function mymodule_generate_token($form_id){
  $secret = 'my-unique-string'; //could be todays date, whatever you want to make it.
  return drupal_hmac_base64($form_id, $secret. drupal_get_private_key() . drupal_get_hash_salt());
}

```

Then I also wrote a utility function which checks to see if the token coming from an anoymous form is valid:

```
function mymodule_check_valid_token($form_token, $form_id){
  return ($form_token == mymodule_generate_token($form_id));
}

```

Hope this helps
> 2 votes

---
Tags: 7, users, forms
---


# Question
Title: Including a PHP file in Drupal via BLOCKS, or REGION
Hi I am newbie in Drupal, I have problem about theming.

I have a PHP file ads.php that contains random advertisements now just wondering what is the perfect way to include that ads.php

Can I just use the PHP include command

```

include('ads.php');

```

or import it as a block for example block--ads.php or region--ads.php I DON'T KNOW IF THIS IS POSSIBLE. I am still confused on how drupal theming works.

Please help me.

# Answer
You need to create a block template in your themes template folder.

To do this, you would create a new block, in Structure \> Blocks, give it a bit of dummy content and save it in a region.

Then inspect the ID of the block in the source, or in Chrome Dev Tools, or Firebug, it should be something like block-block-1

In your themes template folder, copy the file `block.tpl.php` and rename the copied file `block--block--1.tpl.php`

In that file, you should see something like...

```
<div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>
  </div>

```

Just replace the `<?php print $content ?>` with your content from ads.php

Then, in Performance \> Development, flush the cache, and you should see your template replace the content of the block you created.
> 3 votes

# Answer
You can enable the PHP Filter core module and add your php code directly to the block.

1. Enable the module
2. Create a new block
3. Change the text format to PHP Filter
4. add your PHP code to the block body.
5. Save it.
6. Clear your cache.
> 0 votes

# Answer
The answer is to create block but on own module. This way will prevent block from deletion by the UI.

Creating Drupal-7.x module

Use hook\_block\_info and hook\_block\_view - see more for them on api.drupal.org

hook\_block\_info is trivial, so just replace with your info.

ex. of hook\_block\_view

```
function hook_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'my_block':
      $block['subject'] = t('My block');
      $block['content'] = awesome_ads();
      break;

  return $block;
}

function awesome_ads() {
  $output = '';

  // your code here

  return $output;
}

```

Then enable your module and show "My blok" on block UI.

edit:

To include your php file, use instead '// your code here' on function above

```
module_load_include('inc', 'my_module', 'ads');

```

Place ads.inc file with your php code in my\_module folder (if name of your module is my\_module)
> 0 votes

# Answer
From what I understand, you want to output some custom content on a page (some ads, in this case).

**This isn't something you should do at the theme layer, as the theme layer is there for changing markup and appearance, not adding content.** The general rule is: if there isn't already a module that does this for you, you'll need to create one.

There's documentation here on how to create a module: https://drupal.org/developing/modules/7 It's only a couple of files to get started.

If you download the Examples module, you'll find examples of how to create blocks in a module. You'll be shown how to use hook\_block\_info() and hook\_block\_view() to create your block. Once you're up and running you'll be able to make it appear in whichever region you need.

There's some great information, too, about writing secure code. Use of the PHP filter isn't generally encouraged, as it's seen as a security risk. It will be also worth checking that the PHP for the ads that you're including is well written and secure.
> 0 votes

---
Tags: blocks
---


# Question
Title: Why are some contrib module functions not recognized?
I can't seem to get the latest twitter module to work with my site.

I have a custom module that does some sanity checks on user-imported twitter accounts and my site keeps failing at this point. After some digging I noticed the twitter module functino `twitter_account_load()` is not recognized at all.

Devel test code to reproduce:

```
dpm(module_load_all()); // returns 1
dpm(module_exists('twitter')); // returns 1
dpm(twitter_account_load('@twitter')); // returns white screen of death

```

Apache error log:

> PHP Fatal error: Call to undefined function twitter\_account\_load() in /var/www/mysite/httpdocs/sites/all/modules/contrib/devel/devel.module(1285) : eval()'d code on line 4, referer: http://my.site.com/devel/php

Drupal Version 7.26 Twitter Version 7.x-5.8

What I have tried so far:

* Cache cleared
* Twitter module upgrade to latest 5.8
* Cache cleared
* Twitter module reinstall
* Cache cleared
* ...

Nothing worked.

Any idea why?

# Answer
Do module load include of twitter.inc in which above function was defined.. .module files are automatically included, but .inc are not. So you need to include them using above function...

```
module_load_include('inc', 'twitter', 'twitter');
dpm(module_load_all()); // returns 1
dpm(module_exists('twitter')); // returns 1
dpm(twitter_account_load('@twitter'));

```
> 5 votes

---
Tags: 7, installation, social-network
---


title: how to disable required field in form

text:
# Question
Title: how to disable required field in form
I want to disable custom field in form, my field name is `field_course_display_ref` and it is entity reference.
I try `$form['field_course_display_ref']['und']['#attributes']['disabled'] = 'disabled';` but when form submit it return **the `field_course_display_ref` is required** , I also try `$form['field_course_display_ref']['#disabled'] = TRUE;` but not work and field not disabled( user can change it).
also I try to remove `#require` with $form\['field\_course\_display\_ref'\]\['und'\]\['#required'\]=FALSE; but nothing happen and when form submit, return **the `field_course_display_ref` is required** .

How can I disable required field in form ?

I create form in callback of menu ,part of my code

```
function cdigitdev_pre_register_ym() {
    global $user;
    drupal_add_js(drupal_get_path('module', 'cdigitdev') . '/js/cdigitdev.js', array('scope' => 'footer'));
    $nid = intval(arg(2));
    $productId = intval(arg(3)); //it will set to null if arg(3) not set ; equal to $productId=arg(3)? intval(arg(2)):NULL;
    module_load_include('inc', 'node', 'node.pages');
    $form = node_add('pre_register');
    $form['field_course_schedules']['#disabled'] = TRUE;
    //$form['field_course_schedules']['und']['#disabled'] = TRUE;
.
.
.
.
    return drupal_render($form);
}

```

# Answer
I found my problem, in this manner create form with :
`module_load_include('inc', 'node', 'node.pages');
 $form = node_add('pre_register');` `#required=false` and `#disabled=true` not work.

I remove them form my function and put them in `form_alter` and work correctly , both `#required` and `#disabled` .

My problem resolved but really I dont understand why it not work in my function and in hook\_form\_alter work .
> -1 votes

---
Tags: forms
---


# Question
Title: End points for services module not working
I have setup an endpoint following this guide. I am getting mixed results, as **endpoint/node.xml** successfully returns a list of content nodes.

When I try and load an individual node as xml, I just get a blank xml document example below, clicking **/endpoint/node/1000.xml** results in:

```
<?xml version="1.0" encoding="utf-8"?>
<result></result>

```

Also if I try and load it as a ...node/1000.json it just returns false.

Error log is really vague, content is open to non-authenticated users so permissions shouldn't be an issue.

Any help would be fantastic.

# Answer
> 0 votes
Found a work around for this issue, rather than use the node id I am using the UUID. This is now successfully loading the content.

The UUID id is pulled out of the main list of nodes at **/endpoint/node.xml**, giving a working url of:

**/endpoint/node/e2349095-de4f-4827-919f-3ec28cf392a8**

---
Tags: services
---


# Question
Title: Drupal 7 "undefined function" fatal error; from FTP error
One of the guys here deleted a module folder, in error, from drupal 7 site using FTP (I know but it was a mistake).

the Commerce module was deleted. Now can not access the site at all as we are getting a fatal error Fatal error: Call to undefined function commerce\_pricing\_attributes\_property\_info\_callback() in /var/www/sites/all/modules/contrib/entity/modules/field.info.inc on line 30

Anyone know how to correct it? line 30 is $callback($info, $entity\_type, $field, $instance, $field\_type);

The function in question is below

```
function entity_metadata_field_entity_property_info() {
  $info = array();
  // Loop over all field instances and add them as property.
  foreach (field_info_fields() as $field_name => $field) {
    $field += array('bundles' => array());
    if ($field_type = field_info_field_types($field['type'])) {
      // Add in our default callback as the first one.
      $field_type += array('property_callbacks' => array());
      array_unshift($field_type['property_callbacks'], 'entity_metadata_field_default_property_callback');

      foreach ($field['bundles'] as $entity_type => $bundles) {
        foreach ($bundles as $bundle) {
          $instance = field_info_instance($entity_type, $field_name, $bundle);

          if ($instance && empty($instance['deleted'])) {
            foreach ($field_type['property_callbacks'] as $callback) {
              $callback($info, $entity_type, $field, $instance, $field_type);
            }
          }
        }
      }
    }
  }
  return $info;

```

# Answer
If you have a backup this is the time to use it.

If not you should:

1. Put your Site in maintenance mode from command line: https://drupal.org/node/590468 or by using Drush: `drush vset maintenance_mode 1`
2. Replace the deleted module with exactly the same version in exactly the same place.
3. Run update.php either from drush: `drush updb` or command line: https://drupal.org/upgrade/running-update-php
4. All *should* be fine.

Please report back if this works or if another solution is found
> 0 votes

---
Tags: 7, commerce
---


title: Drupal file upload field via popup

text:
# Question
Title: Drupal file upload field via popup
So I'm using a "file" type input inside a form which is called within a popup...but then whenever I submit that form inside the popup after having selected a file, the popup always return an error....

Is there a way to prevent this from happening and to successfully submit the form accordingly even with a file upload?

# Answer
> -1 votes
I made it by creating 'VIEWS' by selecting the facebook style micro publisher images as 'field' and filtered according to my requirement.

---
Tags: forms, ajax, files, javascript
---


title: Allowing ajax link clicks to propagate

text:
# Question
Title: Allowing ajax link clicks to propagate
A click event on a link with the `use-ajax` class on it does not seem to propagate up the DOM. Is this true? If so, is there a setting that will allow it to propagate?

Not being a JS whizz, I'm struggling to see where the call is made (`preventDefault`? `return false`?) that blocks the propagation. I've had a look at misc/ajax.js and there is a setting `element_settings.prevent` that looks like it might be relevant, but I haven't found any documentation on this.

# Answer
> 1 votes
It's in `Drupal.ajax.prototype.eventResponse`, round about line 265:

```
// For radio/checkbox, allow the default event. On IE, this means letting
// it actually check the box.
if (typeof element.type != 'undefined' && (element.type == 'checkbox' || element.type == 'radio')) {
  return true;
}
else {
  return false;
}

```

It's hard-coded, but this is JS - you can just monkey-patch `Drupal.ajax.prototype.eventResponse` and get it to do whatever you like :)

---
Tags: 7, ajax, javascript
---


# Question
Title: How do I pass an additional variable to function theme_item_list
I need an additional variable to be available to the function `theme_item_list`. How do I correcly pass my variable so that I can alter the function like so:

```
function theme_item_list($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];
  $MY_VAR = $variables['MY_VAR'];

```

Here is my render array:

```
  $node->content['list'] = array(
    '#theme' => 'item_list',
    '#items' => $items,
    '#weight' => 2,
    '#prefix' => '<div id="list">',
    '#suffix' => '</div>',
  );

```

Thanks

# Answer
> 2 votes
Implement `hook_theme_registry_alter()` to let Drupal know about the new var:

```
function MYTHEME_theme_registry_alter(&$registry) {
  $registry['item_list']['variables']['MY_VAR'] = NULL;
}

```

Then override the theme function:

```
function MYTHEME_item_list($vars) {
  // Copy/change original theme_item_list as required.
  // $vars['MY_VAR'] is available as long as it has been passed in.
}

```

And just make sure you pass the var in your render array:

```
$node->content['list'] = array(
  '#theme' => 'item_list',
  '#items' => $items,
  '#weight' => 2,
  '#prefix' => '<div id="list">',
  '#suffix' => '</div>',
  '#MY_VAR' => 'foo',
);

```

---
Tags: theming
---