# Question
Title: I get image field upload errors with a custom node_add() form
I've exposed a node\_add form and styled it for certain roles to use. The form is being displayed in panels, through an 'article' node type using the PHP text filter. Users can create new nodes with no issues, but there are errors displayed when users try to upload an image in the form:

> Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function 'node\_form' not found or invalid function name in drupal\_retrieve\_form() (line 795 of /var/www/html/includes/form.inc).
> Notice: Undefined index: #node in comment\_form\_node\_form\_alter() (line 1193 of /var/www/html/modules/comment/comment.module).
> Notice: Trying to get property of non-object in comment\_form\_node\_form\_alter() (line 1210 of /var/www/html/modules/comment/comment.module).
> Notice: Undefined index: #node in menu\_form\_node\_form\_alter() (line 629 of /var/www/html/modules/menu/menu.module).
> Notice: Trying to get property of non-object in menu\_form\_node\_form\_alter() (line 629 of /var/www/html/modules/menu/menu.module).
> Notice: Undefined index: #node in menu\_form\_node\_form\_alter() (line 630 of /var/www/html/modules/menu/menu.module).
> Notice: Trying to get property of non-object in menu\_form\_node\_form\_alter() (line 630 of /var/www/html/modules/menu/menu.module).
> Notice: Undefined index: field\_obs\_image in file\_ajax\_upload() (line 271 of /var/www/html/modules/file/file.module).
> Notice: Undefined index: #suffix in file\_ajax\_upload() (line 280 of /var/www/html/modules/file/file.module).

The actual node form code looks like this:

```
module_load_include('inc', 'node', 'node.pages');
$form = node_add('observation');
print drupal_render($form);

```

I have also tried this code with the same results:

```
$node_type = 'observation';
$form_id = $node_type . '_node_form';
// maybe add current users info
global $user;
// create a blank node

$node = new stdClass();
$node->uid = $user->uid;
$node->name = (isset($user->name) ? $user->name : '');
$node->type = $node_type;
$node->language = '';
node_object_prepare($node);
$output = drupal_render(drupal_get_form($form_id, $node));

print $output;

```

The content type being added is 'observation'. I am also using the identical technique on another page with a different content type, and it results in the exact same error. The error appears directly above the image field during the AJAX image upload call.

I have also done a debug\_backtrace() near line 795 of form.inc and can post the results if requested.

I have read all of these articles, to no avail:

Does anyone have an idea as to where I can start looking? This seems to be a tough problem. Thanks for your time!

# Answer
> 1 votes
You should get node\_form in this way:

```
{
  ...
  // For node_add
  module_load_include('inc', 'node', 'node.pages');
  return drupal_render(node_add('type'));
}

```

or

```
{
  ...
  // For node edit
  $node = node_load($nid);
  module_load_include('inc', 'node', 'node.pages');
  return node_page_edit($node);
}

```

And call form\_load\_include function on form alter hook:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_[your_form_id]_alter(&$form, &$form_state) {
  form_load_include($form_state, 'inc', 'node', 'node.pages');
  // your code goes here if needed
}

```

# Answer
> 3 votes
I believe the problem is, roughly, that while you've ensured the include happens before initial form build, that include doesn't happen when the AJAX file upload processing attempts to rebuild the form... So node\_form() function is undefined and things fall apart.

The solution that worked for me was to use form\_load\_include() in place of module\_load\_include(). According to its documentation, this alternate function exists for this express purpose - "ensures that the include file is loaded whenever the form is processed."

# Answer
> 0 votes
For what it's worth, I never did find a solution for these errors. I remain convinced that the problem lies in the calling of the `node_add()` function from a php-text-type node.

My final solution was to use the Form Block module instead.

# Answer
> 0 votes
Yeah, apparently you should add these line to the menu item array:

```
'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',

```

it is not enough to just add `module_load_include('inc', 'node', 'node.pages');` before printing the form.

---
Tags: 7, forms, ajax, media
---


# Question
Title: How to create a module to process AJAX request?
I want to create a module to process some AJAX request like this:

```
$.ajax({
    url:'/?q=mymodule/path',
    dataType:'json',
    type:'POST',
    data:{'key':'abc', 'value':'123'},
    success:function(data){
        /*do somthing*/
    },
    error:function(){
        /*do somthing*/
    }
});

```

So which hook function should I implement?

# Answer
If you are tying your functionality to Drupal, use Ajax framework commands.

If you want to process any arbitrary incoming request, (ajax or otherwise) implement a Services resource.
> 2 votes

# Answer
You need to do something like this:

```
var element_settings = {};
element_settings.url = $(this).attr('href');
element_settings.event = 'click';
element_settings.progress = {
  type: 'throbber',
  message: ''
};
var base = $(this).attr('id');
Drupal.ajax[base] = new Drupal.ajax( base, this, element_settings );

```

Then use the AJAX framework commands in your page callback to pass instructions back to Javascript.
> 1 votes

---
Tags: 7, hooks, ajax
---


# Question
Title: How can i put two forms build in one module to two URLs
I am very new to drupal and working with D7

I have created two form with a custom module. mysite.com/custom is showing both the forms at the same time

I want each of the form to be shown with 2 different URLs. eg mysite.com/custom1 eg mysite.com/custom2

How is it possible.OR is it not possible at all. am i totally wrong in understanding how the module and forms work?

code

```
function custom_menu() {
  $items['custom'] = array(
      'title' => t('Custom'),
      //'page callback' => 'drupal_get_form',
      'page callback' => 'custom_page_callback',
      //'page arguments' => array('custom_form'),
      //'access arguments' => array('custom module'),
      'access callback' => TRUE,
  );

  return $items;
}

function custom_page_callback() {
  $build = array();

  // Render your two forms here.
  $build['form_one'] = drupal_get_form('custom_form');
  $build['form_two'] = drupal_get_form('custom_second_form');

  return $build;
}
/**
 * Our custom form.
 */
function custom_form($form, &$form_submit) {
  $form['title'] = array(
      '#title' => t('Give a title'),
      '#type' => 'textfield',
      '#required' => TRUE,
  );
  $form['name'] = array(
      '#name' => t('Give a Name'),
      '#type' => 'textfield',
      '#required' => FALSE,
      '#maxlength' => 25,
      '#size' => 10,
  );
  $form['submit'] = array(
      '#value' => 'Add',
      '#type' => 'submit',
  );
  return $form;
}
/**
 * Our custom form second.
 */
function custom_second_form($form, &$form_submit) {
  $form['title'] = array(
      '#title' => t('Give a title'),
      '#type' => 'textfield',
      '#required' => TRUE,
  );

  $form['submit'] = array(
      '#value' => 'Add',
      '#type' => 'submit',
  );
  return $form;
}

```

Thanks all

# Answer
> 3 votes
Have to make small change on function custom\_menu.

Try this code.

```
function custom_menu() {
  $items['custom/first'] = array(
      'title' => t('Custom'),
      //'page callback' => 'drupal_get_form',
      'page callback' => 'custom_page_first',
      //'page arguments' => array('custom_form'),
      //'access arguments' => array('custom module'),
      'access callback' => TRUE,
  );
  $items['custom/second'] = array(
      'title' => t('Custom'),
      //'page callback' => 'drupal_get_form',
      'page callback' => 'custom_page_second',
      //'page arguments' => array('custom_form'),
      //'access arguments' => array('custom module'),
      'access callback' => TRUE,
  );

  return $items;
}

```

# Answer
> 3 votes
If you want to show two forms in two different pages, just define two menu items.

```
function custom_menu() {
  $items['custom'] = array(
    'title' => 'Custom form #1',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_form'),
    'access callback' => TRUE,
  );

  $items['other_custom'] = array(
    'title' => 'Custom form #2',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('custom_second_form'),
    'access callback' => TRUE,
  );

  return $items;
}

```

As side note, the content of the "title" and "description" are not passed to `t()`, as I did.

---
Tags: forms
---


# Question
Title: ajax_render() - CSS not adding/updating in IE
I'm using AJAX to update page content. In my page callback I have a few commands and end with ajax\_render().

When I click the AJAX link from another page, the content updates, all my JS and CSS for that page are added, and everything works perfectly. However, the CSS is not being applied in IE.

It appears that the following two lines in ajax.js are causing the problem:

```
var new_content_wrapped = $('<div></div>').html(response.data);
var new_content = new_content_wrapped.contents();

```

If I hack ajax.js and change (line 519):

```
wrapper[method](new_content);

```

to:

```
wrapper[method](response.data);

```

it works!! Any ideas?

# Answer
The solution for me was CSS aggregation in Drupal: It needs to be on to work.
When it is disabled, it uses @import, which IE does not like if that is used to append to the head. When it is enabled, it appends links instead, which then works with IE.

The same problem is described here.
> 2 votes

---
Tags: 7
---


title: Why is this query failing?

text:
# Question
Title: Why is this query failing?
I'm using `CONCAT` in a join. It works well in PHPMyAdmin, but the equivalent Drupal query doesn't work.

```
$query->join('taxonomy_term_data', 'td', 'sbc.tname LIKE CONCAT( td.name,  "%\" ) AND td.vid = sbc.vid');

```

This query causes the following error:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column '%\\' in 'on clause'

However, the following query works fine.

```
$query->join('taxonomy_term_data', 'td', 'sbc.tname LIKE CONCAT( td.name,  \'%\' ) AND td.vid = sbc.vid');

