# Question
Title: Comment.tpl.php how to add a link back to the node
In the comment.tpl.php I've shown the comment parent node title by:

```
$node->title

```

I need to make this title link back to the parent node:

$node-\>$node\_url

But this doesn't work. How should I do that?

# Answer
You can use the entity\_uri() and l() functions, similar to how it's done in template\_preprocess\_node():

```
$uri = entity_uri('node', $node);
$link = l($node->title, $uri['path'], $uri['options']);

```
> 1 votes

# Answer
Your code should almost work now, I think you missed a print right before the `url()`.

However, it's unsafe to simply print the node title without properly escaping it with `check_plain()`. So that's another good reason to use the `l()` function.
> 0 votes

# Answer
You can achieve your goal with the following line of code:

`<a href="<?php print url('node/'.$node->nid) ?>"><?php print $node->title; ?></a>`.
> -1 votes

---
Tags: theming, comments
---


# Question
Title: Database object syntax for where conditions giving error
I am trying to convert the following SQL query in calls to the database API.

```
SELECT p.id, p.message,t.posted, p.posted AS reply_date,p.poster_id,t.id,t.subject, t.forum_id FROM punbb.punbb_posts AS p JOIN punbb.punbb_topics AS t ON p.topic_id = t.id WHERE p.id = t.first_post_id;

```

What I get is the following code.

```
$query = db_select('punbb_posts', 'p')
  ->fields('p', array('id', 'message', 'posted', 'poster_id'));
$query->join('punbb_topics', 't', 'p.topic_id = t.id');
$query->addField('t', 'posted');
$query->addField('t', 'id');
$query->addField('t', 'subject');
$query->addField('t', 'forum_id');
$query->addField('t', 'first_post_id');
$query->condition('t.first_post_id','p.id');

```

The code generates the following SQL query.

```
    SELECT p.id AS id, p.message AS message, p.posted AS posted, p.poster_id AS poster_id, t.posted AS t_posted, t.id AS t_id, t.subject AS subject, t.forum_id AS forum_id, t.first_post_id AS first_post_id
FROM
{punbb_posts} p
INNER JOIN {punbb_topics} t ON p.topic_id = t.id
WHERE  (t.first_post_id = :db_condition_placeholder_0)

```

Why can't I get "PID"?

# Answer
> 0 votes
As pointed out by rooby, I will add my comment as an answer. Instead of using `->condition` which expects a placeholder to be dynamic, you can add the static condition to your `->join` syntax as in

```
$query = db_select('punbb_posts', 'p')
  ->fields('p', array('id', 'message', 'posted', 'poster_id'));
$query->join('punbb_topics', 't', 'p.topic_id = t.id AND t.first_post_id = p.id');
$query->addField('t', 'posted');
$query->addField('t', 'id');
$query->addField('t', 'subject');
$query->addField('t', 'forum_id');
$query->addField('t', 'first_post_id');

```

Alternatively, you can of course use Clive's option to use the `->where` syntax. However, from my experience adding it to the join should be a bit faster (if that matters in your application).

# Answer
> 1 votes
You need a `where()`:

```
$query = db_select('punbb_posts', 'p')
->fields('p', array('id', 'message', 'posted', 'poster_id'));
$query->join('punbb_topics', 't', 'p.topic_id = t.id');
$query->addField('t', 'posted');
$query->addField('t', 'id');
$query->addField('t', 'subject');
$query->addField('t', 'forum_id');
$query->addField('t', 'first_post_id');
$query->where('t.first_post_id = p.id');

```

---
Tags: 7, database
---


# Question
Title: How to set a $_POST var value as default value for a textfield webform component?
I need to set a `$_POST` variable value as the default value for a textfield webform component using Webform 4

In the Default Value field I filled with `%post[my$_PostVar]` but is not working.

**update: it seems like Webform 4 lost the %get and %post tokens** comment-6337368

any thoughts...

@googletorp

I installed the Availability Calendars module. This module shows a availability calendar and provide a formlet to allows the visitor to submit a booking.

When this form (the formlet) is submitted this is sent to a webform where the visitor will continue filling the personal data to complete the booking.

Then form let send these vars: `$_POST['arrival_date']` and `$_POST['departure_date']` to the Webform. Here is why I need to fetch these `$_post` values in the Webform components

> Booking integration by providing a small "formlet" that can post to (e.g.) a Webform.

and here some part of the Readme file of the module:

> Defining the 'complete booking form' webform -------------------------------------------- This part assumes you are using the webform module.
>
> * Define the webform components that the visitor should complete like name, e-mail, address, number of persons, etc.
> * Define webform components for the dates that are already filled in:
>
> + Begin date (default value: %post\[from\_display\]): the begin date.
>     + End date (default value: %post\[to\_display\]): the end date.

# Answer
> 0 votes
Webform 4 no longer uses so much of its own custom code.

It now uses drupal tokens like you would expect anywhere else.

Under the text area is a link "Browse available tokens." that will give you a javascript token browser to help you find the tokens you want.

You can access submission tokens like this: \[submission:values:FIELD\_KEY\]

The special tokens you are after though like %post are no longer supported in webform 4.x.

For more information see https://www.drupal.org/node/1001798

Your best bet for such token support would be for them to be added to the main token module or another third party token module in the global token space.

$\_GET tokens have an issue https://www.drupal.org/node/550164 however I don't think there is one for $\_POST at this stage.

Alternatively you can write a hook\_form\_alter() in a custom module and set the default value there using $\_POST.
That would be your easiest option I would say.

---
Tags: webforms
---


# Question
Title: Adding a validation handler to the registration form
I have altered the registration form to change the *thank you* message and add the validation of some fields.

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['actions']['submit']['#validate'][]  = 'checkout_nationality_form_validate';
    $form['#submit'][] = 'thank_on_submit';
  }

```

All code is working fine; my problem is the registration doesn't take the default Drupal validation. Why does this happen?

# Answer
You need to change this line

```
 $form['actions']['submit']['#validate'][]  = 'checkout_nationality_form_validate';

```

to

```
 $form['#validate'][] = 'checkout_nationality_form_validate';

```
> 5 votes

# Answer
Your custom validation function should go into the $form\['#validate'\] array

```
$form['#validate'] = 'checkout_nationality_form_validate';

```

I prefer using the implement hook\_form\_FORM\_ID\_alter instead of using an if statement in the hook\_form.

```
/**
 * Implements hook_form_form_id_alter().
 */
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'checkout_nationality_form_validate';
}

/**
 * Custom validation function.
 */
function checkout_nationality_form_validate(&$form, &$form_state) {
  if($form_state['value']['my_field'] == 'is not valid') {
    form_set_error('my_field', t('Value not valid'));
  }
}

```
> 4 votes

---
Tags: forms
---


# Question
Title: Why does node_add_body_field() lock down 'body' field instances to the 'node' entity type?
For a current project our taxonomy terms need a text field with a summary; naturally as there's already a body field available on nodes, I thought I'd just use that.

Confusingly, 'body' doesn't appear in the list of existing fields when managing fields for the taxonomy term. No problem thought I, I'll just use `field_create_instance()` and add it manually. Drupal objected:

> Attempt to create an instance of field body on forbidden entity type taxonomy\_term.

So I thought I'd get clever. I loaded up the field config, added taxonomy\_term to the array of entity\_types, and tried to update with `field_update_field()`. Nope:

> Cannot change an existing field's entity\_types property.

It turns out `node_add_body_field()` does this unconditionally:

```
$field = array(
  'field_name' => 'body',
  'type' => 'text_with_summary',
  'entity_types' => array('node'),
);
$field = field_create_field($field);

```

I (perhaps naively, not sure yet) disagreed with Drupal's various assessments, so I went into the database and manually added taxonomy\_term to the list of allowed entity types for the body field. Works great, I haven't noticed any ill-effects so far, and the body field is where I expect it to be.

So I guess my question is two-fold:

* What reason could there be for the node module locking down this field to a single entity type?
* Can I expect to see any bad effects from this further down the line?

# Answer
I would expect it is for historical reasons and is a place to migrate data from the old Drupal 6 body field.

Since the old Drupal 6 body field was just for nodes it seems in some ways logical that they would then also restrict this to just nodes so it is as it was in Drupal 6.

A couple of quick (not so thorough) greps didn't turn up any code that looks like it would cause you trouble using it for other entities but I could have missed something.

I would not think that this would cause you much trouble in future but I'm not sure of that.

A possible downside though is that it is in some ways like hacking core. If someone else inherits your site they may find it unusual that your site behaves differently than usual.

Personally sometimes I remove the drupal core body field and add my own field\_body and use that throughout the site.
> 3 votes

---
Tags: entities
---


# Question
Title: Show only nodes that are connected via entity reference with views
I am trying to create a simpler version of Organic Groups as I don't need most of it's functionality. What I am trying to do is use entity reference, nodeaccess\_userreference and nodeaccess\_nodereference to duplicate the bulk of what OG does.

At the moment I am trying to create the view to show all content types content that is linked to a "group" content type.

**Content types**:

Group

Link

Text Post

(basically reddit.com!)

**Fields**:

field\_group - entityreference to group content type attached to link and text post.

field\_shortname - textfield with a shorter name for group (no spaces, alphanumerical, etc..)

**Views**:

*Format*: Unformatted List

*Page*: /g/% \<---so I can use group name or shortened name to access group page

*Relationships*:

Entity Reference: Referenced Entity to field\_group (required)

*Contextual Filters*:

Content: Title

Content: Field\_shortname

Content: NID

(all requiring relationships to Entity Reference)

This way if some one goes to /g/Long-Group-Name-Blah-Blah /g/Shortername or /g/3 they will all point to the correct group page and show the link and text post content type content.

I can sort of get it to work if I just use Content: NID as the contextual filter. But I would like to be able to use the group name or shorter version in the URL as well. It also stops working as soon as I add 2 contextual filters.

Any help on getting this to work.

Thanks

# Answer
Contextual filters work combined (`AND`), so if you define two or more contextual filters, *all* of them have to pass.

Here's what I would do.

1. Use Pathauto to create a pattern for your group content, e.g. `g/[node:nid]`.
2. Create additional aliases for long name and short name.
3. Make your view work with just the NID contextual filter and use the block display type.
4. Configure your block to only show up on group node type and place it in main content.

Alternatively, you can also use Panels to create a similar node page for group nodes. To create the additional URL aliases for each group, you might want to try NodeSymLinks module.
> 0 votes

---
Tags: 7, entities, views
---


# Question
Title: How to add registration and login in a custom modules
I am creating a multi step form and in a one step i want to add user registration and login forms in as tabs and i have custom module which is uses to load multi step form,my problem is how i add registration and login forms in my page i try with things but didi't work out

```
  function garland_user_bar() {
  global $user;
  $output = '';

  if (!$user->uid) {
    $output .= drupal_get_form('user_login_block');
  }
  else {
    $output .= t('<p class="user-info">Hi !user, welcome back.</p>', array('!user' => theme('username', $user)));

    $output .= theme('item_list', array(
      l(t('Your account'), 'user/'.$user->uid, array('title' => t('Edit your account'))),
      l(t('Sign out'), 'logout')));
  }

  $output = '<div id="user-bar">'.$output.'</div>';
  return $output;
}

```

# Answer
> 1 votes
You to need render the form element.

Use the following to print the forms:

```
print(drupal_render(drupal_get_form('user_register_form')));
print(drupal_render(drupal_get_form('user_login_block')));

```

---
Tags: 7, theming, forms
---


# Question
Title: How can I access the CiviCRM contact record 'group' value(s) of the current user?
The unique key is email address. Perhaps there is a CiviCRM API?

**EDIT**

There is a CiviCRM API. My code so far:

```
civicrm_initialize();
$content = civicrm_api('contact', 'getvalue', array(
  'email' => $GLOBALS['user']->mail,
  'version' => 3,
  'return' => 'first_name')
);

```

I need the user's group, not first name.

# Answer
> 2 votes
You can even use 'email' api to get the contact id(as you have the email address in $GLOBALS\['user'\]-\>mail) and then use 'GroupContact' api as above to get the groups record.

```
$result = civicrm_api3('Email', 'get', array(
  'sequential' => 1,
  'return' => "contact_id",
  'email' => $GLOBALS['user']->mail,
));

```

---
Tags: civicrm
---


title: how to do node preview validation?

text:
# Question
Title: how to do node preview validation?
It is possible to set a Submit function for Preview button in an add/edit node form.

I would like to see if there is a possibility to go one step backward and validate the data to be previewed.

I **just and only** need to know how to have access to the **validation hook** for Preview button. (*I don't need Submit hook! I only need Validate hook for this button*)

# Answer
There is no difference between Form Submit button's validate hook and Form Preview button's validate hook.

If you set the form's validate hook in HOOK\_form\_validate, you have set a secondary validation hook (it means if the default validation hook is passed, then it's the turn of the one you have set) which can be used for both Submit button and Preview button:

```
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   $form['#validate'][] = 'XYZ_validate';
}

```
> 1 votes

# Answer
Yes you can set the submit for the preview button.

You can find the which button is clicked in hook\_node\_validate() method.

```
 function custom_node_validate($node, $form, &$form_state) {
           $button_value = $form_state['clicked_button']['#value'];
           if($button_value =="Preview"){
            //Do your stuff
           }
    }

```

It will give the clicked button value. For preview button you will get "Preview";
> 0 votes

---
Tags: 7, nodes, forms
---


# Question
Title: how to redirect to another site but still have same url
Is it possible to have an entire path from a drupal 7 site , eg. /externalpaths which will go to an outside application, yet still have the same domain name in the url, so that it looks like you have not left the drupal site ?

# Answer
There are two basic ways to accomplish this without resorting to iframes, you can either read the external application in with file\_get\_contents() and return it, but why take up a php process to accomplish this? A better way would be if you can enable mod\_proxy or equivalent for your webserver.

http://httpd.apache.org/docs/current/mod/mod\_proxy.html is the basic documentation for Mod Proxy. This is not always a good solution, however, if you can't modify the webserver settings or for when the external site is not returning correctly, it is often harder to determine where the issue lies.

If you enable a generic mod\_proxy setting you can enable the rules in .htaccess with the P flag. See http://httpd.apache.org/docs/current/rewrite/flags.html
> 0 votes

# Answer
You should be able to do that relatively easily with full HTML mode using an `<iframe src='desiredurl'></iframe>`. You will most likely want to do some custom styling/template editing to make it look good.

Whether that is a good soluton for you depends a bit on how you want it to look etc. Do note taht security restrictions can break it - and make custom scripting/styling problematic as well inside the iframe. I'd suggest reading the Mozilla Dev Network's iframe page.
> 2 votes

# Answer
You can use the iframe page module to embed the external site to the Drupal site.
> 1 votes

---
Tags: redirection
---


title: Show articles on new page

text:
# Question
Title: Show articles on new page
Is there a way to not promote articles on to the front page and instead gather them under a main menu link?

Like main menu link -\> myArticles and on click all articles written will be shown there?

# Answer
To prevent displaying from front page

Edit the article content type: /admin/structure/types/manage/article

In the Publishing options deselect the "Promoted to front page" checkbox.

And create a Page using views modules with filtering you content type and add link in the main menu.
> 0 votes

# Answer
Yes that would be relatively easy. How I would do that:

Edit the main menu: yoursite.com/admin/structure/menu/manage/main-menu and add menu item named `My Articles` (linking to a view is what I would do but you can choose to link it to anything you want - or nothing)

Edit the `article` content type: yoursite.com/admin/structure/types/manage/article

1. in `Publishing Options` *deselect* `Promoted to Front Page`
2. in `Menu Settings`:
    * check `Main Menu` under `Available Menus`
    * select `My Articles` (or whatever name you chose) in `Default parent item`

Then every time you create an article select `provide a menu link`. This will obviously work best for new sites where you don't have to go through and edit old articles to be in the menu.
> 2 votes

---
Tags: 7, nodes
---


# Question
Title: Can hook_field_extra_fields be used with field collections?
I have a field collection view that I have to manipulate some data on before it gets displayed, so I was going to use hook\_field\_extra\_fields with the extrafield\_views\_integration module. This worked great for me on nodes, but I'm not seeing the extra field get displayed on field collections. Is there any way to get around this?

```
function my_module_field_extra_fields() {
  $extra['field_collection']['my_field_collection']['display'] = array(
    'some_extra_field' => array(
      'label' => 'TESTING FIELD 123',
      'description' => 'This is a test of hook_field_extra_fields on FCs',
      'weight' => 100
    ),
  );

  return $extra;
}

```

# Answer
> 3 votes
The entity name for a Field Collection is actually `field_collection_item` and not `field_collection` (if you run `var_dump(entity_get_info())` you'll see this).

This means your implementation should actually look as follows:

```
/**
 *  Implementation of hook_fields_extra_fields().
 */
function my_module_field_extra_fields() {
  $extra = array();

  $extra['field_collection_item']['my_field_collection']['display'] = array(
    'some_extra_field' => array(
      'label' => t('TESTING FIELD 123'),
      'description' => t('This is a test of hook_field_extra_fields on FCs'),
      'weight' => 100,
    ),
  );

  return $extra;
}

```

Also, dont forget your `t()`'s ;-)

---
Tags: entities
---


# Question
Title: Title Patterns was printed in exactly its self
Look at image:

If you look to image, you will find a \[current-page:page-title\] | \[site:name\] patterns was printed, not replaced to real site name & node title ...etc, I dont know what is wrong was happens...

Token module, Page-title module was enabled, also when i try to change
PATTERN, its give me an error
invalid tokens: \[current-page:page-title\], \[site:name\]. invalid tokens: \[current-page:title\] invalid tokens: \[site:name\], \[site:slogan\]. (for front page)

Also, Im clear cach, and run a cron, and trancate table cashes from database manually ....

thanks a lot

# Answer
I think you should use `[current-page:title]` instead of `[current-page:page-title]`

* Run cron manually and clear the performance cache. If it doesn't help then
* Reload the same version of the Token module. If you use drush, command is:

drush dl token-\[version\]
> 1 votes

---
Tags: 7
---


title: How to get group id from custom url

text:
# Question
Title: How to get group id from custom url
I have some more custom url with og group id like

1. www.example.com/students/6593
2. www.example.com/results/6953
3. www.example.com/book-listing/5367/6953

here 6953 is a group id.

these are the sample link. my questions is how to get the group id from url? And i can't use arg(). because i have more no of url and group id position also varied.

There is any robust solutions for this.

# Answer
> 0 votes
I have used the following code in hook\_preprocess\_page() to solve this issue.

```
$url = current_path();
  $arguments = explode('/', $url);
  foreach ($arguments as $value) {
    if (is_numeric($value)) {
      $node = node_load($value);
      if (og_is_group('node', $node)) {
        drupal_set_message('group id :' . $node->nid);
      }
    }
  }

```

From now, i can set to group member only could see this page.

---
Tags: organic-groups, uri
---


# Question
Title: Why are all Drupal mails going to spam folder wheter it is reset password mail, account activation e-mail etc.?
All the e-mails from my site are going but they are going to spam folder, whether its the Drupal system generated mails like reset password mail, account activation mail etc. How can I prevent that?

# Answer
> 2 votes
This is not a technical sure fire solution. There can't be a sure fire answer either, because spam detection algorithms are different, even if the recipient mail server had same software, per-account activity and a lot of factors can be used to decide whether the email is spam or not.

There are some steps I take for every site before going them live. The obvious one is to not send spam content in first place, but other than the content itself, there are other ways to convince the recipient you are not spamming.

1. Setup SPF records for your domain. The spec is easy to understand, and there are tools to generate the record too. You need to make sure you only send emails from the correct IP addresses only.
2. Install MimeMail module. This is probably overlooked, but Drupal default mail class sends emails using php's mail() function directly. Mimemail does this too, but it adds extra headers and better mime information. All modules using drupal\_mail to send emails will be instantly compatible with the module. Think about going to a meeting with a basic dress vs a complete suit.

Mimemail trick is the most effective one I've tested.

---
Tags: hooks, emails
---


title: Combining fields in preprocess template

text:
# Question
Title: Combining fields in preprocess template
I want to combine two fields (say first name and last name) of a particular type of node so that the name displays correctly and I still have the individual fields to work with in different areas.

I saw this post What is best way to combine multiple fields in template preprocess? that explains how to combine two fields, but one I declare this new combined variable, how to I get it to display as the node?

Do I need to edit my node.tpl file? Should I have a node.tpl for this particular content type?

# Answer
Once you have preprocessed your variables in `theme_preprocess_node()` you can print them in `node.tpl.php`

The best practices would imply to declare one node.tpl.php per content type like this : `node--my-content-type.tpl.php` replacing `my-content-type` by the name of your own content.

In `theme_preprocess_node()` the best way to get the value of a field would be like this : In `template.php` the first function is only here so you can have one preprocess function per content type.

```
/**
 * Override or insert variables into the node templates.
 *
 * @param $vars
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */
function mytheme_preprocess_node(&$vars, $hook) {
  // Optionally, run node-type-specific preprocess functions, like
  // mytheme_preprocess_node_page() or mytheme_preprocess_node_story().
  $function = __FUNCTION__ . '_' . $vars['node']->type;
  if (function_exists($function)) {
    $function($vars, $hook);
  }
}