```

The only difference between the two queries is the string quotes: In the first one I used double quotes to wrap %; in the second one I used single quotes.

PHPMyAdmin gives me the result whether the % is wrapped with single quotes, or double quotes. (Actually, it should.)

I think there is something I'm missing. I'm just curious to know what it is.

# Answer
I tried executing a query similar to the one you are showing using an desktop application to connect to the MySQL server running on my computer, and I got the following error:

> You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"%\\") AND td.vid = n.vid' at line 1

Drupal reported the following error:

> PDOException: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column '%\\' in 'on clause': SELECT n.\* FROM {node} n INNER JOIN {taxonomy\_term\_data} td ON n.title LIKE CONCAT( td.name, "%\\" ) AND td.vid = n.vid;

The PDO driver seems throwing the wrong exception.

The error is caused from the fact you are escaping the second quote, and there isn't any other quote character, except the one ending the join condition.

If I recall correctly, you should not use the double quotes inside SQL strings. Rewrite the query as following, and it works.

```
$query->join('taxonomy_term_data', 'td', "sbc.tname LIKE CONCAT(td.name,  '%') AND td.vid = sbc.vid");

```

I also tried escaping the % character with another %, as suggested by @Clive, but the following still raised the same exception.

```
$query->join('taxonomy_term_data', 'td', 'sbc.tname LIKE CONCAT(td.name,  "%%\") AND td.vid = sbc.vid');

```

The following worked too, but the result doesn't change, compared to the first query I wrote.

```
$query->join('taxonomy_term_data', 'td', "sbc.tname LIKE CONCAT(td.name,  '%%') AND td.vid = sbc.vid");

```
> 3 votes

---
Tags: 7, database
---


# Question
Title: Separate urls for child node with multiple parent nodes?
I have a question. I am currently building a site with different sections (a content type with childrens of type normal-content), where some content is identical on parts of the site but some pages have their own version of the page. Se example below

section1/about\_us (nid 45)
section2/about\_us (nid 45)
section3/about\_us (nid 62)
section4/about\_us (nid 45)

The issue in my example is that when using pathauto to create the urls the url and the hierarchy is created correctly but only one of the nodes is treated as a parent in regards of the url. They all get the same url section1/about\_us (except the one that is created separately). Which I think is the correct way to create the urls but in my case I need separate urls even if the page loaded is the same since it reflects a virtual hierarchy. Is there a way for me to hook into some function to let the pathauto create separate urls for each section?

Best regards, Jocke

# Answer
Though I agree with Clive, nodehierarchy module should help you out on your issue.
> 0 votes

---
Tags: 6, nodes
---


title: How to submit webform programmaticaly?

text:
# Question
Title: How to submit webform programmaticaly?
I need to submit data to a webform.

I receive data from POST submission from mobile application ("webservices").

So I try something like :

```
$form_data = array();
$form_data['values']['firstname'] = $user->field_civilite['und'][0]['tid'];
$form_data['values']['lastname'] = $user->field_prenom['und'][0]['value'];
$form_data['values']['mail'] = $user->field_nom['und'][0]['value'];

webform_client_form_submit(226, $form_data);

```

But this is don't do anything.

Someone have any idea to do that?

# Answer
webform can be programatically save, as shown in below example,

```
  $node = node_load($nid); //nid is the node id of your webform
  global $user;

 //the values to save
  $data = array(
    1 => array('value' => array($first_value)),
    2 => array('value' => array($second_value)),
  );

  $submission = (object) array(
    'nid' => $nid,
    'uid' => $user->uid,
    'submitted' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => FALSE,
    'data' => $data,
  );

  module_load_include('inc', 'webform', 'includes/webform.submissions');
  webform_submission_insert($node, $submission);
  webform_submission_send_mail($node, $submission);

```
> 10 votes

---
Tags: 7, webforms
---


title: How to display a block only for Admin

text:
# Question
Title: How to display a block only for Admin
I want a block to be visible only for Admin in Drupal 6.

To do it I've selected the third option(Show if the following PHP code returns TRUE (PHP-mode, experts only).) and entered the php code:

```
<?php
global $user;return $user->uid == 1;
?>

```

But the problem is that now this block shows only when I'm on some specific urls while logged in admin and not always when logged in admin. What's wrong?

I don't want to use the second option (Show on only the listed pages).

# Answer
One more way to check for admin rights, sure it works in Drupal 6.

```
if (user_access('access administration pages')) {
    // do something
}

```
> 2 votes

# Answer
In this case, if the Block was created from a view (if not then you can create one) you can set the access settings in the view edit mode:

By selecting permissions you can make access to this block fine grained, based on rarely granted permissions such as 'administer-permissions' which is a permission only Administrators are likely to have. click on the little 'cog-wheel' to the right of the 'Access' row under the view's basic settings in order to select the restriction you desire:

Please pay careful attention to the comment below the 'Default Access Options' list, as shown in the third image. It reads 'Only users with the selected permission flag will be able to access this display. Note that users with "access all views" can see any view, regardless of other permissions'.

You can remove the 'access all views' for the anonymous user under '/admin/user/permissions' and then set the permissions of your other views also. This gives more control over who sees what. Views by default have 'Access' set to 'Unrestricted' generally.
> 1 votes

# Answer
Sounds like an issue with your Drupal install. Is this a multisite or single? We have had issues with multisite inside of subfolders. For example: example.com/site1 example.com/site2 etc.

Cookies get all messed around when logged into one site and not the other. So it can make it seem like Drupal is behaving weird.

If this isn't your case you could always try assigning a role to Admin and then restricting the block that way instead of using PHP.
> 1 votes

# Answer
`$user->uid` will return an error if `$user` is not an object.

Protect your code with `try { } catch`
> 0 votes

# Answer
this code works for me: (insert in "Show block on specific pages:")

```
<?php
global $user;
if(isset($user)) {
  if($user->uid == 1){
  return true;
  }
}
?>

```

i see this block in all browsed pages. in what pages/urls are missing the block?
> 0 votes

---
Tags: 6
---


# Question
Title: Can I make a Drupal Book page parent with no content?
Is it possible to Organize Drupal Book pages under parent pages that are just headings, are not links and have no content?

I want to separate pages under headings but I don't want to create pages for these headings, just to add text to the navigation and use as a parent for pages.

# Answer
> 1 votes
Yes, create a new content type, call it headings, remove the body from it and let it have children.

see http://yoursite.com/#overlay=admin/structure/types/add

Create the heading content type and remove the body, add or remove anything you want or don't want while your there.

Then see: http://yoursite.com/#overlay=admin/content/book/settings

Add the new content type to the books modules allowed content types and your done.

# Answer
> 0 votes
For the Book module, each book is associated with a top-level page, which is a node; you cannot have a book without that node.

If you don't want content, you can simply leave the body of the top-level page empty.
As for not having a link shown in the navigation tree, that is only possible if you create a custom module that alters the content of the block output from book\_block\_view().

---
Tags: nodes
---


# Question
Title: Fatal error: in boostrap.inc line number 2913
I ma facing a Fatal error It says `Fatal error: require_once() [function.require]: Failed opening required '/home/myapp/myapp.com/sites/all/modules/views/modules/user/views_handler_field_user_name.inc' (include_path='.:/usr/local/lib/php:/usr/local/php5/lib/pear') in /home/myapp/myapp.com/includes/bootstrap.inc on line 2913`

I am unable to login,or add content type or create a view. Please help to overcome this issue.

I am very much need in it.

My site works fine if not logined.

# Answer
modules/user/views\_handler\_field\_user\_name.inc is one of the Views files.
Delete the /home/myapp/myapp.com/sites/all/modules/views directory (and the files it contains), and copy the Views files from the archive file you download from the project page. Just be sure to download the same version you installed before, and to copy the files in the same directory they were before. (The views.module file must be in /home/myapp/myapp.com/sites/all/modules/views/views.module, not /home/myapp/myapp.com/sites/all/modules/views/views/views.module, or /home/myapp/myapp.com/sites/all/modules/views.module.)
> 2 votes

# Answer
A check list, from things that I have seen happening here:

* Does the 'includes' subdirectory exist? Is it located directly under public\_html? (and not in a drupal/includes subdirectoy or anywhere else)
* Is the 'includes' subdirectory readable by the web server? (permissions at least 755, and not 700).
* Does the 'includes' subdirectory contain a 'bootstrap.inc' file? Does that file look undamaged (not zero length).
* Is the 'bootstrap.inc' file readable by the web server? (permissions at least 644, and not 600).
* Have you added any custom RewriteRules in Drupal's .htaccesss file?

Check it out more information here, I am sure this will help you..
> 1 votes

---
Tags: views, bootstrapping
---


# Question
Title: Programmatically schedule the execution of a component
I have found the function `rules_scheduler_schedule_task()` under the rules module which supposedly does exactly what I want, but I have trouble interpreting how the function arguments are built. The arguments of that function are an array with the following keys :

* config: The machine readable name of the to be scheduled component.
* date: When the component should be executed.
* identifier: User provided string to identify the task per scheduled

And finally :

* state: A rules evaluation state to use for scheduling.

I don't have any trouble with the first three arguments, but what is the meaning of the later (`state`) ? Is it where I put the arguments of the components ? Could someone provide an example ?

# Answer
I know this is an older post, but I had the same problem, and found this post. I found the answer so maybe someone can use it later:

```
$state = new RulesState();
$state->addVariable('variable_name', $variable, array());
// 3rd parameter is called $info it must be an array, but i don't know it's function

$task = array(
'identifier' => 'unique_id_of_scheduled_task',
'date' => time(), // timestamp
'config' => 'id_of_the_rule_component_to_run',
'state' => $state,
);

rules_scheduler_schedule_task($task);

```

So you have to create a RulesState object and pass in that in place of the 'state' parameter. I had to do this because in Rules I couldn't get the timestamp I wanted when I was configuring the "Schedule component evaluation" action.
> 6 votes

# Answer
The code for $State can be found in `rules/includes/rules.states.inc`. It looks like the class holds basic status information for a variety of conditions. Good hunting!
> 1 votes

---
Tags: 7, rules
---


# Question
Title: How to allow multiple parents (menu items) for a single node
How can I enable a single node to have multiple parents (D7)?

Is it possible to show the hierarchical structure in the menu, therefore breadcrumb?

Can I set a structure like the following?

Home \> Section 1 \> SubSection A \> 'my node' Home \> Section 2 \> SubSection B \> 'my node' Home \> Section 2 \> SubSection B \> 'my node'

Before you ask/suggest:

* I used nodehierarchy on a previous project, and the subfeature 'Allow multiple parents" seems a little buggy at the moment
* Duplicate content is not a problem here, since it's an intranet

Do you have any suggestion?

# Answer
> 2 votes
You should definitely use the taxonomy for this. Taxonomy allows you to have multiple sections/subsections with no effort whatsoever, and several terms can be added to each node.

However, for the breadcrumb, you'll have to code something about this. AFAIK, the default `terms` variable in a node template doesn't display the hierarchy, and the breadcrumb only shows one path.

Furthermore:

* taxonomy\_menu allows you to easily transform a vocabulary into some matching menu.
* Alternatively, you can get the taxonomy tree for each term associated with a node using `taxonomy_get_tree`. (And display it the way you wish.)

# Answer
> 4 votes
**The meny system can't do that**

The Drupal menu system does not support what you want to do. Each entry has exactly *one* parent (which is id -1 if at the top).

**The taxonomy module however, can**

One could map the menu structure onto a vocabulary tree. The complex part here will be the node \<=\> term mapping, as I'm not aware of a module for that.

However, it's also worth noting that given that nodes and terms are very similar in D7, it's entirely possible to just migrate to using Terms for your main content, if the multiple parents hierachy generally makes sense for you. This could avoid a lot complexity.

**Other options**

One also make something completely custom or build the hierachy directly onto the entities with entity references, or separately as relations.

**Node hierachy**

If there is a module that solves your problem, you should probably be using it. Since Node hierachy is apparently one such option, it's worth your attention. If it really is buggy, you may want to consider helping out with that, if it helps to avoid a large custom effort.

---
Tags: nodes
---


title: Non-tabs in quicktabs

text:
# Question
Title: Non-tabs in quicktabs
I'm using QuickTabs on a Drupal 6 site. I have a block in which I need to have some normal tabs and some pseudo-tabs, which look like tabs but are actually just links that load a whole new page. Is there a way to do this with quicktabs configuration? In particular, could I use `theme_quicktabs_tabs()` for this? If so, where do I start?

# Answer
You could always copy the tab HTML and put it somewhere outside the QuickTabs output, and then position them using CSS where you want them on the page.
> 0 votes

# Answer
I accomplished this by putting a theme\_quicktabs\_tab override in template.php.
> 0 votes

---
Tags: 6, blocks
---


title: Display a text field on a node/add form

text:
# Question
Title: Display a text field on a node/add form
I want to display a text field on a content type which is simply a paragraph of text (non-editable). Is it possible to add such a field.

The context: I have a node/add form available to anonymous users so that they can create a content type of 'contact form'.

I am using conditional fields to display certain fields based on the choices made in creating the contact form.

I would like to be able to add a 'message' that displays if they select a certain field.

For example: if the problem selected from a select box is 'forgotten password' then the paragraph message would appear directing the user to the retrieve password page via a link.

# Answer
> 2 votes
I think you can use Static Field module to add your text as a separate field. In this case it can be shown/hidden by conditional fields

---
Tags: nodes, entities
---


# Question
Title: How do I make a list of upcoming events in views with the date module?
I'm on D7. I have the date module installed and I want to make a views block of upcoming events. I have a content type "event" and it has a date field. The list needs to only show events that have a date past the current one (there is no real point in showing events that have already happened :) ). I am having no luck finding anything on how to do this and I feel like this functionality is a common need. Any suggestions?

EDIT:

Here is a test view I have created to show what I have tried. :)

Using "Date:Date" filter criterion

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Date */
$handler->display->display_options['fields']['field_date']['id'] = 'field_date';
$handler->display->display_options['fields']['field_date']['table'] = 'field_data_field_date';
$handler->display->display_options['fields']['field_date']['field'] = 'field_date';
$handler->display->display_options['fields']['field_date']['settings'] =
array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] =
array(
  'event' => 'event',
    );
/* Filter criterion: Date: Date (node) */
$handler->display->display_options['filters']['date_filter']['id'] =         'date_filter';
$handler->display->display_options['filters']['date_filter']['table'] = 'node';
$handler->display->display_options['filters']['date_filter']['field'] = 'date_filter';
$handler->display->display_options['filters']['date_filter']['operator'] = '>=';
$handler->display->display_options['filters']['date_filter']['granularity'] = 'second';
$handler->display->display_options['filters']['date_filter']['default_date'] = 'now';
$handler->display->display_options['filters']['date_filter']['date_fields'] =
array(
  'field_data_field_date.field_date_value' => 'field_data_field_date.field_date_value',
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;

```

Using "Content:Date" filter criterion

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

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Date */
$handler->display->display_options['fields']['field_date']['id'] = 'field_date';
$handler->display->display_options['fields']['field_date']['table'] = 'field_data_field_date';
$handler->display->display_options['fields']['field_date']['field'] = 'field_date';
$handler->display->display_options['fields']['field_date']['settings'] =
array(
  'format_type' => 'long',
  'fromto' => 'both',
  'multiple_number' => '',
  'multiple_from' => '',
  'multiple_to' => '',
);
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] =
array(
  'event' => 'event',
    );
/* Filter criterion: Content: Date (field_date) */
$handler->display->display_options['filters']['field_date_value']['id'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['table'] = 'field_data_field_date';
$handler->display->display_options['filters']['field_date_value']['field'] = 'field_date_value';
$handler->display->display_options['filters']['field_date_value']['operator'] = '>=';
$handler->display->display_options['filters']['field_date_value']['granularity'] = 'hour';
$handler->display->display_options['filters']['field_date_value']['default_date'] = 'now';

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;

```

# Answer
> 3 votes
All you have to do is create a new view that shows content of type 'event'... set that on the first page of creating your view. Make sure you check the 'block' option at the bottom - it's up to you whether you also want to create a page display or not, that's checked by default. Also, before moving onto the second page, make sure that your view is a list of 'fields' rather than 'teasers'.

On the next page, in order to limit to upcoming events, make sure you create a new filter on your view based on the event's date. To limit it to current and future events, you should enter a **relative**, as opposed to, a hard-coded date. Here's how I would set up that filter:

That should be it. Add whichever fields you want and limit to as many listings as you want!

Let us know if this works!

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


# Question
Title: D7 in sub directory - Not able to log in
I have a Drupal site I need to show for portfolio reasons so I have installed it in a sub directory.

* I have changed the rewritebase to /subdir

Initially without that change I was served the homepage just fine but no interior pages. With that change I was able to get deeper into this site but when I went to login the backend it loaded forever and spit out this error:

> Additional uncaught exception thrown while handling exception.
>
> ### Original
>
> PDOException: SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away: SELECT source FROM {url\_alias} WHERE alias = :alias AND language IN (:language, :language\_none) ORDER BY language ASC, pid DESC; Array ( \[:alias\] =\> user \[:language\] =\> en \[:language\_none\] =\> und ) in drupal\_lookup\_path() (line 176 of /home/content/k/c/l/name/html/fsubdir/includes/path.inc).
>
> ### Additional
>
> PDOException: SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8, :db\_insert\_placeholder\_9); Array ( \[:db\_insert\_placeholder\_0\] =\> 0 \[:db\_insert\_placeholder\_1\] =\> php \[:db\_insert\_placeholder\_2\] =\> %type: !message in %function (line %line of %file). \[:db\_insert\_placeholder\_3\] =\> a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:284:"SQLSTATE\[HY000\]: General error: 2006 MySQL server has gone away: SELECT source FROM {url\_alias} WHERE alias = :alias AND language IN (:language, :language\_none) ORDER BY language ASC, pid DESC; Array ( \[:alias\] => user \[:language\] => en \[:language\_none\] => und ) ";s:9:"%function";s:20:"drupal\_lookup\_path()";s:5:"%file";s:61:"/home/content/k/c/l/name/html/subdir/includes/path.inc";s:5:"%line";i:176;s:14:"severity\_level";i:3;} \[:db\_insert\_placeholder\_4\] =\> 3 \[:db\_insert\_placeholder\_5\] =\> \[:db\_insert\_placeholder\_6\] =\> http://mydomain.com/subdir/?q=user \[:db\_insert\_placeholder\_7\] =\> \[:db\_insert\_placeholder\_8\] =\> 173.10.171.18 \[:db\_insert\_placeholder\_9\] =\> 1354293470 ) in dblog\_watchdog() (line 157 of /home/content/k/c/l/name/html/subdir/modules/dblog/dblog.module).

Can anyone point me in the right direction to get this resolved?

# Answer
> 0 votes
The server gone away error is an error that happens when the client cannot connect to the database server, and it can happen because:

* The client doesn't have the necessary privileges to access the database
* There has been a timeout on the TCP/IP connection
* The client is running on Windows, and the server dropped the connection, probably because a timeout

When I got that error on my sites was always because the credentials I used in the settings.php file were wrong.
The other reason to get that error is that the value of max\_allowed\_packet is too small.

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


# Question
Title: Email notifcations based on specific dates i.e. employee anniversarries
We are utilizing Drupal 7 as an intranet application for our company. One of the content types of the app is a Views-based Employee Directory. Within this directory is a field detailing the employee's start of employment date.

My boss requests a feature implemented where we will receive notifications via e-mail in regards to upcoming anniversaries of employee start date, i.e. 1 year, 5 years, 10 years, etc.

Is this something I can create using Rules+Views? Thank you

# Answer
You should be able to configure a rule that will run with cron. Then it will check the employee start date field as the condition and send an email as the action.
> 0 votes

---
Tags: views, 7, rules
---


# Question
Title: How to assign drupal webform to drupal node/block?
i am using drupal 6.0 and webform modules to create webforms but i have no idea about asigning webforms to drupal node/block. so please help me and give some ideas and suggestion about this.

# Answer
I suggest using the Webform Block module. It is stable and compatible with Drupal 6.

> Allows embedding a webform node into a block which can be positioned in any block region (theme space permitting).
>
> Handles redirecting back to the current page on validation errors.
>
> A good use for this is to add a site wide contact form inline on your pages, such as in the footer or sidebar.
> 3 votes

# Answer
You *should not* use Webform Block if you are using a recent version of Webform: "The functionality of this module is now included in Webform 3.3. Do not install this module at the same time as Webform 3.x." (see http://drupal.org/project/webformblock)

Just use Webform module.
> 2 votes

# Answer
You can add the following code in node or block

```
$submission = array();
  $enabled = TRUE;
  $preview = FALSE;
  print drupal_get_form('webform_client_form_XXX', $node, $submission, $enabled, $preview);

```
> 0 votes

---
Tags: 6
---


title: Can two drupal distributions co exist?

text:
# Question
Title: Can two drupal distributions co exist?
I am working on a drupal site and One of the functionality of my site is to have an ideation platform. Can I make a distribution work seamlessly within my drupal instance ?

# Answer
*Seamlessly*, probably not. However, what may work is to merge your own Drupal site's install profile with the code found in `idea.install`. Additionally, you'll want to enable all of the modules found here.
> 3 votes

---
Tags: 7, distributions
---


# Question
Title: Moving Drupal database from MySQL to Oracle
I've developed a website with Drupal 7 running on standard PHP/MySQL server. Now there's a need to move it to server with Oracle database. While I managed to set up testing environment with a fresh Drupal 7 install and all my modules, to check if they are working with Oracle DB, now all data from original development version needs to be moved to new server. First option was to use Oracle SQL Developer "Migrate" function, but I ended up manually copying tables from repository to Oracle DB and in the end it failed to function. Next thing I tried some migration tools. DBTNG migrator failed, because production server has no MySQL or SQLite extensions, so it was impossible to import anything from original database. Backup and Migrate module works only with MySQL. Other modules were migrating limited number of data types or didn't support i18n. There's a third option of manually recreating all content types, menus, taxonomy, views and other elements, but in the end it would be very convenient to have a system for migration from MySQL to Oracle database. What needs to be migrated: custom content, fields, blocks, menus, taxonomy, views and all translations. Does anyone have any ideas how to achieve this task? Preferably using open and free software, but commercial products are an alternative, if they work fast and efficiently.

# Answer
> 1 votes
This may be another long shot and I certainly haven't tried it myself, but assuming that the Features module works on a fresh install on top of Oracle, you may be able use it to export your content types, menus, and views from the MySQL-based site. The Features extra module might allow you to export the taxonomy too.

You could then add the Services module on the MySQL site to serve up content to either the Feeds module or maybe the Web service client module on the Oracle-based site.

Another caveat is that I don't know how well either of these steps would handle the i18n.

Good luck!

---
Tags: 7, migrations, database
---


# Question
Title: Solr Indexing Error showing "EntityMalformedException: Missing bundle property on entity of type taxonomy_term"
In Drupal 7.14, when i Index my Whole Site, Solr is showing following error:

```
AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows.
Path: /batch?id=1938&op=do StatusText: Service unavailable (with message)
ResponseText: EntityMalformedException: Missing bundle property on entity of type taxonomy_term. in entity_extract_ids() (line 7539 of /project/path/includes/common.inc).

```

So when i look into the lines in `/includes/common.inc` (around lines: 7537):

```
// Explicitly fail for malformed entities missing the bundle property.
if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
  throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
}