```

Then you can declare your function for your content type and get the value of your fields with `field_get_items()` and `field_view_value()` in order to only get the value and not all the divs all around the field value.

```
/**
 * Override or insert variables into the node templates.
 *
 * @param $vars
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */
function mytheme_preprocess_node_my_content_type(&$vars, $hook) {
  $node = &$vars['node'];
  $first_name = field_get_items('node', $node, 'field_first_name');
  $last_name = field_get_items('node', $node, 'field_last_name');
  $vars['first_name'] = field_view_value('node', $node, 'field_first_name', $first_name[0]);
  $vars['first_name'] = field_view_value('node', $node, 'field_last_name', $last_name[0]);
}

```

and then in your `node--my-content-type.tpl.php` you can print your variable like this :

```
<?php print render($first_name); ?> <?php print render($last_name); ?>

```
> 1 votes

# Answer
If you add some login to your THEME\_preprocess\_node function, in template.php, so vars declared on that function are available on node.tpl or other templates declared for that node (Here instructions about theme hook suggestions).

```
<?php
/**
 * Implements hook_preprocess_node().
 */
function mytheme_preprocess_node(&$vars) {
  $vars['my_custom_variable'] = 'This is the value!';
}
?>

```

On node.tpl you could access this variable in this way:

```
<?php
print $my_custom_variable;
?>

```
> 0 votes

---
Tags: theming
---


# Question
Title: Undefined index: und on search-result.tpl.php for Taxonomy Terms
I want to show the node title and related taxonomy terms in a table and modifying the search-result.tpl.php to do this.

What I use to for taxonomy terms is that:

```
<td class="field-item">
<?php
    $str = '';
    foreach($result['node']->field_my_taxonomy_term['und'] as $obj)
        $str .= l($obj['taxonomy_term']->name, 'taxonomy/term/' . $obj['tid']) . ', ';
    print trim($str, ', ');
?>
</td>

```

This code works in one of my Drupal website and **doesn't work** on another one and gives this error:

```
Notice: include() (.../search-result.tpl.php  line 20) Undefined index: und.
Warning: include() (.../search-result.tpl.php  line 20) Invalid argument supplied for foreach().

```

How can I show the taxonomy terms related to the node in search-result.tpl.php?

# Answer
It's either that your field has a set language (not `'und'` which stands as 'undefined') or that you have no value for `field_my_taxonomy_term`.

Either way you should add this control before your foreach (I also rewrite it to fit Drupal best practices) :

```
<td class="field-item">
  <?php $str = ''; ?>
  <?php if (isset($result['node']->field_my_taxonomy_term[LANGUAGE_NONE]) && $result['node']->field_my_taxonomy_term[LANGUAGE_NONE]): ?>
    <?php foreach ($result['node']->field_my_taxonomy_term[LANGUAGE_NONE] as $obj): ?>
      <?php $str .= l($obj['taxonomy_term']->name, 'taxonomy/term/' . $obj['tid']) . ', '; ?>
    <?php endforeach ?>
    <?php print trim($str, ', '); ?>
  <?php endif ?>
</td>

```
> 1 votes

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


# Question
Title: Changing value of min / max resolution for an image field dynamically based on a previous select list
Does anyone know if there is a way in Drupal 7 to change dynamically the value of minimum / maximum resolution for an image base on a previous select list.

Example :

I have a select with 3 elements :

* Square
* Portrait
* Landscape

When I select Square, the min / max resolution would be set to 200x200, if Portrait 200x400 and landscape 400x200.

I could create 3 different image field but in the future I'll have more type of layouts and I'd rather have only one image field (for database and theming purpose)

I was thinking State API but no solution there.

# Answer
> 0 votes
I came up with a good solution using #ajax property from the Form API :

I declare `hook_form_alter` and add the #ajax on my push type select field.

```
/**
 * hook_form_alter
 */
function my_module_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'push_node_form') {
    // Add id to field image for ajax reload
    $form['field_push_image']['#prefix'] = '<div id="image-field-to-reload">';
    $form['field_push_image']['#suffix'] = '</div>';
    // Create ajax reload function
    $form['field_push_type'][LANGUAGE_NONE]['#ajax'] = array(
      'callback' => 'reload_image_field_resolution',
      'wrapper' => 'image-field-to-reload',
      'method' => 'replace',
      'effect' => 'fade',
    );
  }
}

```

Then in the field settings I put a resolution as a key from the select list like this :

200x200|Square

200x400|Portrait

400x200|Landscape

And then I reload the image field with the proper resolution base on the select value key.

```
/**
 * Ajax callback to reload the image field
 */
function reload_image_field_resolution($form, $form_state) {
  // Get the value of the push type
  $type_value = $form['field_push_type'][LANGUAGE_NONE]['#value'];
  // Explode the value to make sure that it's a good safe key value representing
  // a resolution like this : 100x100
  $resolution = explode('x', $type_value);

  if (count($resolution) == 2 && is_numeric($resolution[0]) && is_numeric($resolution[1])) {
    // If the value is good, build a new array containing the new resolution
    $min_max_resolution = array(
      $type_value,
      $type_value
    );
    // Reset the max and min with of the image field
    $form['field_push_image'][LANGUAGE_NONE][0]['#upload_validators']['file_validate_image_resolution'] = $min_max_resolution;
    // Set the variable to pass to the theme function with empty description otherwise
    // the old string (with the basic resolution) will be concatenated to the new string.
    $variables = array(
      'description' => '',
      'upload_validators' => $form['field_push_image'][LANGUAGE_NONE][0]['#upload_validators']
    );
    // Return the approriate altered string using theme_file_upload_help()
    $form['field_push_image'][LANGUAGE_NONE][0]['#description'] = theme_file_upload_help($variables);
  }

  // Return the image field with its new resolution
  return $form['field_push_image'];
}

```

---
Tags: forms, media
---


title: How to use token in Global: PHP field

text:
# Question
Title: How to use token in Global: PHP field
In View, there is this field called "Global: PHP". I wonder how I can use token in this field in Drupal 7. I can easily use token in "Global: Custom text" but not in "Global: PHP"

# Answer
> 2 votes
In a "Global: Custom Text" you will see a number of tokens listed under "Replacement patterns", such as \[title\], \[php\] (referring to a "Global: PHP" field), \[nothing\] (referring to another "Global: Custom Text" field), ...

These tokens (or replacement patterns), are not listed when working with a "Global: PHP" field, you can only see a list of "Available variables", and if you put a token in the "Output code" textarea, it does not get replaced.

However, there is a way to access these tokens in "Global: PHP" fields. For example, if you are trying to access the \[nothing\] token, put the following code in the "Output code" textarea (not in the "Value code" textarea):

```
<?php
$static = $view->display_handler->get_handlers('field');
echo $static['nothing']->last_render;
?>

```

Solution found here: https://www.drupal.org/node/507012#comment-3410296

Except it was for Drupal 6, so they used `$this->view`. In Drupal 7, you have to use `$view`.

# Answer
> 1 votes
The tokens stand in for values from, say, the $node object for example. So if you're using php instead of using a token like `[title]` you'd call it with `$node->title` or the equivalent. If you don't know what variables are available to you, try the Devel module to help you navigate those objects and arrays.

# Answer
> 0 votes
This file is from Views PHP module. It gives the ability to use raw PHP field as a normal field so you can process the results in real time. It makes other fields available as php variables. You can of course use tokens in Custom text fields. But you can't process them (e.g You can't show sum of 2 tokens using a custom text field). Views PHP solves this by giving you a place to enter the PHP code.

You can use $data *object* to access data of the *current field* and the *current view*. You can use a code like below to see all avail. variables.

```
<?php
print '<pre>'.print_r($data, TRUE).'</pre>';
?>

```

---
Tags: views
---


# Question
Title: Converting MySQL to db_select with subquery count
I have an SQL query, with subquery, that returns as set of nodes ordered by referenced nodes... It works fine in a `db_query`, but I need it to be dynamic, and it feels like a better idea to use Drupal's abstraction layer.

I have got so far, but I am having issues with the subquery. It doesn't appear to having any effect...

I should say I used the Query Coder module to help do the conversion.

**SQL**:

```
SELECT n.nid , dest.field_flight_hero_destination_tid  hero_desintation_tid , (
SELECT COUNT( * )
FROM {field_data_field_field_route_matrix} routes
LEFT JOIN  {field_data_field_flight_destination} destination ON routes.field_field_route_matrix_target_id = destination.entity_id
WHERE routes.entity_id = n.nid
AND  field_flight_destination_tid
IN (:stopovers_tids)
)total
FROM node n
LEFT JOIN  field_data_field_flight_hero_destination dest ON n.nid = dest.entity_id
LEFT JOIN field_data_field_flight_price_matrix prices ON n.nid = prices.entity_id
LEFT JOIN field_data_field_flight_cabin_class class ON n.nid = class.entity_id
WHERE dest.field_flight_hero_destination_tid = :destination_tid AND class.field_flight_cabin_class_tid IN (:class_tid)
ORDER BY total DESC