```
* What is that chunk of code (in `common.inc`) is doing actually please?
* How can i overcome that error?

# Answer
> 1 votes
Drupal tries to index an invalid item and throws this error. To find out what document is causing the error, you can implement the hook\_apachesolr\_index\_document\_build hook with a watchdog statement inside.

This is from apachesolr.api.php

```
/**
 * Build the documents before sending them to Solr.
 * The function is the follow-up for apachesolr_update_index
 *
 * @param integer $document_id
 * @param array $entity
 * @param string $entity_type
 */
function hook_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {

}

```

My guess is that the last item in your dblog will be the offending item.

# Answer
> 0 votes
> What is that chunk of code (in common.inc) is doing actually please?

* Every entity should have an bundle, Say node is an entity and article is a bundle.Like wise taxonomy\_term is an entity and vocabularies are bundle.
* The above error says that you are trying to save or process a taxonomy term without its vocabulary id or name.

> How can i overcome that error?

* To debug you can use debug back-trace or with a patch from here just for testing.
* Check whether the term is saved or processed without its vocabulary.

---
Tags: search
---


title: How do I rename uploaded files?

text:
# Question
Title: How do I rename uploaded files?
How do I rename the uploaded files for my module?

# Answer
> 4 votes
You might find some information about how to code changing file names in the File (Field) Paths module.

# Answer
> 2 votes
```
$file = file_save_upload('file' , array(
  'file_validate_is_image' => array(),
  'file_validate_extensions' => array('png gif jpg jpeg docx')
),'',FILE_EXISTS_RENAME);

$file->filename = basename($file->uri);
if ($file) {
  if ($file = file_move($file, 'public://rohit')) {
    $form_state['storage']['file'] = $file;
  }
}

```

---
Tags: 7, files
---


# Question
Title: List items of a certain content type in another content type
For college we have to create a website with drupal. This website has to be for a travel agency that does surf vacations. We already have the basic website up and running but are kinda stuck with the destinations.

I will quickly explain how the website should be set up and our problem.

So bassicly a customer should be able to go to the page called "Destinations" and have a list of the 4 available countries where they could book a vacation. Like for example you have Australia and Costa Rica. However when a user clicks on for example Australia he should get a new list of possible locations within this country where he wants to go surf.

We have tried with many different ways to get this to work the problem however is that both the countries and local destinations should have a picture and a short description. Also the user should be able to select their "level" on the specific location.

---

What we have tried:

Taxonomy: We have tried using taxonomy but it doesn't allow us to give the right design to the website. It will list the countries but without any description or picture.

Ubercart: I wish this would have worked but somehow you can't create subclasses in ubercart or just only show a list of classes with views.

---

Thank you for taking your time and we hope to find a solution soon.

Kind regards.

# Answer
A general out line is given below,

* Create a content type for country, add your available countries with images and description
* Create a destination content type, with necessary fields like
image,description etc: (If you want process booking with payment, use Ubercart and create a product class Destination, modify the required fields)
* Add a country field to destination contenttype of 'fieldtype' - **Node Reference**, choose widget as select list. This allows choose country on creation of a new destination
* Use Views to list the destinations page, by selecting necessary fields,
* Use views to create the list of related destinations based on the
country name and save it as a block. So based on the country
selection the destinations can be list in this block
* If you are using online payment for booking use ubercart, otherwise
on booking you can send an enquiry to admin.

Hope you got an idea on how to proceed.

**UPDATE** To get list of the destinations on clicking the country do the following

* In your destination listing view, Add a 'Contextual filters'( Arguments in D6) and choose the 'country nodereference field'.
* In your four country listing view, in fields choose Nid (Nid) also and choose 'Exclude from display ' option for that field.
* Then in the 'Country name field' - click 'Rewrite results' and choose 'Output this field as a link' checkbox. In link path give path like below
* eg: destinations/\[nid\] ie: where destinations is the path of the your destination page and \[nid\] is the token for the node id. Probably you have to just change 'destinations' only with your path.

Thats it, now on clicking the country it will goto destinations page which shows all destinations belongs to the particular country
> 0 votes

# Answer
If you want a ajax work it should be done by your own code.

If you don't care about load new pages then you can try with views.

Is this a drupal 6 project?

Oscar?
> -2 votes

---
Tags: taxonomy-terms, nodes, ubercart
---


title: Drupal cannot find user login page

text:
# Question
Title: Drupal cannot find user login page
i was having some problems with my settings.php file. I fixed this but now my user page isn't found and I cannot login. Anyone know how to fix this? Thanks!

Authorize.php loads but obviously i cannot get in

nevermind i think it's an issue with hostgator

# Answer
> 3 votes
Maybe this help others. If you are using drupal with a temporary URL on a hostgator server, follow this link http://support.hostgator.com/articles/specialized-help/technical/drupal/using-drupal-with-a-temporary-url

# Answer
> 2 votes
What kind of problems exactly?

If you changed something in settings.php:

* make a backup of settings.php
* put back a default one with your DB details
* try to login again

If you can't, post here the errors you are getting.

---
Tags: users
---


title: Create a Taxonomy Archive Block

text:
# Question
Title: Create a Taxonomy Archive Block
Hello i was hoping to create a block to attach to the taxonomy/term/\* page but i am running into problems with the date arguement working with the term argument. I have just cloned the archive view and disabled the taxonomy view, added the arguments but to no avail.

Has anyone ever achieved this before with D^ and Views 3?

thanks

# Answer
http://www.webbykat.com/2012/02/creating-monthly-archive-block-drupal-7-views While not taxonomy should work. Change the content type from node to taxonomy and as you create it it will be archived. You may need to ad a date entity to the taxonomy and have rules or trigger put in a creation date since I don't believe they are creation date stamped.
> 2 votes

---
Tags: views, 6
---


title: Move Menu minipanels DOM location

text:
# Question
Title: Move Menu minipanels DOM location
I am trying to create a Menu-minipanel which will appear directly below the horizontal header menu, and push the content below down.

I have set the menu positioning to static so that it sits within the page structure, but that renders it at the bottom of the page when triggered (which is where it is put by default, and usually repositioned from there outside of the page structure).

Among the Menu mini-panels options there is a field labelled:

> "Allows control over where within the page's DOM structure the minipanel will be inserted. This defaults to $(document.body), i.e. at the end of the page's content."

but I have absolutely no idea how to manipulate this, and cannot find any documentation which makes this clear.

DOM is something I simply don't have a clue about, and I feel like I am so close to the answer, but my own knowledge seems to have run out!

Any guidance would be so appreciated!

# Answer
So, though a bit of experimentation I found that the language

> "Allows control over where within the page's DOM structure the minipanel will be inserted. This defaults to $(document.body), i.e. at the end of the page's content."

Was what confused me - it turns out that just by adding a standard css selector to that field moved the menu.
> 1 votes

---
Tags: routes, panels, theming
---


title: extra fields in views module

text:
# Question
Title: extra fields in views module
I am using hook\_form\_alter to add few extra fields in a node. I have also managed to expose those fields in user interface using hook\_field\_extra\_fields. All good until now but I can not see those exposed fields in views module? any suggestions?

# Answer
> -1 votes
In order to expose your field to Views, you need to implement Views API:

http://views-help.doc.logrus.com/help/views/api

This can be made much easier if you implement your field as a proper field, rather than a form alter. The Examples project has some examples, notably Field Permission Example.

---
Tags: 7, views
---


title: Create a new entity and set field value

text:
# Question
Title: Create a new entity and set field value
With the Rules module, I collect a list of row (text value) from a view, then iterate the list (variable `list_item`) and add this action:

* Create new entity of type xxxx, (variable `entity_created`);

I add a PHP action that extracts a substring from `list_item`, convert the substring in a Unix timestamp, and set a field "date" of `entity_created`.

The rule create only one entity, and not one entity for each item in `list_item`.

Does anybody know how to create one entity for each item in `list_item`?

# Answer
> 1 votes
The answer is the one suggested in Creating Entities in a Rules loop creates one first entity only.

After an actions of entity create, or data set, add the "Save entity" Action, and click on the "Force saving immediately" checkbox below on the form. Without selecting the checkbox, the Rules module creates only the first entity.

---
Tags: rules
---


# Question
Title: Node Hierarchy: Display Children of top most parent in views
Node Hierarchy lets you assign parent/child relationships to nodes, which can be displayed in Views.

In Views, you can display the parent of a node, the ancestor of a node and the child of a node. (Instructions below\*).

Is there are any way to combine this to display the immediate children of the top level parent node?

If not, are there any other modules that would allow this. (I have tried both relationship and entity references, but they don't seem capable).

---

---

\*Instructions on how to display Node Hierarchy relationships in Views.

**How to display Parent Node:** In Views, Go to relationships and enable the Node Hierarchy Parent relationship. Then go to contextual filters, and selected Node ID as a filter. Under "When the filter value is available" set the Validator to content.
Create a block display and place it on your node.

**How to display Ancestor Nodes:** Exactly the same as Parent Node, but the Node Hierarchy Ancestor Relationship is used.

**How to display Child Nodes:** This requires a different approach from the above two, as a relationship is not used. The "Node Hierarchy: Parent Node ID" is used as a contextual filter in place of Node ID, however, the settings are the same.

# Answer
> 2 votes
You could try adding parent node as a relationship in views, then add a filter and set it to "is empty (NULL)" as a requirement of the field with relationship parent. This will only display nodes that have no parent node set.

If you want to show only nodes whose parents have no parent, you'd add a second relationship (called something like "grandparent") and then set your filter to require the grandparent, rather than the parent, to be empty.

# Answer
> 0 votes
This code, if put in the template file for a view that is set to display at url `http://yoursite.com/[some word]/[taxonomy term]`. It takes \[taxonomy term\], finds the TID from the name (so if you have TID in the URL you can skip that part), and creates an array of ancestors called `$ancestors_list` (in mine they happen to link to a view at `http://yoursite.com/[some word]/[new taxonomy term]` that takes taxonomy terms as a contextual filter).

```
        if (!empty($args[1])){
            $term_name = $args[1];
            $terms = taxonomy_get_term_by_name($term_name);
            foreach($terms as $term){
                $tid = $term->tid;   //find the TID for the term name
            }
            $pedigree = taxonomy_get_parents_all($tid);         //get the tree for the term and create an array of parent terms
            $ancestors_list = array();
        foreach($pedigree as $ancestor){
            $ancestor_name = $ancestor->name;
            if ((isset($term_name) && ($ancestor_name !== $term_name)) || ($args[0]=='node')){
                $ancestors_list[] = l($ancestor_name, '[some word]/'.$ancestor_name);
            }
        }

```

I believe this list is created in order from child -\> parent -\> grandparent, so the top-level term would be the last in the array and the immediate child of the term would be the second to last.

---
Tags: views, nodes
---


# Question
Title: Do Entity Field Queries respect grants and/or node access?
"How to use Entity Field Queries" contatins the cryptic piece of information,

> `->addMetaData($key, $object)`
>
> Adds additional metadata to the query. One important usage of this method is to run the query as another user, since **EntityFieldQuery's fieldCondition will take current user's permission into account**\[...\]

and there is a DANGEROUS\_ACCESS\_CHECK\_OPT\_OUT query tag that bypasses access checks, implying that access checks are run by default when EFQs are run. But this issue suggests that access checks are NOT run, UNLESS one is using fields in EFQ, in which case the "`field_sql_storage_field_storage_query()` function will always add `'entity_field_access'`".

So... what? Do EFQs respect node\_access by default, or do you have to do something to invoke node\_access?

# Answer
`EntityFieldQuery` will always check the user has the permission to access the field, if "DANGEROUS\_ACCESS\_CHECK\_OPT\_OUT" is not between the tags added to the query, but that is not done directly. It is done by adding a tag to the query, as field\_sql\_storage\_field\_storage\_query() does.

```
if (!isset($query->tags['DANGEROUS_ACCESS_CHECK_OPT_OUT'])) {
  $select_query->addTag('entity_field_access');
}

```

It is then an implementation of hook\_query\_TAG\_alter() that alters the query to check the permission. The Node module implement that hook with node\_query\_entity\_field\_access\_alter().

```
function node_query_entity_field_access_alter(QueryAlterableInterface $query) {
  _node_query_node_access_alter($query, 'entity');
}

```

That is the reason why, before Drupal 7.15 (which introduced the "DANGEROUS\_ACCESS\_CHECK\_OPT\_OUT" tag), it was suggested to use `$query->addMetaData('account', user_load(1))`. The user #1 always have any permission, and checking the permission to access a field would be always positive.

\_node\_query\_node\_access\_alter() contains the following code.

```
  // If $account can bypass node access, or there are no node access modules,
  // or the operation is 'view' and the $acount has a global view grant (i.e.,
  // a view grant for node ID 0), we don't need to alter the query.
  if (user_access('bypass node access', $account)) {
    return;
  }
  if (!count(module_implements('node_grants'))) {
    return;
  }
  if ($op == 'view' && node_access_view_all_nodes($account)) {
    return;
  }

  // Omissis

  // Find all instances of the base table being joined -- could appear
  // more than once in the query, and could be aliased. Join each one to
  // the node_access table.

  $grants = node_access_grants($op, $account);
  if ($type == 'entity') {
    // The original query looked something like:
    // @code
    //  SELECT nid FROM sometable s
    //  INNER JOIN node_access na ON na.nid = s.nid
    //  WHERE ($node_access_conditions)
    // @endcode
    //
    // Our query will look like:
    // @code
    //  SELECT entity_type, entity_id
    //  FROM field_data_something s
    //  LEFT JOIN node_access na ON s.entity_id = na.nid
    //  WHERE (entity_type = 'node' AND $node_access_conditions) OR (entity_type <> 'node')
    // @endcode
    //
    // So instead of directly adding to the query object, we need to collect
    // all of the node access conditions in a separate db_and() object and
    // then add it to the query at the end.
    $node_conditions = db_and();
  }
  foreach ($tables as $nalias => $tableinfo) {
    $table = $tableinfo['table'];
    if (!($table instanceof SelectQueryInterface) && $table == $base_table) {
      // Set the subquery.
      $subquery = db_select('node_access', 'na')
       ->fields('na', array('nid'));

      $grant_conditions = db_or();
      // If any grant exists for the specified user, then user has access
      // to the node for the specified operation.
      foreach ($grants as $realm => $gids) {
        foreach ($gids as $gid) {
          $grant_conditions->condition(db_and()
            ->condition('na.gid', $gid)
            ->condition('na.realm', $realm)
          );
        }
      }

```

Definitively, the code checks the user has access to the node.
> 6 votes

---
Tags: 7, entities
---


# Question
Title: Unsure how to define an entity type using Entity API
I'm here because of this:

> EntityMalformedException: Missing bundle property on entity of type contacts. in `entity_extract_ids()`

I'm trying to create my own entity. Can you identify what is incorrect or missing about my entity configuration?

I am using the Creating your own entities with Entity API guide for setting up a new module using entities.

For my needs, I only need one entity type. The example creates two entity types, one called "task", and another called "task\_type". So I did my best to eliminate the "task\_type" sections, but I'm getting the above error and am not understanding what to do about the bundle type.

This is my `hook_entity_info()`.

```
/**
 * Implements hook_entity_info().
 */
function contacts_entity_info() {
  $return = array(
    'contacts' => array(
      'label' => t('Contact'),
      'entity class' => 'Contacts',
      'controller class' => 'ContactsController',
      'base table' => 'contacts',
      'fieldable' => TRUE,
      'entity keys' => array(
        'id' => 'ckid',
      ),
      'bundle keys' => array(),
      'bundles' => array(),
      'load hook' => 'contacts_load',
      'view modes' => array(
        'full' => array(
          'label' => t('Default'),
          'custom settings' => FALSE,
        ),
      ),
      'label callback' => 'entity_class_label',
      'uri callback' => 'entity_class_uri',
      'module' => 'contacts',
      'access callback' => 'contacts_access',
    ),
  );

  return $return;
}

```