```

**db\_select**:

```
// Subquery.
  $subquery  = db_select('{field_data_field_field_route_matrix}', 'routes');
  $subquery->addExpression('COUNT(*)', 'count');
  $subquery->leftJoin('{field_data_field_flight_destination}', 'destination', 'routes.field_field_route_matrix_target_id = destination.entity_id');
  $subquery->condition('routes.entity_id', 'n.nid');
  $subquery->condition('field_flight_destination_tid', $stopovers);

  // Main query sorted by subquery.
  $query = db_select('node', 'n');
  $query->fields('n', array('nid'));
  $query->fields('dest', array('field_flight_hero_destination_tid'));
  $query->addJoin('', $subquery, 'total');
  $query->leftJoin('field_data_field_flight_hero_destination', 'dest', 'n.nid = dest.entity_id');
  $query->leftJoin('field_data_field_flight_price_matrix', 'prices', 'n.nid = prices.entity_id');
  $query->leftJoin('field_data_field_flight_cabin_class', 'class', 'n.nid = class.entity_id');
  $query->condition('dest.field_flight_hero_destination_tid', $destination);
  if (!empty($cabin_class)) {
    $query->condition('class.field_flight_cabin_class_tid', array($cabin_class), 'IN');
  }
$query->orderBy('total.count', 'DESC');
$result = $query->execute();

```

**Generated output**:

```
[queryString] => SELECT n.nid AS nid, dest.field_flight_hero_destination_tid AS field_flight_hero_destination_tid
FROM
node n
 JOIN (SELECT COUNT(*) AS count
FROM
field_data_field_field_route_matrix routes
LEFT OUTER JOIN field_data_field_flight_destination destination ON routes.field_field_route_matrix_target_id = destination.entity_id
WHERE  (routes.entity_id = :db_condition_placeholder_1) AND (field_flight_destination_tid IN  (:db_condition_placeholder_2)) ) total
LEFT OUTER JOIN field_data_field_flight_hero_destination dest ON n.nid = dest.entity_id
LEFT OUTER JOIN field_data_field_flight_price_matrix prices ON n.nid = prices.entity_id
WHERE  (dest.field_flight_hero_destination_tid = :db_condition_placeholder_0)
ORDER BY total.count DESC
)

```

**Devel dpq**:

```
SELECT n.nid AS nid, dest.field_flight_hero_destination_tid AS field_flight_hero_destination_tid
FROM
{node} n
 JOIN (SELECT COUNT(*) AS count
FROM
{field_data_field_field_route_matrix} routes
LEFT OUTER JOIN {field_data_field_flight_destination} destination ON routes.field_field_route_matrix_target_id = destination.entity_id
WHERE  (routes.entity_id = 'n.nid') AND (field_flight_destination_tid IN  ('31', '366')) ) total
LEFT OUTER JOIN {field_data_field_flight_hero_destination} dest ON n.nid = dest.entity_id
LEFT OUTER JOIN {field_data_field_flight_price_matrix} prices ON n.nid = prices.entity_id
WHERE  (dest.field_flight_hero_destination_tid = '86')
ORDER BY total.count DESC

```

# Answer
> 0 votes
Your adding the subquery via a `join`. you want the subquery to be run as piece of the outermost `Select` statement, which Drupal 7 `SelectQuery` cannot do see:

https://stackoverflow.com/questions/20214014/how-do-i-place-a-sub-query-in-a-select-statement-in-drupal7

The easiest way to do this to use `db_query` (a string) or maybe `hook_query_alter` after adding a tag to the `db_select` query and adding in the subquery via a string later. If you need additional info passed in and out the `hook_query_alter` then use the metadata options.

---
Tags: 7, database
---


# Question
Title: Drupal JS add noscript after every <script> tag
I'm looking for a way to add the noscript tag after every tag. Even the file tags. I cannot have alternatives as the client I'm doing this for has made this mandatory for 508 purposes. I believe the software they are using is failing the 508 scan because of this.

Example below.

```
<script type="text/javascript" src="http://local.dev/misc/jquery.once.js?v=1.2"></script>
<noscript>Your browser does not support Javascript</noscript>
<script type="text/javascript" src="http://local.dev/misc/drupal.js?neolt5"></script>
<noscript>Your browser does not support Javascript</noscript>

```

# Answer
Use the html.tpl.php of your theme to add the noscript tag using the $scripts array.

```
$scripts = str_replace("\n", "\n<noscript>Your browser does not support Javascript</noscript>\n", $scripts);

```

Note : html.tpl.php will apply this for all pages of your theme.if you want to do it for specific content type pages or specific pages then use the specific template.See Drupal 7 template suggestions for more information.
> 4 votes

---
Tags: javascript
---


# Question
Title: Safe change of field type from text to email or link
I have some field types that are in text and have data and I need them to be a link or email type (ie. email module.) I realize there are several approaches: change in D7 database. Use the migration module. Export as Feature and re-import.

Does someone have experience addressing this and a suggested approach?

# Answer
> 3 votes
A different approach could be - Why try to change field type ? Why not copy old to new ?

You could possibly use something like views data export or other similar module to create a dump of your nodes as node ID and text field to csv file.

Then create your new field.

Then use feeds to import your csv and assign the old text field column to your new field. Make sure you tick the box to update nodes !

Then delete your old field.

# Answer
> 1 votes
Use the db\_change\_field(). See the similar answer given by heddn

---
Tags: entities, migrations
---


title: Alter weather block behaviour?

text:
# Question
Title: Alter weather block behaviour?
In the weather module, if a user has not configured a custom weather block, the block does not display:

```
/**
 * Implement hook_block_view().
 */
function weather_block_view($delta = '') {
  global $user;
  module_load_include('inc', 'weather', 'weather.common');
  $block = array();
  // Handle the 'system_NUMBER' type of blocks
  if (strpos($delta, '_') === FALSE) {
    $display_type = $delta;
  }
  else {
    list($display_type, $display_number) = explode('_', $delta);
  }
  $forecast_days = (int) variable_get('weather_forecast_days', '2');
  switch ($display_type) {
    case 'user':
      if (weather_access_userblock()) {
        // Show the user's custom weather block, if there is already
        // a place configured. Otherwise, do not show the block.
        $places = weather_get_places_in_use('user', $user->uid);
        if (!$places) {
          return;
        }
        ...
        [from weather.module]

```

Is there a way of displaying a 'Please set your weather location' link, instead of nothing at all, without applying a patch to the module?

Thanks.

# Answer
Use the hook\_block\_view\_MODULE\_DELTA\_alter in your custom module to display text if user has not configured the custom location.you can access the current user object from global $user if you want to perform any operation on it.

```
/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function demo_wipe_block_view_weather_user_alter(&$data, $block) {
//Check here that whether user has configured or not.
  if(!is_array($data)) {
    $data['subject'] = t('Blah Blah Blah!');
    $data['content'] = t('Blah Blah Blah! link');
  }
}

```

P.S. : I have tested it on php 5.5.3

I think you should also specify this as a feature request in the module issue queue to set default whether location(that should be in admin configuration) on user whether block if user has not configured the block yet.
> 2 votes

# Answer
You could just create your own wrapping block. Implement hook\_block\_view, and call `weather_block_view` from it.

If you get back a useful response, simply return it as your own blocks output. If you don't, return your own output instead, by generating the appropriate link with `l`.
> 0 votes

# Answer
1. Enable PHP Filter module.
2. Create custom block, add on textarea "Please set your weather location" link , set title to "Weather".
3. Set PHP visibility for block next code: `global $user;
$places = weather_get_places_in_use('user', $user->uid);
return !$places;`
4. Move block position to under Weather block.
5. So when user doesn't set Weather, he will see set location link block, otherwise, he will see Weather block. No hacks :)
> -2 votes

---
Tags: blocks
---


# Question
Title: how could the global $user be different between the Drupal interface and Services module?
If i do:

```
hook_node_view($node, $view_mode, $langcode) {
        global $user;
        var_dump($user);
        die();
        // i get the correct dump of the current pre-authorized user
}

```

HOWEVER, if I dump `global $user` from one of my public `Service` endpoints an anonymous user. That dump comes from a GET service resource defined as:

```
'retrieve' => array(
       'help' => 'Retrieves a note',
       'file' => array('file' => 'inc', 'module' => 'noteresource'),
       'callback' => '_noteresource_retrieve',
       'access callback' => '_noteresource_access',
       'access arguments' => array('view'),
       'access arguments append' => TRUE,
       'args' => array(
         array(
           'name' => 'id',
           'type' => 'int',
           'description' => 'The id of the note to get',
           'source' => array('path' => '0'),
           'optional' => FALSE,
         )
       )
     )

```

How could that be?

**For my Drupal configuration**: I am using `LoginToboggan` and `Generate Password` to handle registrations with only an email address. Alongside I am using the `Services` module which drives the API for our mobile app to tell the app if the user is logged in or not.

Under /admin/config/system/**logintoboggan** I have:

> * I have "Set password" checked
> * a "pre-authorize" permission selected for the "non-authenticated" role prior to email validation.
> * I "never delete" unvalidated users
> * I allow "immediate login" checked

Under /admin/config/people/**accounts** (regarding passwords), I have:

> * Selected "Users may enter a password on registration. If left empty, a random password will be generated. This always applies when an administer is creating the account."
> * Selected "Do not display" under generated password display.

The flow works well from the Drupal interface. That is, the registration is successful, the email is sent, and the user is logged immediately with the pre-authorize role applied even before validating their email. HOWEVER, my API endpoints still show that same user as `anonymous` users session when accessing it with `global $user`. I can literally reload the two pages as if there were no connection between them.

I have cleared all caches. I have weight-ordered the roles with `pre-authorzed` 2nd, after `anonymous` and before `authenticated user` I have verified the JS cookies are identical between the API page and Drupal interface (see the side by side comparison in the screenshots below) and that the $\_SESSION globals shows nothing pre-authorized or more.

Is there another way I should access the pre-authorized user other than global $user?

# Answer
Nice question! After reading your question. you are not logged in to your app because you are sending the anonymous requests after login. Workflow should be like this : 1)User register on the site.you will get the session id and session name. 2)Now need to set the session id and session name in headers then send the requests. you can check the same in drupal logs that whether your requests are coming from anonymous user or authenicated user. if drupal getting the requests from anonymous user then make sure that headers are properly set. See the services module documentation to learn out about this. **Browser tools** :

1. The Poster add-on for Firefox.
2. The REST Console app for Chrome.

if you are using the services module then take a look at its documentation
> 0 votes

---
Tags: users, services, authentication-authorization
---


# Question
Title: Force authentication for specific IP range on IIS
I have a Drupal 6 installation as a corporate Intranet site. I would like to permit a set of IP ranges the ability to view the site anonymously, and anything that does not match that rule must authenticate (either by form, or by HTTP - either would be fine).

I've looked at httpauth (obsolete) - this could be made to work, but I found it wasn't reliable under IIS.

I looked at securesite (what took the place of httpauth), but was getting issues with the form authentication (didn't look at the http authentication portion in detail).

In both cases, the modules didn't seem to be configurable to configure that behaviour on a per-ip basis, but I expect could be modified to do so.

Anyone know of anything out there that might solve this problem?

# Answer
> 0 votes
Use the Rules module to determine if the user is from a specific IP range, or is authenticated. If they are not from that IP range or not logged in, redirect to Login page.

1. Install and enable Rules module.
2. Create a new Rule that is triggered when Drupal is initializing.
3. Add a Condition of Data, Text Comparison
4. Add a Data field of `site:current-page:path` that matches `user`, and negate the condition so this Rule requires this Condition to be False.
5. Add a Condition Or group, set it to Negate, so that if neither condition are positive it will execute an action
6. Within the Or group, add a condition that executes PHP Code. Enter PHP code that returns True if the IP is in range (learn how to get the visitors IP).
7. Within the Or group, add another condition of User's role. Configure the condition to return true if the User has the Authenticated User role.
8. Add an Action of Page redirect, and redirect the user to user, or some other page where they can login.
9. Save and enable the Rule.

---
Tags: 6, users
---


# Question
Title: user-profile-edit.tpl.php not working for user#1
I am going crazy on this one :-/

I have overridden my user edit page with a user-profile-edit.tpl.php

In my template I have:

```
function mytheme_theme() {
  $items = array();
  $items['user_profile_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'mytheme') . '/template',
    'template' => 'user-profile-edit',
    'preprocess functions' => array(
      'mytheme_preprocess_user_profile_form'
    ),
  );
  return $items;
}

```

My problem is that my user-profile-edit.tpl.php is not being picked up by user#1, it is working however for all other authenticated users.

Is there some setting i am overlooking here?

# Answer
> 0 votes
It seems that your themes are different for your users because the template name is fine. It will work fine with the theme in which you have added the template.

---
Tags: theming, users
---


# Question
Title: How can I set time limit for each question in quiz module?
I have been searching for settings where I set time for each question in a quiz. For example setting 30 seconds for allowing answer to a question.

I wonder why this option is not available in quiz module? It's so important. I'm not able to find this option when creating a quiz.

Is there any additional module available for it?

# Answer
> 0 votes
Searching google for 'drupal quiz timer' brings up an issue from the module queue that is fixed, and points the reader to the FAQ's for the module.

Apparently you need UserPoints and JQuery Countdown modules enabled, then go to `admin/quiz/settings` to enable.

---
Tags: quiz
---


title: Rules Interface unresponsive and odd

text:
# Question
Title: Rules Interface unresponsive and odd
I am trying to set up a Rule to check if a user has added one of several states to an address field in a Profile2 profile. So I thought I'd do a Data Comparison.

1. I created a new rule called "Profile Save"
2. Added an Event from the drop down menu: "After saving a new profile"
3. Added "Entity has field"

Parameter: *Entity*:\[profile2\], *Field*:field\_address
4. Added AND and Add Condition,
5. chose "Data comparison"

But the Data Comparison form is all wonky. The drop down has div tags in it. The "Data Selectors" isn't active.

Do I have to already know what the Data selector should be? Or should it be available in the drop down?

(See images)

Any idea what I'm doing wrong? Is this a known issue with Data Comparison.

# Answer
> 1 votes
That data selection interface often has jQuery Update-related issues; for the most part those should be solved by using the dev version (at the time of this answer) of jQuery Update and the current stable of Rules (7.x-2.7) as recommended by https://www.drupal.org/node/1810656#comment-9298435. That issue also has a good history of these problems.

Another issue appears to describe your exact issue and has a patch. It sounds like that resolved the problem, so future visitors might try that as well after seeing if updating jQuery Update doesn't work.

---
Tags: rules, users
---


# Question
Title: Using Webform as an Application for membership/user roles
I'd like to implement the following on a Drupal site:

* Anonymous site visitor (Joe) submits a membership application with various custom fields
* Admin (Jane) reviews membership application
* Jane approves Joe's application and creates new user account
* Joe gets notice of approval and login information

Possible solutions:

* A **Webform** (But how can the data from the webform be easily transferred into a user account?)
* **Profile2** with Admin approval necessary. (The problem with this one is we don't want it to feel to the user like they are creating an account on the site, but applying for the membership.)
* Create a **Membership** content type that an anonymous user can fill out (?)

I feel like I'm overlooking something obvious.

I can't use the core user registration with additional fields because there are 3 different types of memberships. And users should be able to change from 1 membership to another (upon approval).

# Answer
Based on some other questions you've asked on this site I wonder if you are using CiviCRM for tracking the memberships? If so I might suggest this workflow:

* Setup a webform with CiviCRM integration. Add your membership and other custom fields to the form.
* Set the membership status to be "Approval Needed" (you can create that status in CiviCRM if it isn't there already).
* Have it send an email to your staff whenever that form is filled out.
* You can optionally restrict access to that form so that only non-members can use it. This would require you to enable the module 'CiviMember Roles Sync' which is bundled with CiviCRM and enabled syncing between Drupal roles and Civi memberships.
> 6 votes

---
Tags: webforms, users
---


# Question
Title: Can a Drupal site design (not just colors, fonts, etc -- template stuff) be replicated over multiple drupal sites?
I will apologize in advance for using the L word...but in Lotus Notes there is the concept of a Template file that holds all the design elements of a database...fields, views, forms, etc. -- has a .ntf extension. That template can then be used as the design model for other notes databases which have .nsf extensions. For instance if I have a business model where all my customers do the same thing - say bands keeping track of songs and tours. I have one bandmaster.ntf file and band01.nsf, band02.nsf, band03.nsf, etc. The data in each .nsf file is specific to each band...but the design of the database is exactly the same. Each db inherits it's master design from the one .ntf file.

If I have say a contact form and need to add a new field to it ... say "Alternate Email" -- I open the design of the .ntf file and add that field to my contact form. Then I 'refresh' the design of all my bandxx.nsf databases and they all now have the new field.

Is there any way to do something like that in Drupal? Is there a way to export maybe a site's design and use that as the design structure for one or more sites?? I'm just getting started with Drupal. Thank you for any information.

ER

# Answer
> 0 votes
Just to be able to replicate additional fields that you may add to bundles on a "master" site to several other sites, you may use Bundle Copy.

This project provides export/import support for:

* Node types
* Taxonomy
* User
* Field API fields
* Field groups

It will only export/import the bundle definition, not the content.

For a more elaborate export/import module that not only handles fields, but whole features, take a look at Features.

From the module's description:

> Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

---
Tags: theming
---


# Question
Title: After upgrading, the Search module gives no results
I have upgraded a website from D6 -\> D7 using Drush `site-upgrade` command. Using a bash script it takes a `drush archive-dump` of a D6 site, assures it's at the latest version of D6 and upgrades it to Drupal 7. After the upgrade I apply a new theme and configuration via the `Configuration` module.

After the upgrade if I do a re-index of Search I see the following output:

```
drush cron -v
Initialized Drupal 7.33 root directory at                              [notice]
/var/www/2014/comparative_literature/snapshot/dest_www
Initialized Drupal site comparative-literature at                      [notice]
sites/comparative-literature
Indexing node 1.                                                    [ok]
Indexing node 2.                                                    [ok]
Indexing node 3.                                                    [ok]
Indexing node 4.                                                    [ok]
Indexing node 5.                                                    [ok]
Indexing node 6.                                                    [ok]
Indexing node 7.                                                    [ok]
Indexing node 8.                                                    [ok]
Indexing node 9.                                                    [ok]
Undefined index: email email.module:109                                [notice]
Undefined index: email email.module:109                                [notice]
Undefined property: stdClass::$uri file.module:737                     [notice]
Undefined property: stdClass::$filemime file.module:775                [notice]
Undefined property: stdClass::$filemime file.module:819                [notice]
Undefined property: stdClass::$filemime file.module:862                [notice]
Undefined property: stdClass::$filemime file.module:834                [notice]
Undefined property: stdClass::$filemime file.module:834                [notice]
Undefined property: stdClass::$filemime file.module:834                [notice]
Undefined property: stdClass::$filemime file.module:834                [notice]
Undefined property: stdClass::$filemime file.module:744                [notice]
Undefined property: stdClass::$filesize file.module:744                [notice]
Undefined property: stdClass::$filename file.module:750                [notice]
Indexing node 15.                                                   [ok]
Undefined index: email email.module:109                                [notice]
Undefined index: email email.module:109                                [notice]
Undefined property: stdClass::$uri file.module:737                     [notice]
Undefined property: stdClass::$filemime file.module:775                [notice]
Undefined property: stdClass::$filemime file.module:819                [notice]
Undefined property: stdClass::$filemime file.module:862                [notice]
Undefined property: stdClass::$filemime file.module:834                [notice]
Undefined property: stdClass::$filemime file.module:834                [notice]
Undefined property: stdClass::$filemime file.module:834                [notice]
Undefined property: stdClass::$filemime file.module:834                [notice]
Undefined property: stdClass::$filemime file.module:744                [notice]
Undefined property: stdClass::$filesize file.module:744                [notice]
Undefined property: stdClass::$filename file.module:750                [notice]
Indexing node 16.                                                   [ok]
Indexing node 18.                                                   [ok]
Indexing node 19.                                                   [ok]
Indexing node 20.                                                   [ok]
Indexing node 21.                                                   [ok]
Indexing node 22.                                                   [ok]
Indexing node 23.                                                   [ok]
Indexing node 24.                                                   [ok]
Indexing node 25.                                                   [ok]
Indexing node 26.                                                   [ok]
WD cron: Cron run completed.                                           [notice]
Cron run successful.                                                [success]
Command dispatch complete                                              [notice]

```

This site is simple like 3 content types which are Basic Page, Faculty and News items. Pages index fine above, and the News and Faculty throw errors do to `file` (people headshots) and email field issues I guess ...

But, when I use the site to Edit a page or uplaod an image to the Faculty member it appears to work fine. **The search index is Built and content is in the tables but nothing ever returns from searching for say `academics` and its a keyword in the built index found in basic Drupal "Page" content type nodes.**

The search page sometimes spits out notices such as (related to file field issues, email field issues, etc):

```
Notice: Undefined index: email in email_field_formatter_view() (line 109 of /project/drupalwww/sites/mysite/modules/contrib/email/email.module).
Notice: Undefined index: email in email_field_formatter_view() (line 109 of /project/drupalwww/sites/mysite/modules/contrib/email/email.module).
Notice: Undefined property: stdClass::$uri in theme_file_link() (line 737 of /project/drupalwww/modules/file/file.module).
Notice: Undefined property: stdClass::$filemime in theme_file_icon() (line 775 of /project/drupalwww/modules/file/file.module).
Notice: Undefined property: stdClass::$filemime in file_icon_path() (line 819 of /project/drupalwww/modules/file/file.module).
Notice: Undefined property: stdClass::$filemime in file_icon_map() (line 862 of /project/drupalwww/modules/file/file.module).
Notice: Undefined property: stdClass::$filemime in file_icon_path() (line 834 of /project/drupalwww/modules/file/file.module).
Notice: Undefined property: stdClass::$filemime in file_icon_path() (line 834 of /project/drupalwww/modules/file/file.module).
Notice: Undefined property: stdClass::$filemime in file_icon_path() (line 834 of /project/drupalwww/modules/file/file.module).
Notice: Undefined property: stdClass::$filemime in file_icon_path() (line 834 of /project/drupalwww/modules/file/file.module).
Notice: Undefined property: stdClass::$filemime in theme_file_link() (line 744 of /project/drupalwww/modules/file/file.module).
Notice: Undefined property: stdClass::$filesize in theme_file_link() (line 744 of /project/drupalwww/modules/file/file.module).
Notice: Undefined property: stdClass::$filename in theme_file_link() (line 750 of /project/drupalwww/modules/file/file.module).
Notice: Undefined index: text_processing in _text_sanitize() (line 319 of /project/drupalwww/modules/field/modules/text/text.module).
Notice: Undefined index: text_processing in _text_sanitize() (line 319 of /project/drupalwww/modules/field/modules/text/text.module).

```

So far as I can tell there are no Errors, only `Notices` during the upgrade process. Well there is 1 error from Serial Field usage on the site -- but the project page says to ignore it. The CCK Migration shows all fields are migrated although an email and link field loose association with their original content type maybe?:

I'm so annoyed! I get alot of `Notices` but nothing is a fatal error, and the site is Editable as a logged in user so far as I can tell. But I'd love to fix search (and as a bonus get rid of the `Notices`) ...

Any pointers, thoughts, tips, prayers welcome. :D

# Answer
Ok, so I was kinda stupid and functions suck. Let me explain ...

At some point in my development of a D7 theme for my site upgrade I created a function:

```
function MYTHEME_preprocess_search_result(...) { ...}

```

to theme search results. It wasn't working right so I commented out it's body:

```
function MYTHEME_preprocess_search_result($vars) {
  #dpm($vars);
  #dpm($vars['info']);
  #unset($vars['info']);
}

```

But in my function above I'm missing a Pass-By-Reference operator on the `$vars` parameter. The proper function signature is:

```
function MYTHEME_preprocess_search_result(&$vars) { /* ... */ }

```

By merely commenting out the body of the function I left the function itself consume `$vars` and never return any `results` (due to the pass by reference operator missing) thus causing every search to say "No search results found" -- but not raise any errors.

Note:

* I saw my error after I used Xdebug and some targeted breakpoints to track the results in functionn `search_view` for example from a search form HTTP `POST`.
* I say functions suck because if this was an Object Oriented method then an IDE would be able to say the signature was erroneous; relying on `hook` functions created from macros I think is kinda silly.
* Maybe there were other ways to check this like examine the previous Git commit, but to me this type of bug is really really hard to track.
> 0 votes

---
Tags: 7, upgrading
---


# Question
Title: How to add a different specific image for each page in a region?
I want to have a **different specific** image on every page in the same region for each. I don't want to have to create separate blocks for each one. Is there an easier way? I will be getting the images from the directory.

Thanks

# Answer
> 3 votes
I assume that you have a content type which contains the field image and that image field have to displayed randomly in different pages. If so the solution would be

* Create a **block** view and add the content type as criteria and the `field:image`
* *Remove all sort criteria* and just add `Global: Random` as a sort criteria
* specify only one content should be displayed in Pager option

That's it. Now you can render it and it will randomly display the image in each page

# Answer
> 0 votes
Try the Random Image Block module.

> This Drupal 7.x Random Image Block module displays random images taken from a specified directory. It obtains its list of images to display by requiring a php file (imageList.php) which defines one function which returns a keyed-array of keyed-arrays. This random image block is not cached so a new image is displayed for each hit to the website.

---
Tags: blocks, media, theming
---


title: How to run custom code on rollback?

text:
# Question
Title: How to run custom code on rollback?
I have write a migration class to enter the value in custom table. But I want to know that how to rollback custom table entry.

I used :

```
public function complete($entity, stdClass $row) {
  // db_insert in my custom table
}

```

I want to rollback the above changes. For this I tried the completeRollback method below but it is not working.

```
public function completeRollback($entity_id) {
  dsm($entity_id);
}

```

# Answer
> 1 votes
What I just did for the solutions is, I set the variable in `complete` function as like :

```
public function complete($entity, stdClass $row) {
  $migrated_variable = variable_get('migrated_variable', array());
  $migrated_variable[] = $entity->nid;
  variable_set('migrated_variable', $migrated_variable);
}

```

And used in `postRollback` function :

```
  public function postRollback() {
    parent::postRollback();
    $migrated_variable = variable_get('migrated_variable', array());
    foreach ($migrated_variable as $nid) {
      db_delete('custom_table')
        ->condition('nid', $nid)
        ->execute();
    }
    variable_del('migrated_variable');
  }

```

# Answer
> 1 votes
You want to use prepareRollback() because at that point the thing that you are rolling back has not been removed yet.

```
public function prepareRollback($entity_id) {
  parent::prepareRollback();
  // Code to execute before an entity has been rolled back
}

```

Take a look at this guide for more info.

---
Tags: 7, migrations
---


# Question
Title: State field in Civicrm profile display as digit
I'm using D7, with CiviCRM 4.4.6. I had use civicrm to create a profile, for user to enter and edit their billing address in their account.

The country, displaying well as "Malaysia", but the state field is displaying as digit, "07".

Is there any way that I can display the state name, just like the selected name in drop down when editing state field?

# Answer
Check the table:

civicrm\_state\_province

specifically the column abbreviation for malaysia. If i had to guess, all the abbreviations are numeric and hence u r seeing numbers.

You can use PHPMyAdmin to find the relevant rows for malaysia. Your short term fix will be to populate the right values. Would be even better for you to submit a PR against civi-core so that changes get incorporated into future versions
> 4 votes

# Answer
'Administer \> Localization \> Address Settings' provide display format in terms of token, that we see on Contact Summary page's Address Section, not for profile usage.

Profile is being composed of fields, so when we view/edit a profile those field(s) got displayed in freezed or desired HTML element format respectively.

As in your case it seems like there is a js break involved, because last time I encountered such problem for a drop-down where name(label) is being replaced by integer(value).

Do you have firebug installed to see if there is any error report on console, which might help us to dig further!
> 2 votes

# Answer
I have found that by default CiviCRM displays a code or an abbreviation for state/province rather than the full name.

You can change this by going to Administer \> Localization \> Address Settings (siteroot/civicrm/admin/setting/preferences/address?reset=1)

Here you can see the tokens that are used for mailing labels and for address display. Edit the token that reads "{contact.state\_province}", changing it to "{contact.state\_province\_name}". Then the addresses should display using the full name of the state/province as stored in the database.
> 1 votes

---
Tags: civicrm
---


title: URL aliases and bidirectionality

text:
# Question
Title: URL aliases and bidirectionality
I have responsibility for a number of Drupal 6 and Drupal 7 sites and I'm curious about a difference I've noted among them.

URL aliasing is enabled on all of the sites, so that a user who navigates to 'some/readable/path' is directed to 'node/123' but continues to see the 'some/readable/path' URL alias in the browser's address bar.

On most of the sites, if the user requests 'node/123', that URL is displayed in the browser's address bar. On a few of the sites, however, the user who enters 'node/123' sees 'some/readable/path' in the address bar.

I was not aware that this sort of "bidirectional aliasing" was possible; it doesn't seem to be default behavior. Is there a module which provides this bidirectional capability? If it is default behavior, how is it enabled?

# Answer
By default in Drupal if you have node/7 with an alias of some/readable/path then a user can go to either of those URLs and it will load the page.

For SEO reasons it is considered bad to have the same page viewable at multiple URLs.

For this reason a very large number of drupal sites use the redirect module.

The redirect module forces users to always access a node from the same URL so if a user navigates to node/7 it will redirect them to the aliased URL instead.

It is likely the difference between the sites you are looking at is the redirect module.
> 3 votes

# Answer
You should use Global redirect module (not Redirect module)
> 0 votes

---
Tags: uri, path-aliases
---


# Question
Title: Best way to convert PHP block to improve site
I've just taken control over a Drupal site which the old admin used php blocks. I normally work on Joomla sites but from research and advice from others PHP blocks don't help the site in the long run.

What's the best way forward when some of the PHP blocks are set to some pages in a set area.

For example PHP block 1 is only on the Home Page's Sidebar where PHP block 2 is on Page About Us and Contact Us' Sidebar.

Just some background, This is the first Drupal site I've worked on and know only bits and pieces about Drupal apart from the general how it works and some extra details. If I've missed some research or reading which could aid in this issue which you can direct me too, this again would be great help.

# Answer
> 1 votes
Just make them a custom module!

The best start I can think of would be taking block\_example.module from the Examples for Developers project as a start. Rename it, of course, and then just define your blocks in it, the way example blocks are defined. For blocks' content - move code from where it is now to appropriate functions.

That's pretty much all, if you will have more specific question during development, ask it, too.

Understanding the hook system for Drupal modules might be a useful read, too.

---
Tags: blocks
---


title: Colorbox First Field Image Style

text:
# Question
Title: Colorbox First Field Image Style
Using colorbox in views.

Can someone explain what the functionality of the "Content Image Style for first image" is?

At first glance, I would assume that it allows me to choose an image style for all of my gallery images, and then choose a different image style for the first image, allowing the first image in the gallery to be bigger or smaller, which would be very cool.

However, when I change the image style for the first image and save, all of my images in the gallery are changed to that style.

Am i missing the point here?

# Answer
> 0 votes
Ah, I have just figured this out.

This only works when you show all multiple fields in the same row.

Changing the field to display all images in the same row, and displaying them in an unordered list sorted it right away.

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


# Question
Title: Alter a field by select list in entity form
I have a problem with Ajax and some fields in my entity form. i have a select list in my form and when i change the selected option i wanna increment another field. To explain better, i can create some entity called "modification", in this entity i have a select list with options "option 1, option 2, option3". When i will create an entity with "option 1", my field incrément will be "1", in a create a second entity with "option 1" the incrément will be "2". But if i create a third entity with "option 3" my increment will be "1".

The first thing i need to do is to collect the element list choosen automatically and do an EntityFieldQuery. When i got the count of result i just want to put the count in my field "increment".

Here is my code in hook\_form\_alter (field\_pjt\_phase is my list) :

```
$form['field_pjt_phase']['und']['#ajax'] = array(
     'event' => 'change',
     'callback' => 'projetcreate_modification_callback',
     //'wrapper' => 'field_event_1_role_replace',
);

```

And my callback :

```
function projetcreate_modification_callback($form, $form_state) {
      //$valeur = $form_state['values']['list_eltmission'];
      //My EntityQUery to take the last increment....
      //return $form['field_event_1_role'];
      var_dump($form);
}

```

And here a picture of my fields :

How can i execute the Query when i change the select list ? How to put the result of my coult entityquery in my second field ?

Thanks for your help.

# Answer
> 0 votes
* In your form alter add some code to check the form state like below to alter the text field value

```
if (!empty($form_state['values']['field_pjt_phase'])) {
    $field_val = $form_state['values']['field_pjt_phase'];

    // write dynamic query to get the count of the particular field with $field_val  as a condition
    $form['replace_textfield']['#value'] = $count;
  }

```
* Modify your Ajax callback by adding just `return $form['replace_textfield'];`

# Answer
> 0 votes
A good place to start is the aJax example module, and specifically the dependant example.

In that example, the seconds list is updated when the first list is changed, and it's value it updated according to its helper function `_ajax_example_get_second_dropdown_options($selected)` which is passed the value of the first list.

You could do something similar except use a simple text field for the second field but place the helper function on default value or value :

```
'#default_value' => _ajax_myentityfieldquery($selected),

```

and in the helper `_ajax_myentityfieldquery` return the result of your EntityFieldQuery function.

---
Tags: entities, ajax
---


# Question
Title: How can I implement connected jcarousel views?
I know drupal has jcarousel and views slideshow modules and work with each of them some times, I want to create something like this link ( images list below with carousel and when click on each one the big image changed), I know I can create a slide show that thumbnail image be below of big image and when click on them the big image changed (but this is not carousel, it means all images listed below big image without next and prev ), **Anybody has idea how can I implement `connected-carousels` in views?**

# Answer
> 1 votes
You can use the Views Slideshow JCarousel module, it is a combination of jcarousel and slideshow modules.

# Answer
> 1 votes
You need Views Slideshow JCarousel which provides the same functionality. It will add jcarousel pager in slideshow settings. ;)

---
Tags: views
---


# Question
Title: Pages with embedded views - a good aproximation?
I have a view with a listing of nodes. I want to create a page which contains the view as a block and lots of others features. I have followed this approach, but it seems to me that it is a little clumsy and there are better ones:

1) I have created a new type of content, with no fields. 2) I have created a new node of that content. 3) In the template.tpl.php I have made a suggestion for that type of content, to load a specific page--type-of-content.tpl.php page. 4) In that page I embed (php) my view and all the other features.

Is there a more straighforward method? This one works, but it seems rather convoluted.

Maybe creating the view as Page and altering the page? How can I do that?

# Answer
> 0 votes
You better use Panles Module to display everything in a single page and It allows you create complex layouts

> The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.

---
Tags: views
---


title: Background Image on pages

text:
# Question
Title: Background Image on pages
I want to display the content of a page in the manner as present in the image below:

Are any module present for this?

# Answer
> 0 votes
As said in other answers you can do that by theming. If you want to go for modules. Then these are for you.

Background Images

> Background images is a collection of modules that allows users to add background images to html elements on pages of the site

Background Images Formatter

> This module provides an image formatter who allows you to set an image in background of a div. The images are from a field of an entity and not from a configuration page or sth else, so it's very easy to setup and manage.
>
> **Use cases**
>
> 1. You want to display a image on the back of a div when viewing a particular node.
> 2. You want to display a random image on the back of a div on the frontpage only. This can be done using Views. Create a block, select the "Background Image" formatter for your image field, save, place the block, boom, you're done.

---
Tags: entities
---


# Question
Title: Customising the print stylesheet for the print module
I Would like to customise the http://drupal.org/project/print style sheet.

In the readme file it says: - To modify the template of printer friendly pages, simply edit the print.tpl.php or the css/print.css files.

Re: css/print.css Does it refer to the print.css inside the print module or inside my theme? If inside the module, wouldn't this make the maintenance difficult when the module needs updating?

# Answer
> 1 votes
Though I haven't worked with print module but as per Drupal structure, if you have to override any CSS file(in your case print.css) of some module, you can simply write your style in your own CSS file which stay in your theme directory. But if you want to use the same file & keep your styling separate then simply cut that from the module directory & paste in your theme directory...mention the CSS file in your INFO of theme...and extend it as much as you want...

Don't forget to clear your cache after you do cut/paste & done with INFO file edit..

In same way...you can copy your print.tpl.php file from the module folder & paste in your theme directory(no need to mention tpl in INFO file)...& then you can do as much editing as you want to have custom look...clear your cache in this case too..

I hope this will solve your worry about maintenance as you will get this file in your theme folder itself...

# Answer
> 2 votes
Don't edit directly your print.css file, because when you update the module, this will erase your edits

You have to copy the print.css file on your own theme and then indicate the link to this file in the module admin panel : /admin/config/user-interface/print/common

As an alternative you can also copy the print.tpl.php on your theme template dir if you want to add/remove some html content

---
Tags: theming
---


# Question
Title: How to add delete link for imported content type
For the content type which is imported by feature, there is no delete link for it, but we can delete them by going to the url `/admin/structure/types/manage/YOUR_CONTENT_TYPE/delete`

My question is how to make the delete link also available for the imported content type?

# Answer
> 1 votes
Although I am agains editing db directly, the simplest solution would be do edit table in your database.

find 'node\_type' table and under 'custom', for your content type, change 0 to 1.

---
Tags: 7, nodes, features
---


# Question
Title: Alias URL not changing when switching language in a View
I have a content node in 2 languages. When I use the language switcher while displaying the English content:

www.example.com/en/content/Article-on-relativity

it displays correctly the translated content in Spanish in this URL

www.example.com/es/content/Articulo-sobre-relatividad

However, when I include the contents filtered in a View, the language switcher only swiths the first part of the URL, but not the alias URL of the content itself, displaying Not Found

www.example.com/en/myView/Article-on-relativity

changes to

www.example.com/es/miVista/Article-on-relativity

instead of the desired

www.example.com/es/miVista/Articulo-sobre-relatividad

Thanks!!!

# Answer
An alternative would be to use i18n\_page\_views module - it is a display plugin that installs an item labeled `i18n page` into the **+Add** (display) button menu. It's like a `page` display extended by fields for entering a path for each enabled language.

While it does not offer any tool to convert existing displays into i18\_page type, it's quite easy to do that manually - just export your existing view(s), change the type of the display in a notepad and re-import w/override.

Regretfully, the module does not offer UI for creating translated menu items - this also has to be done manually.

At any rate, it's advisable to bind all translation paths (created manually as jdu suggested, or created automatically) into a translation path set (`admin/config/regional/i18n_translation/path/add`). I found that without it the `i18n_get_path_translations` function worked whimsically.
> 0 votes

---
Tags: path-aliases
---


# Question
Title: Passing PHP filtered arguments to Panel and View Pane
I have been able to pass URL parameters to a Panel and from there to a View Pane inside the Panel. However, I must pre-proccess the URL data with PHP. I have only been able to use Visibility rules with PHP in the View Pane but cannot manage to insert the PHP code in order to pass the specific PHP-modified values.

# Answer
By far the best way to do this is to provide your own context.

See What are Ctools plugin (content type, access, etc), and how does one create them? for how ctools plugins work, and adapt one of the examples to a context plugin instead.

That way you can decide what data is passed into Panels, and on to the individual panes in a safe manner.
> 1 votes

---
Tags: panels
---


title: Programmatically Updating Taxonomy Term

text:
# Question
Title: Programmatically Updating Taxonomy Term
I'm looking for a better way to update a set of taxonomy terms. It's currently causing cron to hang which slows down the site substantially.

```
    //Look through all of the stocks
    foreach ($terms_data as $symbol => $data) {
        //Check to see if term exists in the default vocabulary
        $matching_terms = taxonomy_get_term_by_name($symbol, __DEFAULT_VOCAB_MACHINE_NAME);

        //Loop through existing term(s)
        foreach ($matching_terms as $term) {
            //Load the new vocab term
            $new_term_data = taxonomy_term_load($term->tid);
            foreach ($data as $k => $v) {
                //Add in the new data
                $field_name = substr("field_".$k, 0, 31);
                $new_term_data->{"$field_name"}['und'][0]['value'] = $v;
            }
            taxonomy_term_save($new_term_data);
        }
    } //endforeach

```

The only way I could figure out how to get it to work was to:

1. Find the term that matches the $symbol variable
2. Loop through the matching term (1 term)
3. Create a new term
4. Update the exact fields
5. Save overtop of the old term

I know there has to be a better way to do this. Any ideas? **Thanks in advance!**

# Answer
For those of you interested: the bottleneck is in the *taxonomy\_term\_save()* function.

Following the trail, it led me to the *field\_sql\_storage* module (in core) which deletes an existing row and then inserts it. It should really use the built in DB Driver functionality and UPSERT instead of deleting and then inserting.

Working issues (for D8 only):

As of writing this, no patches have been applied yet. Updating large sets of taxonomy terms will lock up your DB.
> 2 votes

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


# Question
Title: How do I have views exposed filter results in separate block?
I know how to expose the Views exposed form on a block but what I would like is for the *results* from the exposed filter be shown as a separate block.

For example:

User will go to www.example.com/search\_names On this page they will see an exposed filter where they can enter a name and hit Apply After the user clicks Apply the *results* are shown in a *different* block.

Thanks for any help.

---

I'm thinking that I may be missing a step in the process. Here are the steps I am taking and the order I am doing them:

1. Add New View and click on CREATE BLOCK on the Add New View page. (Both have display format of GRID)
2. I add my fields that I want to show in the filter result.
3. I add my Filter Critea and choose "Expose this filter to visitors, to allow them to change it "
4. I click on Advanced and under Expose Form In Block I choose YES.
5. Under Exposed Form Style I choose Input required.
6. Under Use Ajax I choose Yes.
7. At this point, in the Preview section I no longer see my Filter Critea.
8. I save my View.
9. I now go to Structure then Blocks and can see 2 new blocks under Disabled: **Exposed form: view\_name-page** and **View: view\_name**
10. I *assume* that the one starting in **Exposed form** is the Filter Critea (where the user can put in the search paramater) and the one starting in **View** will be where the results of the Filter will be shown.
11. I place the **Exposed Form** block in the Content area of my theme **and** under Pages I input the node where I want this block to ONLY appear in. (In my case node/109).
12. I go back to the Blocks page and then place the **View** in the Content Area of my them **and** under Pages I input a **different** node where the results will be shown. The reason I have a different node is because on this node I have text that pertains to the filtered result.

I go to the node where I have the Exposed Form (node/109) and see the Filter Request. I type what I am searching for and hit apply. The results IS NOT appearing under the node where I placed the **View** block. Why is this?

Thanks for any help.

# Answer
This has worked for me:

* Make a View `Page` with the fields, filters and exposed filters you want. Make the view work with exposed fields in the Views Admin UI. In the view settings assign a `page url`.
* When done with the above step, click the `Exposed Form` block in the advanced view settings (make a block of the exposed filters).
* Then goto the Admin Blocks UI for your drupal site and place the block on whatever URL and theme Region you want. I placed my exposed form block on a Panel page.

When the filter form is used, it `POSTS` to the Views page URL within your view. You can't just make views block(s) for the display and exposed filter form(s). A block does not know from within Views where the `<form action="SOME_URL_HERE" method="POST" />` url of the form should post to.

# **For example, the exposed form on some page**

# **The result of submitting the form**
> 2 votes

# Answer
Assuming Drupal 7.x and Views 3.x here.

Exposed filters separated into blocks exist as an option for Views *Page* displays. To separate exposed filters for a *Block* display, look at using the Views Block Exposed Filter Blocks module.

Via this method, your `search_names` callback could be generated by the same or another view, or any other module, and you would load both the "Exposed form" block and the "View" block on that path via the blocks admin page.

Note though that there is currently a dependency on AJAX for the operation of this filter; you'll need to set "Use AJAX: Yes" in the block.
> 0 votes

---
Tags: views
---


# Question
Title: How can I have the table headers repeat throughout the view results for every X results?
I have a view that has a lot of columns with numbers in it and about 200 records in it. As I view the results and scroll down, I forget what each column's title is. Is there a module or other way to have views include the table headers ?

# Answer
> 1 votes
Assuming that you are using the display style type of table in your view, you can set the checkbox for: *Enable Drupal style "sticky" table headers (Javascript)*

This will freeze the headers and allow the table data to scroll.

---
Tags: views
---


title: Dynamically Alter Node Edit Tab Link

text:
# Question
Title: Dynamically Alter Node Edit Tab Link
I would like to all the href of the edit tab link on several nodes.

IOW: instead of

example.com/node/%/edit

I would like to substitute my dynamically created link

example.com/products/$myproductid/edit

My first stab at this (just to see if I understood the wild cards):

```
function jch_utilities_menu_alter(&$items) {
  $items['node/%node/edit']['title'] = '1234';
}

```

...and this fires, BUT I don't understand how to pass the URL I want dynamically to it.

What I want to do is pass a variable from the node (a field variable) to that link.

I see that there is a page callback member of the array but that seems to call the node\_edit page... which is over my head. I can't find a simple clear example of how to do this without a -lot- of study.

Is there no way to simply -force- a link href as one could do with jQuery?

TIA.

# Answer
You can use a module call Sub Path Auto

here is a help video with an example that should work for you.

Module description :

> For example, if user/1 is aliased to users/admin, this module rewrites the link to the user contact page user/1/contact to use the aliased URL users/admin/contact instead. This also includes Views URLs taking a node as argument (e.g. node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal non-administrative URLs.
> 0 votes

---
Tags: nodes, routes
---


# Question
Title: Clear example on how to use #theme for form API
I cannot find a good example of how to accomplish custom theming on a field level within a form:

```
$form['test_2'] = array(
  '#type' => 'textfield',
  '#title' => t('Test Field #2'),
  '#required' => true,
  '#description' => t('This is a test field which we hook into.'),

  '#theme' => 'custom_func'
);

```

Inside my template.php I have:

```
function MYTHEME_theme() {
    return array(
      'custom_func' => array(
        'render element' => ??? // WTF goes here???
      )
    );
}

function MYTHEME_custom_func($variables) {
  return 'Something';
}

```

This code obviously does not work...what am I missing?

# Answer
You're so close...the name of the render element is arbitrary, it's just a name so you can pick it up at the other end. Or, put more eloquently:

> The name of the renderable element or element tree to pass to the theme function. This name is used as the name of the variable that holds the renderable element or tree in preprocess and process functions.

So:

```
function MYTHEME_theme() {
  return array(
    'custom_func' => array(
      'render element' => 'my_element',
    ),
  );
}

function MYTHEME_custom_func($variables) {
  $element = $variables['my_element'];

  // Use the values in the $element render array to build markup.

  return $element;
}

```
> 1 votes

---
Tags: theming
---


# Question
Title: custom block menu path returns json Ok, but a 404 status header
I created a custom path via hook\_menu with a page callback to a function that prints json.

It all works in the sense that requesting: http://cms.tripchi.com/tripchi/getme returns my JSON, but the header says it's 404 which is throwing off everything in the app. This only returns the 404 status on the client's godaddy server (PHP Version 5.4.19 w/ CGI/FastCGI), but returns 200/Ok on my local PHP Version 5.3.5 w/ Apache 2.0 Handler. All Drupal configurations and databases are equal.

**hook\_menu**

```
function tripchi_menu() {
    return array(
        'tripchi/getme' => array(
            'title' => 'My Profile',
            'description' => 'mobile test for user status and object',
            'access callback' => 'user_access',
            'access arguments' => array('access content'),
            'page callback' => 'tripchi_getme')
    );
}

```

**callback function**

```
function tripchi_getme(){
    $user = $GLOBALS['user'];
    $json = array();
    // ... a bunch of stuff to construct a special array;
    drupal_add_http_header('Status', 'Ok');
    drupal_add_http_header('Access-Control-Allow-Origin', '*');
    http_response_code(200);
    //echo json_encode($json);
    drupal_json_output($json);
    drupal_exit();
    //die();
    // i've tried all combinations of commenting/uncomming the above...
}

```

below screenshot of the requests locally (right) and remotely (left):

why does this always return 404 but also give me my perfectly json encoded data?

# Answer
> 1 votes
First of all, for JSON output use drupal\_json\_output as a `delivery callback` in your menu. It will make thinks much easier:

```
function tripchi_menu() {
    return array(
        'tripchi/getme' => array(
            'title' => 'My Profile',
            'description' => 'mobile test for user status and object',
            'access callback' => 'user_access',
            'access arguments' => array('access content'),
            'page callback' => 'tripchi_getme',
            'delivery callback' => 'drupal_json_output'
         ),
    );
}

```

Then in your menu callback just return array. You don't need any other fancy stuff. I also faced `404` issue, but with this solution AND explicitly set response code `200` everything worked fine.

```
function tripchi_getme(){
    global $user;
    $json = array();
    // ... a bunch of stuff to construct a special array;

    // Only this was needed to make the stuff work.
    http_response_code(200);

    return $json;
}

```

I couldn't tell if the cause of my trouble was drupal or apache or both, but this certainly helped. Note that `Access-Control-Allow-Origin` was not needed to make this work (and I didn't plan to use cross domain calls either).

# Answer
> 0 votes
Tried code below. Works fine. Did you check if the user you're using has 'access content' permission?

```
... hook_menu ...
  $items['tripchi/getme'] = array(
    'title' => 'My Profile',
    'access arguments' => array('access content'),
    'page callback' => 'tripchi_getme',
  );

return $items;
}

`function tripchi_getme(){
  $json = array();
  // ... a bunch of stuff to construct a special array;
  drupal_add_http_header('Access-Control-Allow-Origin', '*');
  drupal_json_output($json);
}`

```

# Answer
> 0 votes
for the record, i ended up giving up on Blocks and moved this whole function under Services which already replies in JSON and seems to handle access / reponse codes properly.

---
Tags: 7, http-request
---