This is my custom controller. (Do I even need this?)

```
class ContactsController extends EntityAPIController {
  public function create(array $values = array()) {
    global $user;
    $values += array(
      'mail' => '',
      'notes' => '',
      'created' => REQUEST_TIME,
      'changed' => REQUEST_TIME,
      'uid' => $user->uid,
    );
    return parent::create($values);
  }

  public function buildContent($entity, $view_mode = 'full', $langcode = NULL, $content = array()) {
    $wrapper = entity_metadata_wrapper('contacts', $entity);
    $content['author'] = array('#markup' => t('Created by: !author', array('!author' => $wrapper->uid->name->value(array('sanitize' => TRUE)))));

    // Make Description and Status themed like default fields.
    $content['notes'] = array(
      '#theme' => 'field',
      '#weight' => 0,
      '#title' =>t('Notes'),
      '#access' => TRUE,
      '#label_display' => 'above',
      '#view_mode' => 'full',
      '#language' => LANGUAGE_NONE,
      '#field_name' => 'field_contact_notes',
      '#field_type' => 'text',
      '#entity_type' => 'contacts',
      '#items' => array(array('value' => $entity->notes)),
      '#formatter' => 'text_default',
      0 => array('#markup' => check_plain($entity->notes))
    );

    return parent::buildContent($entity, $view_mode, $langcode, $content);
  }
}

```

# Answer
> 1 votes
`entity_extract_ids()` raises an exception when `$info['entity keys']['bundle']` is not defined, or is an empty string. If you don't want to explicitly set the bundle property, you need to set it to value that is considered empty from PHP, but it is not an empty string, such as an empty array, or `FALSE`. In such cases, the bundle property is set to the entity type name.

The following is the code contained in entity\_extract\_ids(), and which raises the exception you are seeing.

```
if (!empty($info['entity keys']['bundle'])) {
  // Explicitly fail for malformed entities missing the bundle property.
  if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys'] ['bundle']} === '') {
    throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
  }
  $bundle = $entity->{$info['entity keys']['bundle']};
}
else {
  // The entity type provides no bundle key: assume  single bundle, named
  // after the entity type.
  $bundle = $entity_type;
}

```

Keep in mind that entity\_get\_info() caches the entity information it gets. If you edit an enabled module, you need to disable it, and re-enable it. This forces Drupal to clean the cache it uses, and call the implementations of `hook_entity_info()` to get a fresh definition of the entity.

```
  // Use the advanced drupal_static() pattern, since this is called very often.
  static $drupal_static_fast;
  if (!isset($drupal_static_fast)) {
    $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
  }
  $entity_info = &$drupal_static_fast['entity_info'];

  // hook_entity_info() includes translated strings, so each language is cached
  // separately.
  $langcode = $language->language;

  if (empty($entity_info)) {
    if ($cache = cache_get("entity_info:$langcode")) {
      $entity_info = $cache->data;
    }
    else {
      $entity_info = module_invoke_all('entity_info');
      // Merge in default values.
      foreach ($entity_info as $name => $data) {
      // …
    }
    // …
  }

```

Installing a new module has the same effect, as Drupal should clear its cache in that case too. If it doesn't happen, you can always force Drupal to clear its cache with `cache_clear_all('entity_info', 'cache', TRUE)`.

---
Tags: 7, entities
---


title: Use Media Youtube with File Field Type

text:
# Question
Title: Use Media Youtube with File Field Type
I have set up a Feed Importer than gets a YouTube Atom Feed and processes it into "YouTube Video" content type. This is working great so far but what I want to do now is have the actual YouTube video embedded in my website rather that linking to the youtube website.

I downloaded and installed the Media YouTube module and went to set up a field in the YouTube Video content type to hold the video url. The Multimedia Asset field type is deprecated and I found somewhere that said to use the File field type. So I created the "Video" field as a File field with the Media File Selector widget. Then I set up the mapping in the feed importer. I am using the Feeds: YouTube Parser module to parse the Atom Feed. I set the Source to Video URL and the Target to my new Video field.

When I went to import the feed I got a bunch of errors that look like this

Download of http://www.youtube.com/watch?v=tag:youtube.com,2008:video:xm6Jv3BhdS4 failed with code 404.

I'm not sure where the "tag:youtube.com,2008:video:" part is coming from otherwise the url is correct. Anyone know what my problem is? Is it the way the YouTube Parser is getting the url or something else?

Thanks a lot!

# Answer
In your feed importer mapping, change the Source to `Watch page`. It seems `Video URL` is broken.

I have it working right now with the following modules:

* Feeds (feeds) 7.x-2.0-alpha7
* Feeds: YouTube (feeds\_youtube) 7.x-2.0-beta1+7-dev
* Media Feeds (media\_feeds) 7.x-2.0-alpha1+9-dev
* Media (media) 7.x-1.2
* Media Internet Sources (media\_internet) 7.x-1.2
* Media: YouTube (media\_youtube) 7.x-2.0-rc1

All dev versions were as of today (Dec. 1, 2012). And for anyone that's trying, I found Embedded Media Field (emfield) to not work with Feeds at all.

Using the File field type (the widget type doesn't matter for feeds imports), set the display to Rendered file.
> 2 votes

---
Tags: feeds, media, files
---


# Question
Title: Restrict user access to several actions in function
I have a function, that returns statistics for the user:

```
function module_menu() {
  $items = array();
  $items["statistics"] = array(
    'page callback' => 'module_statistics',
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function module_statistics($group_id, $user_id = NULL) {
  global $user;
  if ($user_id == NULL) {
    $user_id = $user->uid;
  }
  $result = module_statistics_table($group_id, $user_id);
  print $result;
}

```

I want only the administrator to have access to this function with $user\_id != NULL. So the user will be unable to watch someone elses statistics. I have an access argument 'admin tasks' for the admin. How to do the else statement:

```
if ($user_id == NULL) {
  $user_id = $user->uid;
}
else {
  if($user has no access to 'admin tasks') {
    return HTTP 403 Forbidden status code;
    exit from function;
  }
}

```

# Answer
If I assume correctly that this is going to called/accessed like this...

```
www.yourhost.com/statistics/group_id[/user_id]

```

eg

```
www.yourhost.com/statistics/19/64

```

or

```
www.yourhost.com/statistics/19

```

...then you could do something along the lines of...

```
function module_statistics($group_id, $user_id = NULL) {
  global $user;

  if ($user_id == NULL) {
    $user_id=$user->uid;
  }

  if ($user_id==$user->uid || user_access('admin tasks')) {
    return module_statistics_table($group_id, $user_id);
  } else {
    return MENU_ACCESS_DENIED;
  }
}

```

which if my pre-espresso logic is working will call your function if the user's uid matches what s/he is asking for OR they are they admin. If not, return an access denied message.
> 2 votes

# Answer
In your `hook_menu` call you can use different *access arguments*, to make sure only administrators access the callback function. For example,

```
'access arguments' => array('administer users'), // usually Administrators have this permissions

```

If users with some other roles try to access the menu, they'll get the **Access Denied** message by default.

If you want your users to access the function and restrict only certain part, you can check the user role in that case:

```
if ($user_id == NULL) {
  $user_id = $user->uid;
}
else {
  if(in_array('administrator', array_values($user->roles))) {
    //apply your exit function logic here
  }
}

```
> 2 votes

# Answer
From your code, I take you are always expecting the group ID is passed, as your page callback doesn't assign a default value to `$group_id`. If this is the case, I would rather suggest the following code.

```
function module_menu() {
  $items['statistics/%/%user_uid_optional_load'] = array(
    'page callback' => 'module_statistics',
    'access callback' => 'module_statistics_access',
    'access arguments' => array(2),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function module_statistics_access($account) {
  return ($GLOBALS['user']->uid == $account->uid || user_access('admin tasks'));
}

function module_statistics($group_id, $account) {
  print module_statistics_table($group_id, $account);
}

```

Notice that:

* It should be only the access callback that decides if the user has access to a page.
* With the code I wrote, `$account` is the user object for the currently logged-in user, when the user ID is not passed as argument, or the user object for the passed user ID when the user ID is passed in the URL.
> 2 votes

---
Tags: users
---


# Question
Title: How can I create a simple non-CRUD resource action with Drupal 7 / Services 3?
The resource "username" appears but my action does not appear in the list in services admin. Response to a POST is HTTP/1.1 404 Not found: Could not find resource username.

I replaced my module name with "module" here:

```
function module_services_resources() {
  return array(
    'username' => array(
      'check' => array(
        'help' => 'Checks username for uniqueness',
//       'file' => array('file' => 'inc', 'module' => 'noteresource'),
       'callback' => '_module_username_check',
       'access callback' => '_module_resource_access',
        'access arguments' => array('view'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'username',
            'type' => 'string',
            'description' => 'The username to check',
            'source' => 'data',
            'optional' => FALSE,
          ),
        ),
      )
    )
  );
}

function _module_resource_access($op, $args) {
  return TRUE;
}

function _module_username_check($data) {

  $username = $data->username;

  $user = db_fetch_object(db_query("SELECT uid FROM users WHERE name=':username'", array(":username" => $username)));

  return $user;
}

```

# Answer
Actions outside the normal CRUD roster must be wrapped in an array under the key 'actions'

```
function module_services_resources() {
  return array(
    'actions' => array(
      'username' => array(
...

```
> 5 votes

---
Tags: services
---


# Question
Title: How do I create a administration page (with overlay) through the UI
I would like to add an administration page (with overlay) to my site (not programatically). I assume the basic process is:

1. Create a 'basic page'
2. Set the path to /admin
3. Set permissions \<-- How do I do this??? I can't see how do I restrict the page??
4. Configure overlay - Is it automatic?
5. Add page to admin menu.

I'm stuck on 3, but I could probably use help on 4 and 5.

Thanks!

# Answer
> 1 votes
You're probably looking for the Overlay Paths module:

> This is a simple module that enables site builders to use the built-in Overlay for non-admin pages.

However, if the path you've got for the node is under /admin I'm pretty sure that if you configure permissions properly you won't need that module; the overlay should pop up automatically. You'll need to give your users the "Use the administration pages and help" permission, as well as the one to actually use the overlay.

As it's a node, whatever node access solution you have in place will determine the access beyond those two permissions.

---
Tags: modal-dialogs
---


# Question
Title: how to edit number of characters to be shown in "readmorecontrol" module?
Any idea on how to edit the number of characters to be shown before the "Read More" link is displayed?

I remember this to be an editable field but not able to locate anymore how to do so.

Link to module: http://drupal.org/project/readmorecontrol

Thanks!

# Answer
This setting is unique for ech content type

* Select "Structure" - "Content types"
* Select "Manage display" for desired content type
* In secondary tabs select "Teaser" link
* For Content field you will something like this "Trim length: 600" - click on gear icon and change it
> 1 votes

---
Tags: 6
---


# Question
Title: What's the difference between using Drupal's jQuery library and adding it in html.tpl.php?
I'm recoding one site (D7) where I stumbled upon statically added jquery (using a script tag inside html.tpl.php that pulls jquery library from google CDN). I installed "jQuery CDN" module that does the same and expected that when I loose statically added script tag everything would stay the same, but the menu and slider don't work (menu is implemented using some internal jsddmenu.js file, also slider using slides.jquery.js). What's the difference between those two implementations, when both of them add:

```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>

```

to the html code?

# Answer
> 1 votes
Its better to add javascript using your: a) theme's .info file using scripts\[\] = "some/filename.js" b) in the theme dynamically ... such as mytheme\_node\_view() { drupal\_add\_js('file', 'some/filename.js'); } c) or in a custom module ... (similar to above)

depending entirely on your site's needs.

the reason its better to approach this this way is: 1) the theme's scripts\[\] array is cacheable and will attach the javascript to every page. 2) dynamically attaching it allows the script to be used only when needed. 3) you don't force the client to load anything they don't need. 4) if its attached in one of the above ways, it can be minified if needed --- allowing the client to download one big javascript file instead of a dozen separate ones.

# Answer
> 0 votes
Why you should not add script in your tpl because Drupal has theme layer access and module layer access. It's for Drupal caching performance reason.

Have you read about how to work with Javascript & jQuery ?

http://drupal.org/node/171213

You can check this option to use Google CDN http://yourdrupal.site/admin/config/development/performance

If you need uptodate version you can install http://drupal.org/project/jquery\_update

# Answer
> 0 votes
Its may related to lead and Lag of files, when you add script in `tpl` it will load after all scripts specified in head. jQuery in dependency for slider ...

---
Tags: 7, javascript
---


# Question
Title: How to add contextual links to the main content block?
The main content block has no contextual links. I believe this is related to \_block\_get\_renderable\_array but I'm not really sure. I'm using Custom Contextual Links module to add contextual links to blocks, but of course it doesn't work with system-main (the main content block).

# Answer
Contextual module (core) will preprocess the block renderable array and turn `$block->content['#contextual_links']` into the block template `$title_suffix` using the contextual\_links element type (see contextual\_element\_info). See contextual\_preprocess for the implementation of this behavior.

While block module relies on \_block\_get\_renderable\_array for performance reasons, contextual links example module (from the examples package) shows an example of setting `#contextual_links` on `hook_block_view`.

As for CCL, it relies on hook\_contextual\_links\_view\_alter which will only alter or add links if there is already a `#contextual_links` element in the renderable array. The main content block doesn't get the default 'Configure block' contextual link (see `_block_get_renderable_array`), and therefore CCL doesn't affect it by default. Let's just add the default contextual link:

```
/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function MYMODULE_block_view_system_main_alter(&$data, $block) {
  if (user_access('access contextual links')) {
    $data['content']['#contextual_links']['block'] = array(
      'admin/structure/block/manage',
      array('system', 'main'),
    );
  }
}

```
> 5 votes

# Answer
This answer is not related to user's question. I wrote this in case others similar like me is looking for adding contextual link in hook\_block\_view.

Here is the contextual link example module mentioned by Barraponto regarding setting #contextual\_links on hook\_block\_view.

http://api.drupalize.me/api/drupal/function/contextual\_links\_example\_block\_view/7 http://api.drupalize.me/api/drupal/function/contextual\_links\_example\_menu/7

Another example will be the original drupal menu module.

```
// http://api.drupal.org/api/drupal/modules!menu!menu.module/function/menu_block_view/7
function menu_block_view($delta = '') {
  $menus = menu_get_menus(FALSE);
  $data['subject'] = check_plain($menus[$delta]);
  $data['content'] = menu_tree($delta);

  // Add contextual links for this block.
  if (!empty($data['content'])) {
    $data['content']['#contextual_links']['menu'] = array('admin/structure/menu/manage', array($delta));
  }
  return $data;
}

// The contextual link above needs to work out with hook_menu as example show below.
// http://api.drupal.org/api/drupal/modules!menu!menu.module/function/menu_menu/7
function menu_menu() {
  ...

  $items['admin/structure/menu/manage/%menu'] = array(
    'title' => 'Customize menu',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('menu_overview_form', 4),
    'title callback' => 'menu_overview_title',
    'title arguments' => array(4),
    'access arguments' => array('administer menu'),
    'file' => 'menu.admin.inc',
  );
  $items['admin/structure/menu/manage/%menu/list'] = array(
    'title' => 'List links',
    'weight' => -10,
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  );

  ...
}

```

Hope it helps other who facing similar problem like me.
> 2 votes

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


# Question
Title: How can I authenticate against a non-drupal database?
We have a non-Drupal intranet system built on php/mySQL. We're adding a Drupal install to handle some social functions, and would like (if possible) to not duplicate all of our login information. Is there a module (or technique) that would let us authenticate against our existing users table, rather than needing to create separate user records in the new Drupal install?

I did find this, but it's been abandoned for 6 years, so I don't know how relevant it is anymore.

We have not started the new install yet, so either 6 or 7 is possible - if there's a module that would work for only 6, we're perfectly willing to do that.

# Answer
My suggestion would be to take a look at LDAP integration or Lightweight Directory Access Protocol modules to see how they handle authentication.

My recollection is that they `hook_form_alter` the `user_login` form to add a new validation function that calls out to the LDAP server if Drupal authentication fails. You should be able to do this for your own authentication. We modeled a custom authentication on this method, but I don't recall all of the details.

Just remember that you want to use the external authentication *in addition to* and not *instead of* Drupal authenticaion so you don't lock out any admins if/when your other site is down.
> 2 votes

# Answer
Read this link on how to connect to multiple dB's with Drupal: http://drupal.org/node/18429

Then... You need first to add another database connection in sites/default/setting.php You will find your primary connection, and add another as stated in config file:

* Database configuration format:
    + @code
    + $databases\['default'\]\['default'\] = array(
    + 'driver' =\> 'mysql',
    + 'database' =\> 'databasename',
    + 'username' =\> 'username',
    + 'password' =\> 'password',
    + 'host' =\> 'localhost',
    + 'prefix' =\> '',
    + );
    + $databases\['default'\]\['default'\] = array(
    + 'driver' =\> 'pgsql',
    + 'database' =\> 'databasename',
    + 'username' =\> 'username',
    + 'password' =\> 'password',
    + 'host' =\> 'localhost',
    + 'prefix' =\> '',
    + );
    + $databases\['default'\]\['default'\] = array(
    + 'driver' =\> 'sqlite',
    + 'database' =\> '/path/to/databasefilename',
    + ); Then you can easily acess data from that another database, for example, executing script in node.tpl.php like this:

db\_set\_active('my\_database'); $artikal = db\_select('my\_table', 'n') -\>fields('n') -\>condition('my\_row', $my\_variable, '=') -\>execute() -\>fetchAssoc(); and after acessing your other database, get back to default with

db\_set\_active('default');

db\_set\_active

5 database.inc db\_set\_active($name = 'default') 6 database.inc db\_set\_active($name = 'default') 7 database.inc db\_set\_active($key = 'default') 8 database.inc db\_set\_active($key = 'default') Sets a new active database.

Parameters $key: The key in the $databases array to set as the default database.

Return value The key of the formerly active database.

Related topics Database abstraction layer Allow the use of different database servers using the same code base. 2 calls to db\_set\_active()

File includes/database/database.inc, line 2522 Core systems for the database layer. Code function db\_set\_active($key = 'default') { return Database::setActiveConnection($key); }
> 1 votes

---
Tags: users
---


# Question
Title: How to move drupal 7 site in a different path from Home directory
what is the way to move drupal 7 site in a different path from Home directory. Currently my website is based on d7, so how i should move drupal 7 site to www.example.com/a/ instead of www.example.com

# Answer
> 0 votes
Depending on your server setup, it should not be hard. My only recommendation will be to disable the clean urls and the 444 permission of the settings.php file before moving the site over. After the move is done check if the .htaccess file is there, clean the cache, re-enable the clean urls and restore the permissions to the settings.php file to 444.

---
Tags: 7
---


# Question
Title: Field type "date" is not in the list of available field types
I'm trying to create a new content type with a field that would contain a date. However, the drop-down list for field type doesn't have "date". What's wrong?

p.s. drupal 7.17

# Answer
You need to install the date module:

http://drupal.org/project/date

Then enable the date module and that will give you the option to add a date field to your content type. Depending on your case you might want to check also the popup calendar module that is part of the date module to ease the date input.
> 5 votes

---
Tags: entities, 7
---


# Question
Title: Ubercart module, understanding drupal_get_form
This is all taken from ubercart uc\_attribute module.

So in hook\_form I have this:

```
  $items['admin/store/products/attributes/%uc_attribute/edit'] = array(
    'title' => 'Edit attribute',
    'description' => 'Edit a product attribute.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('uc_attribute_form', 4),
    'access arguments' => array('administer attributes'),
    'file' => 'uc_attribute.admin.inc',
  );

```

As far as I understand this menu entry will call the function drupal\_get\_form that will call the function uc\_attribute\_form using %uc\_attribute as a parameter.

Now if I go to the function definition:

```
function uc_attribute_form($form, &$form_state, $attribute = NULL) {

  // If an attribute specified, add its ID as a hidden value.
  if (!empty($attribute)) {
    $form['aid'] = array('#type' => 'value', '#value' => $attribute->aid);
    drupal_set_title(t('Edit attribute: %name', array('%name' => $attribute->name)), PASS_THROUGH);
  }

```

It is clear that $attribute is not an integer when it is used by this fucntion. It actually is an attribute stdClass object probably loaded by uc\_attribute\_load(...).

My question is: What's happening behind drupal\_get\_form that at the end an integer (the attribute ID) coming from the URL, ends being a full attribute standard object.

I'm kind of learning / developing a module extension and tried to backtrace but definitely couldn't get to an answer.

Thanks!

Juan B.

# Answer
> 1 votes
Its not related to `drupal_get_form`, its completely separated events sequentially fired in Drupal.

step 1 - First in menu: argument `%something` loaded via `something_load` and passed to `page callback` as parameters.

step 2 - Second in menu: `page arguments` will passed to function specified by `page callback`.

step 3- Third in `drupal_get_form`: get first argument `uc_attribute_form` as form ID and use it for build form and get second argument `4` from menu which loaded in step 1. `4` means fifth argument in path `0-admin/1-store/2-products/3-attributes/4-%uc_attribute/5-edit`

**EDIT:** read more about hook\_menu

> Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule\_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule\_abc' part defines the prefix for a load function, which here would be named mymodule\_abc\_load().

# Answer
> 0 votes
Thanks Mohammad but stilldidn't get it very clear. I kept looking in the documentation and I finally found it:

Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule\_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule\_abc' part defines the prefix for a load function, which here would be named mymodule\_abc\_load(). When a matching path is requested, your load function will receive as its first argument the path component in the position of the wildcard; load functions may also be passed additional arguments (see "load arguments" in the return value section below). For example, your module could register path 'my-module/%mymodule\_abc/edit':

```
  $items['my-module/%mymodule_abc/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );

```

When path 'my-module/123/edit' is requested, your load function mymodule\_abc\_load() will be invoked with the argument '123', and should load and return an "abc" object with internal id 123:

```
  function mymodule_abc_load($abc_id) {
    return db_query("SELECT * FROM {mymodule_abc} WHERE abc_id = :abc_id", array(':abc_id' => $abc_id))->fetchObject();
  }

```

Thanks anyway for the directions!

Juan

---
Tags: forms, ubercart
---


# Question
Title: In an Aegir platform how do I change what modules drush enables when a site is created
So far I have successfully in setting up Aegir and seting up a number of Platforms using makefiles. Now I want to tinker with one of the platform by adding a number of modules and tweaking some template files. I realize making these changes within the platform folder will propagate to all of the sites within that platform. What I want to know is, what do I have to change, so that when I provision a new site the new modules that I have added will automatically enabled? Does this have something to do with drushrc.php? it seems there are two, one in the platform and one in the site. I'm also wondering how to get Aegir to set certain values, like auto populating users.

# Answer
> 0 votes
Both requirements (auto enable modules and autopopulating users) can be done by Drupal install profiles or distributions. Install profiles are in Drupal, not in Aegir, but fits perfectly to Aegir.

In short, I recommend you to compile your install profile and use this profile in Aegir.

See more: http://drupal.org/project/distributions

---
Tags: 6, aegir, drush
---


title: Custom PHP processing page

text:
# Question
Title: Custom PHP processing page
I have a PHP page already written specifically for users to be directed to (sort of like a referrer link, and carries querystring values) from external sites. This page is not intended to have any theming or Drupal content, and only is supposed to show a a single block of text in the middle-center of page with the words `PROCESSING...`. The intended workflow here is as follows:

1. User clicks on a link from an affiliate-type site that links to something along the lines of `www.example.com?reciprocate.php?a=x&b=y&c=z` in my Drupal website.
2. `reciprocate.php` then checks if the user is currently logged in, and if not, presents the user with the Drupal login form, and preserves the querystring values in a post variable, and posts back to itself.
3. If the user is logged in, then the page will fetch some data from an external source, process it along with the original querystring values.
4. Depending on the results of the processing, the user will then be redirected to an appropriate URL (for authenticated users only) within the site.

I can't seem to find any way to do this with either Drupal core or contrib modules, and I know I should be creating a custom module to do this, but I honestly haven't got around to learning how to do that, but believe me I will soon! Therefore hopefully you will understand the approach I took...I know it's not great, but I'm trying to work with what little I know.

I've already created my page at the root of my site, with all of my processing code, but I just can't seem to access any Drupal globals using the following as a test:

```
<?php
    include("includes\bootstrap.inc");
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    global $user;
    if ($user->uid) {
       // do custom processing here
    } else {
       print drupal_get_form('user_login_block');
    }
?>

```

Please see if there is any way you can assist me, as I am really desperate. This may seem like a simple isolated block of code, but my site really relies on it. I thank you most humbly in advance!

# Answer
> 0 votes
**SOLVED!!**...I think :)

I decided to give the "Login Destination" module one last shot.

1. Created a rule for `reciprocate` as its own destination under Login Destination configuration.
2. Created a Page node, gave it some arbitrary title, and gave it a URL alias of `reciprocate`. This was associated as `Node-10` in Drupal.
3. In my theme, I cloned `node.tpl.php` and renamed it to `node--10.tpl.php`.
4. In this file I wiped everything and added my code from my original post above, starting from `global $user;...` (omitting the `DRUPAL_ROOT` definition bit).
5. Browsed to my new page (unauthenticated) and included some test querystring values: `http://localhost/kindred.test/reciprocate?a=x&b=y&c=z`
6. Was presented with a login block, and after logging in, I was redirected back to `/reciprocate` with my querystring values intact!!
7. My `// do custom processing here` ran successfully, and as a test pulled in my querystring values using `$_GET`

I'm really chuffed that worked out! took my entire weekend, but worth it in the end. Thank you though to kiamlaluno for your help and patience.

# Answer
> 1 votes
Your code should be similar to the index.php file that comes with Drupal, at least for the part that bootstraps Drupal.

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (user_is_logged_in()) {
  // do custom processing here
}
else {
  drupal_render(drupal_get_form('user_login_block'));
}

```

Drupal code requires the `DRUPAL_ROOT` constant to be defined, as that constant is used to include PHP files.

```
    case DRUPAL_BOOTSTRAP_SESSION:
      require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
      drupal_session_initialize();
      break;

```

If you look at the errors in the server log, it is probable you will find some errors about the constant not being defined, or about files not being found by `require_once`.

I am assuming you copied your PHP file in the same directory that contains index.php, and update.php that comes with Drupal.
Otherwise, the generic code to bootstrap Drupal from an external PHP file is the following one, suggested in drupal\_bootstrap() documentation.

```
define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

Replace `'path/to/drupal'` with the absolute path where the Drupal files are copied.

Instead of trying to render a specific form, I would rather redirect the users to the page containing the login form. This method allows you to set the destination of the login form, which where the users are redirected after they submitted the login form.

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (user_is_logged_in()) {
  // do custom processing here
}
else {
  // The following line is probably not necessary, but if the user access the page
  // with reciprocate.php?destination=anotherpage, s/he will be redirected to anotherpage.
  unset($_GET['destination']);

  drupal_goto('user/login', array('query' => array('destination' => str_replace('%2F', '/', rawurlencode('reciprocate.php?a=x&b=y&c=z')))));
}

```

With Drupal 8, the code to fully bootstrap Drupal is slightly different.

```
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

```
define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

The difference is the name of the directory containing the core files.

---
Tags: 7, users
---


title: Manual per-instance cropping

text:
# Question
Title: Manual per-instance cropping
I have tested tried out a couple of image-cropping modules listed here. None of them seemed to meet my expectation, but chances are I was doing something wrong. That's why I'm looking for your experience.

What I want is to enable the admin-to-be to manually select the area and crop uploaded images to a square based. I don't want to rely on automatic scale-and-crop effect provided by Drupal as it may trim the image inappropriately. So, I'd expect the module to offer a per-instance cropping.

Has anyone encountered that kind of capabilities?

# Answer
The Manual Crop module does the best job.

To quote the project page:

> The Manual Crop module exposes a set of image style effects that enables users, if enabled in the widget settings, to crop (and scale) an image after uploading.

Essentially this means you can choose a different crop area for each image style used.
> 1 votes

# Answer
This allows per instance cropping if you use the CKEDITOR + Media module: http://drupal.org/project/media\_crop

This is discussed in-detail on this blog post: http://www.drupalgardens.com/documentation/image-editor

I also used to use the Image Resize Filter: http://drupal.org/project/image\_resize\_filter

The last time I checked this did not work with Media based images because Image Resize Filter inserted its own image markup different from Media module's markup. Also Image Resize Filter (has never?) worked in WebKit based browsers.

EDIT:

note i didnt say media\_crop works with ckeditor+wysiwyg module. I have done a far amount of image\_styles in D7, used Media and various WYSIWYG editors + Fields. It's not pain free.
> 0 votes

---
Tags: media
---