# Question
Title: Custom validate exposed filter on a view
I have a view with a single exposed taxonomy field that requires the user to click apply before any results are shown.

The options in the list appear like this

* Please Select (All label overridden with form alter, also the default option)
* option 1
* option 2

if the user clicks apply when please select field is highlighted I would like to show an error message rather than all of the results I have tried the following.

Form:

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

```

Function:

```
function MY_MODULE_forms_claims_validate(&$form, &$form_state) {
  if($form_state['values']['user_category'] == 'All') {
    // $form_state['values']['user_category'] = 0;
    form_set_error('user_category', 'please enter a value');
  }
}

```

It does set a form error message but also throws the follwoing warning, it also does this on the first page load which I don't want it to do either.

**Notice: Undefined index: nid in views\_handler\_field\_term\_node\_tid-\>pre\_render()**

It throws this error the first time the page is loaded which is a

# Answer
Another approach is to use `hook_form_FORM_ID_alter()` like other answers suggest, but to put custom validation before the default validation callback of views. By this way you can stop to step over to the second validation callback if validation fails, otherwise validation continues to process.. Example:

```
function MY_THEME_OR_MODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-MY_VIEWS_NAME_MY_VIEWS_DISPLAY') {
    array_unshift($form['#validate'], 'my_custom_validation_callback');
  }
}

function my_custom_validation_callback($form, &$form_state) {
  if(/* CONDITION */) {
    form_set_error('user_category', 'please enter a value');
  }
}

```
> 6 votes

# Answer
If you are using Drupal 7, I'd leverage the Form API's #states functionality and only allow the `(APPLY)` to appear when you've selected something in your exposed filter.

For a quick example, I just threw together a View that exposes the content type...

...and then a quick form\_alter() along these lines...

```
function MODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id=='views_exposed_form') { // obviously you'll probably need to be more specific :)
    // drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>'); // uncomment to see what you have to work with
    $form['type']['#options']['All']='Please Select';
    $form['type']['#description']=t('You must select a type before continuing.');
    $form['submit']['#states']=array(
      'enabled' =>  array(':input[name="type"]' => array('!value' => 'All')), // enable this when we aren't selecting "All" for our type
      'visible' =>  array(':input[name="type"]' => array('!value' => 'All')), // show it when we aren't selecting "All" as well
      // 'disabled' => array(':input[name="type"]' => array('value'  => 'All')), // you don't really need this one or the next one but include them
      // 'hidden' =>   array(':input[name="type"]' => array('value'  => 'All')), // for completeness or if your site does need them (mine didn't)
    );
  }

}

```

which, together, produces on the first page load:

and when a type has been selected:

thus allowing your users to look at the View.

Obviously, for your View, you'll have to change the `'type'` to your taxonomy field as well as the `name=` to the correct name, too, but the broad strokes are here.
> 2 votes

# Answer
You can use hook\_form\_alter() to attach a custom #validate callback:

```
function my_module_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);
  if ($form_id == 'my_exposed_form') {
    $form['#validate'][] = 'my_custom_validate';
  }
}

function my_custom_validate($form, &$form_state) {
  // Do custom validation here...
  // If there was a problem...
  form_set_error('my_taxonomy_exposed_field', t('Something bad happened!'));
}

```

Alternatively, you may want to overwrite the #validate handler, rather than appending your validate handler to it, if the default handler is causing problems.

Also, on your exposed filter, check out the different 'operator' settings as a way to help prevent all results from being displayed if nothing is selected.
> 0 votes

---
Tags: views, forms
---


# Question
Title: Issue with adding content to a content type
I am developing a Drupal 7 website. My site is in its final stage. All of sudden according to the clients requirement I need to add a new content type to the site. The content type is added successfully, now when I am trying to add content to the newly added content type it's not showing in **Add Content**. I don't even have the clue when this issue initiated. Please help.

# Answer
> 0 votes
That page is tied to the menu system.

It loads the node/add menu item, then makes the content type links from the children of that menu item.

Go to the navigation menu (admin/structure/menu/manage/navigation) and make sure that content type is in the list under the add content menu item.

---
Tags: nodes
---


# Question
Title: How to create a squeeze page for attached files under Drupal 7?
I have a content type set up in my Drupal 7 site which has an attached file. As it currently stands, this file can be freely downloaded without requiring a user account.

I do not want to require users to create an account on this site, but I would like to set up a 'squeeze page' for the newsletter/mailing list. That is, when someone decides to download the file, I'd like to present a dialog or screen a bit like this:

> Enter your email here to sign up for our email newsletter:
>
> \[***_*\__*_*_**\] \[Sign up and Download\]
>
> OR
>
> \[No thanks, I'd just like the file\]

I found two modules which would have worked if I were using Drupal 6 - Webform Protected Downloads and Squeeze Page, but no equivalents for Drupal 7. I was considering using the Custom Formatters module and a light box/dialog of some sort to jury rig it, but then I'd still need to code something to save the emails out again.

Is there a more elegant solution out there for this requirement? I am capable of coding new modules myself if that's the only option, but the less new code I need to write for this the better. Perhaps there might a module or combination of modules which comes close, which I could then tweak or modify?

Thanks in advance!

# Answer
There are a number of modules out there and I assume you found them, your particular implementation will affect which suits you, but for D6 or D7 take a look at the Comparison of file download gateway and tracking modules.

I have found each of these to be too specific and limiting in some or other way and have resorted to using webform and some custom coding.
> 1 votes

---
Tags: 7, forms, files
---


# Question
Title: When saving an updated node, does the update operation clear all caches?
Just want to confirm when a node is updated, the update operation clears the complete cache table or the updated node related cache contents. Is this right?

# Answer
There is only one line about clearing cache in `node_save()`:

```
// Clear the static loading cache.
entity_get_controller('node')->resetCache(array($node->nid));

```

It only resets entity-related cache. Caches related to another nodes, caches like boost and so on are left untouched, unless specifically cleared by other module's actions in node or entity saving hooks.
> 3 votes

# Answer
**Short Answer : *Yes, it does*.**

**Long Answer :** Function `node_form_submit` from the file `node_form_submit` also gets called when you edit or add a node. The last line in this function is `cache_clear_all`. This function deletes all the entries form page and block cache bins and prunes the other cache bins.

The reason that `cache_clear_all` is moved from `node_save()` to `node_form_submit` is so that you could just change the form submit handler for this form and change the cache clearing logic if you want to.

A suggested approach would be to increase Minimum Cache Lifetime value from the performance page and then use the Expires which helps you handle your cache clearning(Invalidation) logic.

Detailed Explanation : Whenever I edit/update a node all the page caches for anonymous user are lost
> 2 votes

---
Tags: caching
---


title: Upload images between texts in CKeditor

text:
# Question
Title: Upload images between texts in CKeditor
I have a user manual in my site using Drupal 6, Which was created using book module. I use CKEditor as the editor and I want to upload images between the paragraphs. CKeditor asks for url to upload images.

# Answer
> 0 votes
Insert is must for easy insertion of image links in the text of node. You case insert using Colorbox or lightbox2. It can also insert using image styles you may have defined.

Make sure you do the screencast mentioned in the Insert module page.

# Answer
> 0 votes
If I am understanding clearly your question, then you want to upload images using *ckeditor*.

You can use IMCE module which provide the functionality to upload image.

> IMCE is an image/file uploader and browser that supports personal directories and quota.

# Answer
> 0 votes
it is very simple with Wysiwyg should just add this module IMCE Wysiwyg bridge go to admin/config/content/wysiwyg/profile/ and edit for example FULL HTML then check IMCE image in buttons and plugins

---
Tags: media, wysiwyg
---


# Question
Title: How can I add background music to an existing Drupal 7 website?
I have a nice little website built with Drupal 7. It's very basic, nothing crazy going on.

The client is demanding there be background music playing on the site. I have pleaded with them not to do this, but they are insistent and they are also signing the checks. :)

What is the best way to add background music to an existing Drupal 7 site that won't stop playing between pages? For any given solution what are the consequences to search engine friendliness and impact in general to the structure of Drupal?

Looking only for solutions to the music problem as not having music on the site isn't an option here.

# Answer
I'm looking at doing the same thing for a band's website where the music can keep playing even when switching pages. AJAX is definitely the way to go here.

Check out the pjax for Drupal module.

> pjax is a jQuery plugin that loads new content into the current page without a full page load. This is usually quicker and smoother than a full page reload, because Drupal only has to deliver the main page content and not the full page – and the browser only has to redraw a smaller amount of markup.
>
> In addition to this, pjax updates the page URL with the proper page path using HTML5 pushState – not with #url-fragments that are commonly used with ajax-loaded content. It also updates the page title with the title of the loaded page. In other words, it has all of the benefits of standard page loads (permalinks, SEO), while taking advantage of partial page loads in the browser.
> 1 votes

# Answer
If you want the music to continue playing even while you go from one page to another, you'll have to make the site so that all pages are loaded with AJAX, or in frames. With regular page loading, the music will be interrupted between each page.

As far as a player to use, I haven't tried anything, but this one looks pretty good to me: http://www.cincopa.com/media-platform/services/add-music-to-website
> 0 votes

# Answer
From a Google/Search perspective, the frames idea is a bad one. Has the client also considered people accessing via Mobile platform? Also an issue.

I hate pop-unders, but in this case, a pop under spawning the player might also be the way to go...then do mobile agent detection, and kill the spawn for that platform.
> 0 votes

# Answer
This is an old question but some may still stumble upon it so here is the solution:

Combine two modules, https://drupal.org/project/ajax\_pages and https://drupal.org/project/background\_audio

This allows a user to browse the site (visiting different pages) and have an audio file continuously playing (without interruption).

In essence you are using ajax to have constant regions which do not change when a page is loaded.
> 0 votes

---
Tags: 7
---


title: How to completely replace a view query?

text:
# Question
Title: How to completely replace a view query?
I have a view whose query I want to completely change. I want to change the select statement, the joins and the where clause. the original query is this:

```
SELECT node.nid AS nid, node.title AS node_title, field_data_field_location.field_location_tid AS field_data_field_location_field_location_tid, node.created AS node_created, 'node' AS field_data_field_location_node_entity_type, 'node' AS field_data_field_longtext_node_entity_type
FROM
{node} node
LEFT JOIN {field_data_field_entity_type} field_data_field_entity_type ON node.nid = field_data_field_entity_type.entity_id AND (field_data_field_entity_type.entity_type = :views_join_condition_0 AND field_data_field_entity_type.deleted = :views_join_condition_1)
LEFT JOIN {field_data_field_location} field_data_field_location ON node.nid = field_data_field_location.entity_id AND (field_data_field_location.entity_type = :views_join_condition_2 AND field_data_field_location.deleted = :views_join_condition_3)
LEFT JOIN {node} node_1 ON node.nid = node_1.nid AND (node_1.language = 'bg' AND node.tnid != node.nid AND node.language = 'en')
WHERE (( (field_data_field_entity_type.field_entity_type_tid = :field_data_field_entity_type_field_entity_type_tid ) AND (field_data_field_location.field_location_tid = :field_data_field_location_field_location_tid ) )AND(( (node.status = :db_condition_placeholder_4) AND (node.type IN  (:db_condition_placeholder_5)) AND (node.language IN  (:db_condition_placeholder_6, :db_condition_placeholder_7)) )))
ORDER BY field_data_field_location_field_location_tid ASC, node_title ASC, node_created DESC

```

and the new query is this:

```
select CASE when b.node_title is not null then b.nid else a.nid end as nid,
CASE when b.node_title is null then a.node_title else b.node_title end as node_title,
CASE when b.node_title is not null then b.field_data_field_location_field_location_tid else a.field_data_field_location_field_location_tid end as field_data_field_location_field_location_tid,
CASE when b.node_title is not null then b.node_created else a.node_created end as node_created,
'node' AS field_data_field_location_node_entity_type, 'node' AS field_data_field_longtext_node_entity_type
from
(SELECT node.tnid, node.nid AS nid, node.title AS node_title, field_data_field_location.field_location_tid AS field_data_field_location_field_location_tid, node.created AS node_created, 'node' AS field_data_field_location_node_entity_type, 'node' AS field_data_field_longtext_node_entity_type
FROM
node node
LEFT JOIN field_data_field_entity_type field_data_field_entity_type ON node.nid = field_data_field_entity_type.entity_id AND (field_data_field_entity_type.entity_type = 'node' AND field_data_field_entity_type.deleted = '0')
LEFT JOIN field_data_field_location field_data_field_location ON node.nid = field_data_field_location.entity_id AND (field_data_field_location.entity_type = 'node' AND field_data_field_location.deleted = '0')
WHERE   field_data_field_entity_type.field_entity_type_tid = '818'
AND field_data_field_location.field_location_tid = '408'
AND node.status = '1'
AND node.type IN  ('data_entity')
AND node.language = 'en') a LEFT OUTER JOIN
(SELECT node.tnid, node.nid AS nid, node.title AS node_title, field_data_field_location.field_location_tid AS field_data_field_location_field_location_tid, node.created AS node_created, 'node' AS field_data_field_location_node_entity_type, 'node' AS field_data_field_longtext_node_entity_type
FROM
node node
LEFT JOIN field_data_field_entity_type field_data_field_entity_type ON node.nid = field_data_field_entity_type.entity_id AND (field_data_field_entity_type.entity_type = 'node' AND field_data_field_entity_type.deleted = '0')
LEFT JOIN field_data_field_location field_data_field_location ON node.nid = field_data_field_location.entity_id AND (field_data_field_location.entity_type = 'node' AND field_data_field_location.deleted = '0')
WHERE   field_data_field_entity_type.field_entity_type_tid = '818'
AND field_data_field_location.field_location_tid = '408'
AND node.status = '1'
AND node.type IN  ('data_entity')
AND node.language = 'bg') b
ON a.nid= b.tnid

```

I tried with views\_pre\_execute hook and with query\_alter view with no luck... The first attemt is using https://drupal.org/node/409808 $view-\>build\_info\['query'\] = MY QUERY; which throws error:Call to a member function addMetaData() on a non-object

The attempt with query alter is a dissaster...I cannot make it work..

# Answer
I wasn't able to solve my problem by tampering the query. In order to solve my "language fallback" problem, I used the hook\_views\_post\_execute(&$view) and parsed the results in order to remove the nodes not needed. In more details... My query fetched the nodes in the english (default site language) and in the language selected by a UI dropdown. Then in the views\_post\_execute hook I removed what not needed.

```
switch ($view->current_display) {
    case "my_case_block":
      if ($language->language != 'en') {
        $results = $view->result;
        $parsed_results = array();
        $index = 0;
        $source_node = node_load(arg(1));
        $source_node_parent_nid = $source_node->tnid;
        foreach ($results as $result) {
          $result_node = $result->_field_data['nid']['entity'];
          if (!empty($result_node)) {
            if ($result_node->tnid == $source_node_parent_nid){
              continue;
            }
            if ($result_node->language == 'en') {
              $translations = translation_node_get_translations($result_node->nid);
              if (!empty($translations) && count($translations) > 0 && array_key_exists($language->language, $translations)){
                continue;
              }
            }
          }
          $parsed_results[$index] = $result;
          $index++;
        }
        // HERE I REPLACE THE RESULT with the parsed one
        $view->result = $parsed_results;
      }
      break;
  }

```

Thank you all for your help and suggestions
> 0 votes

# Answer
As the others say you can use `hook_views_query_alter` in your custom module and this is Sample of using it :

```
function alterform_views_query_alter(&$view, &$query) {
  switch($view->name) {
    case 'myViewName':
      echo 'test test'; // test
      $query->orderby[0] = "FIELD(node.type, 'story', 'page', 'productTypeC', 'productTypeD') ASC";
      $query->orderby[1] = "node_title ASC";
      break;
  }
}

```
> 2 votes

# Answer
hook\_views\_query\_alter

Use the hook\_views\_query\_alter(&$view, &$query) to alter the present query.

> Alter the query before executing the query.
>
> This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME\_views\_api(), or the same directory as the .module file, if 'path' is unspecified.
>
> Parameters
>
> $view: The view object about to be processed.
>
> $query: An object describing the query.
> 1 votes

---
Tags: views
---


# Question
Title: How do I grant edit access on workbench to specific users?
All the users have a field, field\_country. All the content types have also a field, field\_country. I want the logged in user to be able to edit in workbench, his own content and the content added by other users of the same country. I managed the first. How can the second requirement be implemented? Which hook should I use? Is there any example?

# Answer
I solved my problem as follows: 1) Using hook\_views\_query\_alter I fetched the desired rows. With that step I was able to see in the recent content list all the rows I want but with edit link only to the ones that the logged in user has created. In order to see the edit to the rest of the rows whose author is somenone else I followed the step 2.

```
switch ($view->name) {
case "workbench_recent_content":
...
unset($query->where);
....
$where_expression = MY where statement where I filtered by content type and by a field_location field that exists on all of my content type.
 $query->add_where_expression(0, $where_expression);

```

2) I created a rule, on node save, grant edit access to the people that have a specific role and belong to a specific country. That way the edit link appeared even all the rows I wanted.
> 0 votes

---
Tags: workbench
---


# Question
Title: Display content by taxonomy term, including sub-terms
I'm looking at Drupal for the first time in a long time, with a view to using it in a project we're starting. This seems like a very simple question, but I'm struggling to find the answer.

If we have a taxonomy of website sections and associated sub-sections, like this:

```
News
    - Europe
    - America
    - etc
Products
    - Widgets
    - Doodahs
    - etc

```

If we have a menu linking to News it's easy to display content associated explicitly with that term, I'm not seeing how to include content associated with its sub-terms though. Is the conventional way of achieving this through...views?

Thanks,

Toby

**Update:** It looks like in previous versions of Drupal you could perhaps specify a term depth in your URLs. I guess this is what I'm after, but in Drupal 7

# Answer
> 0 votes
From what I can see, Views is the way to do it, using a 'Filter criteria' of 'Content: Has taxonomy terms (with depth)'. If there's a simpler way do let me know.

# Answer
> 0 votes
link- https://drupal.org/project/taxonomy\_menu\_block

Taxonomy Menu Block allows you to make blocks containing unordered lists that represent the structure of your vocabularies, creating a menu out of your taxonomies (without using Drupal's menu system). TMB combines the idea of Taxonomy menu with the workings of Menu block : Make multiple menus per vocabulary. "Split" the taxonomy into different menus. This allows, for example, the creation of one menu with only the top items (parents) of a vocabulary and another menu with only the sub-items (children). Make a menu out of a specific branch of your vocabulary only. Follow the active trail, also for nodes coupled to a term with a term reference field.

---
Tags: views, taxonomy-terms, routes
---


# Question
Title: Contact attached to every node of a particular type
I am trying to figure out how to attach one form to every node of a particular content type in Drupal.

Each node will be owned by a different user and the form will be sent to the user who created that node.

The closest I have got is with Webform and Webform Templates. However, It makes the user choose the template to use. I don't want that I want it to be set automatically and I can't see how it can be?

Any suggestions would be greatly appreciated.

# Answer
Try installing Form Block module which give you possibility to expose a form as a block. And you can configure appearance of that block on every node of a particular content type.

> To enable adding of a form to a node, select the option "Enable data entry from a block" in the admin configuration page for a given content type. Visit the block administration page and enable/configure the block for the form.
> 0 votes

---
Tags: forms, webforms
---


title: FAPI #states for multiple selections.

text:
# Question
Title: FAPI #states for multiple selections.
I've used the FAPI #states system before to show/hide conditional fields. It's great.

However, when I am trying to show a field based on another field's value, I'm running into a problem. The documentation for this only explains how to show/hide a field based on whether my independent field has a particular value. In my case, I don't care what the exact value is, but if it has multiple values selected from a select list, I'd like to show my dependent field, and hide it otherwise.

Does the FAPI #states system support this? If so, where can I find the syntax for how to use it?

# Answer
I cannot see how `#states` can meet a condition like this. The right side of the condition array always requires a literal value. In my opinion this use case requires custom JavaScript. Something like this should do it (obviously adapt the selectors etc.).

```
(function ($) {
  function update($select_element, $target) {
    var count = $('option:selected', $select_element).length;
    if (count > 1) {
      $target.show();
    }
    else {
      $target.hide();
    }
  }

  Drupal.behaviors.MYMODULE = {
    attach: function (context, settings) {
      $('#-MY-SELECT-FIELD', context).once('MYMODULE', function () {
        var $target = $('#-MY-TARGET-FIELD');
        var $select_element = $(this);

        // Update once on attach-behaviors.
        update($select_element, $target);

        // Update whenever select element changes.
        $select_element.change(function() {
          update($select_element, $target);
        });
      });
    }
  };
}(jQuery));

```
> 3 votes

# Answer
You should be able to define something like this:

```
'visible' => array(
  array(
    ':input[name="ELEMENTNAME"]' => array(
      array("value" => 'VALUE_1'),
      array("value" => 'VALUE_2'),
    ),
  ),
),

```

See this question for more details
> 3 votes

# Answer
> Does the FAPI #states system support this?

Core can't do it out of the box, but you can extend or even override it. There is great example: Extending Form API #states with regular expressions

In your case I suggest to create new state `"select_not_empty"` which will be TRUE when one or more items selected in select list.

```
(function ($) {
  Drupal.behaviors.statesModification = {
    weight: -10, // Don't forget to enable https://drupal.org/project/behavior_weights module.
    attach: function(context, settings) {
      if (Drupal.states) {
        // Custom state for select list.
        Drupal.states.Trigger.states.select_not_empty = {
          'change': function () {
            return $('option:selected', this).length ? true : false;
          }
        }
      }
    }
  }

}(jQuery));

```

Now you can use this new state as usual:

```
'#title' => t('Something selected!'),
'#type' => 'checkbox',
'#states' => array(
  'checked' => array(
    array(
      'select[name^="select"]' => array(
        'select_not_empty' => TRUE,
      ),
    ),
  ),
)

```

This method requires Behavior weights module.
> 1 votes

---
Tags: javascript
---


# Question
Title: How do I add a dynamic Facebook like button to every node of a certain content type
One very comfortable solution to that problem is provided by http://drupal.org/project/fblikebutton. Unfortunately the positioning of the button isn't flexible enough for my needs.

I want every single node of one certain content type to have a FB like button at its bottom, making the base+node-url like-able. Facebook provides some snippets for that. Since I know that loading many iframes makes the site load very slow, I'ld like to add the JavaScript snippet into the appropriate template file.

My questions now are, in what template file exactly would I inject the little snippets and how do I have to customise the url in the plugin to make it fetch the url of every single node dynamically?

# Answer
> 5 votes
Inside a `template_preprocess_node()` I have done:

```
/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $variables['full_url'] = url('node/' . $node->nid, array('absolute' => TRUE));
}

```

Then in my node.tpl.php, I have

```
<?php // http://developers.facebook.com/docs/reference/plugins/like/ ?>

<div class="fb-like" data-href="<?php print $full_url; ?>" data-send="true"
  data-layout="button_count" data-width="450" data-show-faces="false"></div>
<script>
  (function ($) {
    try {
      FB.XFBML.parse();
    } catch (e) {
      $('.fb-like').remove();
    }
  })(jQuery);
</script>

```

In my html.tpl.php, I will hardcode the JS include so that it is right after the body (so I am not at the mercy of render trees, preprocess, etc:

```
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

```

This is from a pretty specific use case on a recent site. I am not 100% sure if I tested this with multiple nodes on a single page, as the site I did this on doesn't have pages like that.

# Answer
> 1 votes
You could try: https://github.com/grizzly/jquery.facebook

```
$(document).ready(function() {
    $('.likebutton').facebook("likebutton", {
        url : "http://jquery.com",
        action : "like"
    });
});

```

Which adde a like button to every div, marked with class .likebutton

# Answer
> -1 votes
Try Facebook Like Button Module

> Rather than having to manually copy/paste the Like this on Facebook code for each piece of content you (or your users) create, this module will automatically add that code to the end of each chosen node type. You are able to add a Like button which likes a given URL (static, e.g. your homepage) or/and put a dynamic Like button on your page to like the page you are actually visiting.

Also there is Facebook Share

> The Facebook Share module enables Drupal site administrators to add a Facebook Share button to selected content type nodes in their website(s).

---
Tags: 7, nodes, javascript, social-network
---


title: Show link based on role

text:
# Question
Title: Show link based on role
In page.tpl.php I'm displaying a link for user page. For an example:

```
<?php echo l(t("My offers"), 'user/' . $user->uid . '/offers'); ?>

```

So when a user clicks on the link it goes to user/uid/offers.

Now I want to show this link only based on a role. Let's say we have a role "Seller" that has unique ID 5 in the database. How can I set

```
<?php echo l(t("My offers"), 'user/' . $user->uid . '/offers'); ?>

```

to be visible only when a user has a role "Seller"?-

# Answer
> 2 votes
I've got answer from drupal.org and this is the right solution:

```
<?php
if(isset($user->roles[5]))
{
  echo l(t("My offers"), 'user/' . $user->uid . '/offers');
}

```

# Answer
> 1 votes
For a non-coding method, you can create a block or for more control over the content a Views block that shows for certain roles.

# Answer
> 0 votes
you can do this in following way say your seller roll machine\_name is **profile\_seller** then,

\<

```
?php
if($user->**profile_seller** == "yes")
{
  echo l(t("My offers"), 'user/' . $user->uid . '/offers');
}
?>

```

Let us know if it works

---
Tags: users
---


# Question
Title: Upgrade Commerce Kickstart 1 site with drush
From http://www.drupalcommerce.org/blog/9072/updating-commerce-kickstart-2 I learned that it's possible to upgrade a CK2 site using drush.

Is it possible to do a minor upgrade od CK1 using `drush dl --select commerce_kickstart` and selecting the proper version? I tried and failed.

# Answer
According to this page http://www.drupalcommerce.org/commerce-kickstart-2/install you should use Drush 8.x-6.x for an upgrade.
> -1 votes

---
Tags: drush, commerce
---


# Question
Title: Drupal 6 Image Resize Thumbnail Maintain Aspect Ratio
We have a content type which has an original image. There is also a resized version which is not a thumbnail, but not the original size either which is used on a drill down page.

What is the best way to maintain the image aspect ratio for this drilled down page image? I've found some functions, but is there a module or best practice way to do this?

# Answer
> 0 votes
You want the ImageCache module https://drupal.org/project/imagecache there are also additional actions if you require them https://drupal.org/project/imagecache\_actions

---
Tags: media
---


# Question
Title: How to display User from Access Log in Views
The statistics module documentation says that user name is logged in the Access Log: "This access log is used to store data about every page accessed, such as the remote host's IP address, where they came from (referrer), what node they've viewed, **and their user name**. "

I have enabled statistics Acces Log and created a view which shows Access Log. Available fields are:

I can't find any field related to user.

# Answer
You have to add a relationship to Users to be able to display user fields in the view.

1. Click on Add next to Relationships.
2. Check "Access log: User" then click Apply.
3. Click Add next to Fields then you should see the User fields including username.
> 2 votes

---
Tags: 7, views, nodes
---


title: Expand Addressfield Components in Views

text:
# Question
Title: Expand Addressfield Components in Views
Situation :

1. I have added few more fields in user registration form using account settings-\>manage fields. The type of the field is cck address field.
2. I created a new view as json document, and I added that field to the view as well, but the problem is its not expanding it as the way I wanted. What I mean is, I filled the user registration form address field as first name, last name, street etc etc. but I am either seeing the whole field in a single line under Address tag in json or just a tag like this `{"nodes":[{"node":{"name":"admin","field_address":"1"}}]}` but what I want is like this:

{"nodes":\[{"node":{"name":"admin","first\_name":"xyz","last\_name":"sdas","street":"ssdsf"}}\]}

Any suggestions?

# Answer
I also had the same issue with Addressfield module. There is a long discussion here regarding this issue. You can find two solution for it by the patch provided by some members.

* This one works by field formatter modification.

If you apply this patch, add the address field to a view and then you will see in the Formatter drop down all the components of the address is listed. (where before it just said Default).

* This one works by adding data by field\_view\_data.

If you apply this patch then you can add the addressfield component in the add field itself. You will have option to add by searching something like "Content:Address(COMPONENT MACHINE NAME)
> 1 votes

# Answer
Current version of Addressfield (7.x-1.0-beta5) supports displaying address components in views as separate fields.
> 2 votes

---
Tags: views, entities
---


# Question
Title: Programmatically disabling webform component - Drupal 7
According to hook\_form\_alter doc for webform, I can target the component's properties using $form\['submitted'\]\['component\_name'\], etc. This works fine for altering title, weight, description. The form structure of webform looks something like:

```
Array
(
  [#tree] => 1
  [component_email] => Array
     (
       [#type] => webform_email
       [#title] => Email
         .
         .
       [#webform_component] => Array
         (
           .
           .
           [extra] => Array
             .
             [disabled] => 0

```

Simply changing the disabled property to `true` or `1` doesn't disabled the component. I have also tried the $form\['#node'\]-\>webform path.

# Answer
I have never had luck trying to set the disabled flag via a FormsAPI hook using the array indexes. Looking at the code above, it would also seem that you are setting the incorrect 'disabled' for the form array - #disabled is what is checked during the rendering process.

But, like I said, never had much luck with it anyway. What you may end up needing to do is set the #attributes array for the form element, specifically identifying the disabled property as in the html element tag:

```
<input type='text' disabled />
// becomes
$form['element']['#attributes'] = array('disabled' => '1');

```

obviously with the form indexes specified as needed.
> 3 votes

---
Tags: webforms, forms
---


title: Trigger Event After Node Is Indexed

text:
# Question
Title: Trigger Event After Node Is Indexed
I have a pretty basic Drupal 7 web site with Solr search (works great!).

I would now like to perform some "work" after each node is indexed with Solr.

First I tried creating a workflow rule but there is no event for "node has been indexed". Next I looked for Solr API hooks but came up empty handed.

Should I look at adding a hook somewhere in the PHP code? If so where? Or am I overlooking a more obvious solution?

Thanks

# Answer
> 0 votes
Both Solr modules provide APIs:

But neither provide an after-node-update hook. If I had to guess I'd say it's both modules send data to Solr in batches, not one node at a time.

You might get some joy with the core `hook_node_update_index()`:

> Act on a node being indexed for searching.
>
> This hook is invoked during search indexing, after node\_load(), and after the result of node\_view() is added as $node-\>rendered to the node object.

# Answer
> 0 votes
What you probably want is the ApacheSolr hook `hook_apachesolr_index_document_build`. This gets fired when a node (or any entity type) is being processed before sending to solr. Note the 'before', but this is called for every node whenever it is being indexed.

You could exit early from your hook by doing `if ($entity_type != 'node') { return $document; }` and you can also add or modify fields being sent to solr. The ApacheSolr module processes created/updated nodes in batches (default 200) during each cron run.

---
Tags: hooks, rules, search
---


# Question
Title: How to send data like NAME[]=value via POST request and simultaneously redirect user to 3rd party server?
I'm writing a custom module which needs to send data string like this: "CODES\[\]=xxx&NAMES\[\]=xxx" via POST to 3rdparty payment gateway AND redirect user there.

I've written a form to gather data from customer, but I can't use \[\] in form fields names, Drupal reports an error (an array instead of string) and quits.

I can post all data manually via drupal\_http\_request, but it doesn't redirects browser to needed URL. If I use drupal\_goto after drupal\_http\_request, the data is lost and payment service doesn't recognize the user. If I include $request(my drupal\_http\_request)-\>result in a page, I get redirected to 404 page of my site with a non-existent URL (/order/checkout.php which has to be appended to payment server root and instead glues to my server root URL).

If I use $form\['#redirect'\] or $form\['#action'\] it posts fields names without "\[\]".

Question is, how can I append these square brackets after request is formed, but before it is sent?

Or how can I send data along with redirecting?

Will be very grateful for help, this problem is driving me nuts for a week now.

UPD My code:

```
    //a form
function mymodule_ask(&$form_state) {

 $form = array();

$form['#action'] = 'https://3rdpartysite.url/script.php';
$form['#method'] = 'post';

 $form['ORDER_PRICE[]'] = array(
   '#type' => 'textfield',
   '#title' => t('Amount'),
   '#size' => 10,
   '#required' => TRUE
 );

 $form['ORDER_PNAME[]'] = array (
   '#type' => 'radios',
   '#title' => t('Name'),
   '#options' => array('Avia' => 'Avia tickets', 'Other' => 'Other'),
   '#required' => TRUE
 );

 $form['submit'] = array (
   '#type' => 'submit',
   '#value' => t('PAY')
 );

return $form;
}

function mymodule_ask_submit {
    //in form submit function retrieving data from form values
    $requestar['ORDER_PNAME[]'] = $form_state['values']['ORDER_PNAME'];
    $requestar['ORDER_PRICE[]'] = $form_state['values']['ORDER_PRICE'] * 1.02;
    //forming an array to post
    $onestr = '';
    foreach ($requestar as $key => $value) {
    $onestr .= $key."=".$value."&";
    }
    $resstr = chop($onestr, '&');
    // and then I tried different ways

    //either creating and auto-submitting a form with needed values
    create_form($requestar); //separate function creating this form
    drupal_execute('payu_addform', $form_state);
    // but it doesn't pass drupal evaluation because of "ORDER_PRICE[]" element name

     //or via http_request
    $result = drupal_http_request('https://PAYMENT_SERVER_URL/script.php',  array('Content-Type' => 'application/x-www-form-urlencoded'), 'POST', $resstr);
    drupal_set_message($result->request);

    // but it takes me to MY_SERVER_URL/order/checkout.php?CART_ID=442bc42170616cd36dfd2246434d4210, while I need it to make to PAYMENT_SERVER_URL/order/checkout.php?bla-bla-bla
    //may be I can use $result->request in some other way? Just printing within this submit function gives nothing... But how can I pass it to make drupal take me out?

}

```

# Answer
> 1 votes
Try setting the name directly:

```
$form['order_price'] = array(
  '#type' => 'textfield',
  '#title' => t('Amount'),
  '#size' => 10,
  '#required' => TRUE,
  '#name' => 'ORDER_PRICE[]',
);

```

---
Tags: 6, redirection, forms
---


# Question
Title: how do i create a site that allows users to create "organizations?
I'm creating a site where users should be able to create organizations(groups) that other users should be able to join....a list of these orgs should be accessible by all users of the site on an "orgs" page.....whats the best way to do this? thank you very much!

# Answer
The module to do this with in Drupal would be Organic Groups https://drupal.org/project/og. It's not a trivial module though. Here's the official documentation: https://drupal.org/node/1114858.

There are some online courses available from for example Lullabot: http://drupalize.me/series/organic-groups-drupal-7 and Brian Lewis: http://modulesunraveled.com/organic-groups-7x-2x.
> 2 votes

---
Tags: organic-groups
---


title: Tagging a friend in a node

text:
# Question
Title: Tagging a friend in a node
Is it possible to create the functionality where, on creating a node, the user can tag friends to associate their friend with the node. Such as in Facebook's tag a friend in a post.

This would require a friends lookup field, which would imply that the users have already approved each other as friends (maybe using User Relationships).

So, the key thing is to provide a lookup field which searches the user's friend list, and also exposes itself to Views.

Ideally, the field would allow you to enter an email address if their friend isn't already on the site (probably asking too much, and could possibly make do with using the Invite module here).

# Answer
It is definitely possible, and some of the functionality you need already exists.

I would go the route of creating a new field widget for a standard user reference field that tackles limiting the possible list to current friends.

Have a look at user\_relationship\_views hook\_menu implementation for an example of how you would do the user lookup (in this case we're looking up relationship types but you can get the idea). I think the code for doing this with standard user fields in views is pretty straightforward as well if my memory serves me correctly. To find all the relationships with the current user look at the api docs for user\_relationships\_load().

User relationships already comes with invite module integration (invite user x with y relationship attached to the invitation). The ui isn't that stellar but I'm guessing you could squeeze it into a node form with a little work.
> 1 votes

# Answer
I've implemented it using an entityreference field.

Steps:

1. Install and enable the entityreference \+ Entityreference Views Filter modules.
2. Create the selection view.

>

The display type should be "Entity Reference."

>

The view should be field-based, with the 'Entity reference list' format. You should add the 'Entity Reference View Widget Checkbox: User' field:

>

Then add a name and picture fields.

3. Now, that you've created the ER user selection view, it's the time to add an entity reference field to the node's content type. Go to your content type's fields page and add a new entity reference field, with the 'View' widget:

>

4. Field settings: 'Target Type' should be 'User', for the 'Entity Selection' field select 'Views', and for the view select the view from step 3 (friends\_selection):

>

5. Now you get the standard CCK Field definitions page. Here select the max number of people you allow to tag (probably bigger then 1).

>

6. Now create a new node - you will see the new field.

>

7. Click on the 'add items' link inside the view field and you will get the selection popup.

>

8. Check the friends you want and click on the buttons on the bottom of the popup:
    * "Add items and close window" will select items on the current view page.
    * "Add selected items" will allow you to select more friends from the next view page.

Enjoy!
> 1 votes

---
Tags: users
---


# Question
Title: ImageBlock Module- Responsive/Fluid images
I am using the ImageBlock Module to upload/insert images into a block, which works great! However I am designing a responsive/fluid website. I have no problem with this if the image is stated in CSS, but for some reason I can not get the ImageBlock to treat the image that was uploaded as responsive/fluid.

How can the image that I uploaded to the ImageBlock I created, be responsive/fluid in a website that is designed to be fluid?

Thanks!

# Answer
Figured it out. In order to make a image that is a part of a imageblock, responsive/fluid, you need to:

1.) Use firebug to find the image block class for the imageblock. 2.) For me I added this to CSS

```
#block-imageblock-### .imageblock-image{
    width:100%;

}

```

This will make your image that you've uploaded into a ImageBlock responsive/fluid to any screen resolution
> 0 votes

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


# Question
Title: Entity Reference View Widget problem with add selective
I am using a content type which uses a field as "Views" Entity Reference View Widget. When I click "add selective" or "add .. and close" in form of this widget, it's just redirect to `http://localhost/denwer`.

How do I solve this problem?

Thank you for answer, kiamlaluno.

details of question: 1. I create a view with type display "Entity Reference View Widget" as table of taxonomy term (after create view in this view besides display name of views "Entity Reference View Widget" no more information that it use "Entity Reference View Widget" - in Format just show that it's table (grid etc..) 2. Create content type in content type create field: \- type filed "Entity Reference" \- widget "view"

after create field in description of module "Entit.. widget" says that "on the next page select your View from the dropdown" but there is no dropdown in which can choose my view (picture below)

if just click "save" created view chosen (picture below)

then i use default settings and save settings of field.

Next step - Add node of created type and here is problem: \- i see field with widget, can click add item \- then i see "widget form with created view" But if click on buttom "add selected item" - it's just go to page "/localhost /denwer" and of cause nothing add in "node add"

# Answer
I solved a very similar issue by changing the display type to "Entity Reference" (not "Entity Reference View Widget") and using using the ER Widget only for the view checkbox selection field.

Here is a detailed step-by-step guide to a solution which worked for me using the latest Drupal 7 dev version of the ER Widget module.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Trouble extracting year from date field for computed field
I have a date field, 'field\_date', from which I need to extract the year. The date format is yyyy-mm-dd, so I figured the following would do it:

```
$date = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_date')));
$year = explode("-", $date)[0];
$entity_field[0]['value'] = $year;

```

This gives me `Parse error: syntax error, unexpected '['` Am I not getting the date string correctly?

# Answer
> 3 votes
Function array dereferencing was added in PHP 5.4, you must be using an older version.

To fix:

```
$parts = explode("-", $date);
$year = $parts[0];

```

---
Tags: 7, entities
---


# Question
Title: how do i create a site that allows users to create and view events?
I'm creating a site where users should be able to create events that are accessible by all users of the site on an "events" page.....whats the best way to do this? thank you very much!

# Answer
It is very simple to do this task.

You need to create a new content type. add to it corresponding fields and set to it create/edit/delete permission for anonymous and registered users in the permissions page.

As I see, your are a newer on Drupal. I advice you to go throught the documentation to learn about Drupal, its conception and how it works.
> 1 votes

---
Tags: 7
---


# Question
Title: Having a hover or mouseover effect in views for drupal 7
I am creating a staff page for a project, and I am putting an image (suing views) that links to the staff members page. What I thought would be really cool is if when you scrolled your mouse over the image it turned into the name of the person. I am not sure at all how to do this, and after several hours of searching I need some help.

Thanks in advance.

# Answer
> 2 votes
You can do a simple thing like this:

HTML

```
<a class="person" href="#">
   <img src="" width="100" height="100">
   <span>John Doe</span>
</a>

```

CSS

```
a.person {
    border: 1px solid #ddd;
    display: block;
    height: 100px;
    overflow: hidden;
    width: 100px;
}
a.person:hover img {
    display: none;
}
a.person span {
    display: block;
    text-align: center;
    margin: 20% 0 0;
}

```

Fiddle: http://jsfiddle.net/fXnmr/

If you want fade effects etc you need to go the Javascript/jQuery route.

# Answer
> 1 votes
If you're using views I'd overwrite the image field with the code by enzipher but use tokens for the staff names so it's pulled from a 'Staff Name' field. Then use CSS and JS to do the rest of the fancy stuff.

So...

Edit your content type to add 'Staff Name' and 'Staff Image' Create a view of fields Add 'Staff Name' and 'Staff Image' Don't display Staff Name and put it above the image in the order Rewrite Results the Staff Image using the code above and replacement patterns for the staff name and image.

If you want to link this to content don't click "Link to Content" or anything like that. Add the NID field to the mix above, exclude from display then write that into the link.

Or something along those lines.

Hope that helps, i've just done battle with a similar thing that looks like the pic attached...

Good luck!!

# Answer
> 0 votes
You could do the following.

Add the name as well as the image in the view.

Using css initially place the name below the image covering it completely.

Now again using css write a hover on image and set the display to none so that it would hide and the name would show up.

If you want some kind of animation effects the you would go with JS

---
Tags: 7, views, nodes
---


title: Pagination using XML Views Backend

text:
# Question
Title: Pagination using XML Views Backend
We're using the Views XML Backend module to display XML data in our Drupal site from an XML-based Web API. (We actually have an integration tool wrapping the API, so we can transform data going into the Web API call. For example, I'm transforming JSON data into XML.)

I'd like to be able to use pagination in Drupal so that the users see that they are viewing results 1-20 of 500 results (for example), then pass the pagination information along to the Web API. The API (which was written in-house) can take the number of results to retrieve and either the page number or the first result to retrieve.

How can I achieve this?

I'm relatively new to Drupal, so please be patient. Thanks!

# Answer
> 0 votes
Searching for `pager` in the issue queue of Views XML Backend shows that the plugin can output the info you want.

You should be able to add to the `Header` region of the view a `Global Results Counter` which shows text like "Viewing X of N to M records". All of this is done in the Views Administration UI for your View.

You could then call the page via curl or via `views_embed_view` using php programatically to pass and or set the page number and records per page as needed to get the results you want.

---
Tags: views, feeds
---


# Question
Title: Hide the title or Change the Title style of one page based on page Title Multi site
I know that I can hide the title by using:

```
.page-node-43 h1
{ display: none;}

```

The problem with that is that I am using this css file for all of the websites that I am using. The websites have **different node numbers** for sometimes the same kind of page. So there is the catch.

I want something like

```
.page-practial h1
{ display: none;}

```

But that doesn't work. Do I have to use to achieve this? :)

Thanks in advance!

# Answer
> 1 votes
If you're on a multi-site, you could just use the domain and add it to the body class. That way you can target the same content type differently on each site.

Using preprocess\_html...

```
function THEMENAME_preprocess_html(&$vars) {
  global $base_url;

  // Split the URL
  $site_host = explode('/', $base_url);

  // Split the root domain from the TLD (.com).
  $site_host = explode('.', $site_host[2]);

  // Add it to your body class.
  $vars['classes_array'][] = drupal_clean_css_identifier($site_host[0]);
}

```

You might have to alter it a bit, but you get the idea. So if your domain was `http://example.com`, this would add `example` to the body class.

```
<body class="page-node page-node- page-node-194 node-type-product example">

```

---
Tags: 7, theming
---


# Question
Title: Does Views RSS display deals with relationship
I have a content type "Event" which has a relationship with the content type "Category", via the node reference field 'category\_ref'.

The "Category" content has a field "Image". I have figured out how to display the field "Image" in a page view listing the "Events" node, with relationship option on "Image" field.

It works just fine, except that I would like now to create a feed for this view, to export it on Facebook. But then, as there is no field to set up for RSS feed, I don't know how to fetch the image from "Category" and get it in my RSS.

The point where I'm stuck is that the relationship is set on the RSS display tab, but the image does not show.

Is there a way to do fetch datas from another content type than the one of the views via the RSS display of the Views interface?

# Answer
It sounds like you want the Views RSS module. It will add a new plugin that will allow you to map arbitrary fields to RSS elements at the channel and item level.

So, if your view is fielded out with the proper relationships already, you can just add a new display, map the fields, and assign it to a path, all in about 10 min.

The help in the module is also excellent.
> 2 votes

---
Tags: feeds, views
---


title: Drupal 6 Add Webform Programmatically

text:
# Question
Title: Drupal 6 Add Webform Programmatically
I'm trying to add a new component or populate an existing hidden component on a web form programmatically. I found this:

http://drupalcontrib.org/api/drupal/contributions!webform!webform.module/function/\_webform\_client\_form\_add\_component/6

However I have not found any hooks, which would be the preferred way to do this. I'm essentially just checking to see if there is a hook or how to access that function in a custom module if no hook exists.

# Answer
> 0 votes
A webform is simply a node so the rough process of doing this would be to node\_load() your particular node, add your components array to the $node-\>components\[\] array and then execute a node\_save(). There is some documentation here that fleshes out how to programmatically add a webform, your code would look something like this:

```
$node = node_load(YOUR NODE ID);
$components = $components = array(); #YOUR COMPONENTS ARRAY
$node->webform = array(
      'components' => $components,
);
node_save($node);

```

---
Tags: hooks, webforms
---


# Question
Title: View Contextual filter for content updated dates
I am new to Drupal.

I want to implement a contextual filter in YYYYMMDD or in Unix date format. if I pass a value as 1st Dec 2013 (20131201) then it should return me all the contents who has been updated after that date. I am not able to get how to do it.. I got to know about updated date but its in the format of CCYYMMDD is it same as YYYYMMDD? if not then can I change it to so?

# Answer
> 0 votes
The date format CCYYMMDD is indeed the same YYYYMMDD.

CC means century number as a 2 digit cardinal number where the first century was given the number 00. The present century is century number 20.

YY or YYYY means year (written as a 2 or 4 digit cardinal number with a leading zero if required), The present year is 14 (two digits) or 2014 (four digits).

MM means month as a two digit cardinal number with a leading zero if required. The present month, January, is written as 01.

DD means day om the month as a two digit cardinal number with a two digit leading zero if required. Today is day number 24 of January.

In other words, today's date (January 24th 2014) is written `20140124` in both these formats, and December 1st 2013 is written as `20131201` in both these formats.

---
Tags: views
---


# Question
Title: Views contextual filter to a number of product variations
I am having real trouble with this and would appreciate any help.

I have a view block that needs to display all variations of a product that have the same sku with an increment at the end.

Example:

Product name is: 4 jembi avenue

This produces a url of /4jembiavenue

All product variation skus are based on this, so every product variation will now have sku

4jembiavenue0 4jembiavenue1 4jembiavenue2

so on so forth.

What I need is views to display ALL product variations in the view.

I can achieve this by using a filter and setting it to Contains: 4jembiavenue. However as I am intending to have many products displayed like this I do not want to do it like this as each new product would have to have a new block and a new view.

I can use a contextual filter to get the value (4jembiavenue) from the URL and it works fine, but of course it only displays 1 product variation where I am going to need up to 60.

So my question is this:

How can I use a contextual filter with a "contains" operator to find and display all of the product variations?

If you know of any other way I can achieve this I would gladly try this too.

Thanks in advance for any help!

# Answer
> 0 votes
You could try like. First include sku in your view and exclude it from display. Then write this code it would give u desired results.

```
function modulename_views_query_alter(&$view, &$query)
    {
    if($view->name=='yourname'){
        preg_match('/.*[^\d+]/',drupal_get_path_alias(),$match);
        $query->add_where(1,'commerce_product.sku','%'.$match[0].'%','LIKE');
    }
}

```

---
Tags: commerce, views
---


# Question
Title: how to create a page.tpl.php without $page['content']?
The `page.tpl.php` of my website shouldn't contain `<?php print render($page['content']); ?>` because it is only set of blocks. The problem is I'm not able to insert comment form into node pages of a website which its `page.tpl.php` hasn't `<?php print render($page['content']); ?>` . what shall I do?

# Answer
You have asked simple question & there is very simple answer for that --

Yes, you can create `page.tpl.php` without `<?php print render($page['content']); ?>`. You just have to remove this snippet from the TPL file & it will work.

But then you have explained your issue about comment.

So if you go through the structure of tpl files at theme, you will understand that `<?php print render($page['content']); ?>` is responsible to print `node.tpl.php` & that one contains `<?php print render($content['comments']); ?>`.

So without fetching the things of `node.tpl.php` you won't get comments. Anyway, how a comment can be associated to a page when there is no node.
> 3 votes

---
Tags: nodes, 7
---


title: Fetch views using a ajax request

text:
# Question
Title: Fetch views using a ajax request
I worked in printing out a view using php. Is it possible to fetch views using ajax and load in the page? For suppose I have three links each one will fetch a view using ajax and load in the current page. (Am I talking sense?)

# Answer
Yes it is very much possible, but probably you can do it only by creating custom module.

* send Ajax request to the Drupal
* load selected view form database by views\_get\_view
* execute selected display by $view-\>execute\_display('display')
* send HTML created on executing display back to the client.
* on client side put this html wherever you want

Check ajax load module (which is D6 only) too, maybe it can help you.

There is a even quicker way and more robust to render a view: views\_embed\_view
> 3 votes

# Answer
Use the following javascript code to load a view via ajax.

```
$.post(
Drupal.settings.basePath + 'views/ajax',
{

view_name: '<your view id>',view_display_id: '<page or block ...>',view_args: 'arg1/arg2..'
},

function(response)
{
    if (response[1] !== undefined)
    {
        var viewHtml = response[1].data;
        $("#user_gal_photos").html(viewHtml);
       /*...*/
        Drupal.attachBehaviors();
    }
});

```
> 2 votes

---
Tags: views, ajax
---


# Question
Title: Media Gallery not using lightbox and required libraries are in place. What is wrong?
I'm trying to make a Gallery utilizing lightbox on my Drupal 7.26 site. I've picked Media Gallery (7.x-1.0-beta8) and as it says it requires the following compulsory components to work:

* Media (1.4)
* Multiform (1.0)
* ColorBox jQuery plugin

I've extracted a colorbox-master.zip under `sites/all/libraries` and renamed `colorbox-master` folder to `colorbox`. Now the `sites/all` looks like this.

I also have the colorbox module installed.

The images in the gallery doesn't seem to use any lightbox at all when clicked upon. I've checked a couple of other solutions elsewhere and I think I've gotten all of them covered as you can see on the screenshot above. Nothing else seems to help.

What am I doing wrong?

# Answer
> 0 votes
As Bala Varadarajan suggested. I gave `sites/all/libraries/colorbox/` and all its contents **full Read/Write** permissions.

The lightbox is working now.

---
Tags: 7, javascript, media
---


# Question
Title: Anonymous users email subscriptions to node updates
How can I achieve the following:

I want to be able to notify the anonymous user by email when I update a node.

Example: I have \`mysite.com/cool-page. I want to have a block with an email field so users can subscribe basically to that page. And every time I update the content from that page, I want the subscribed users to be notified by email.

With Rules I managed to set something up so every time my node is updated it will send an email to users of a role. The problem is that I want to send an email to a list from the database (that I previously collected in a subscription block).

I use Drupal 7.

# Answer
You could try the MailChimp Subscriptions module. It won't let you subscribe to individual pages, but instead to node authors. (Never tested that)

Another way, might be to use the Simple Subscriptions module and to write some custom code to achieve exactly what you want.
> 0 votes

---
Tags: rules, emails, notifications
---


# Question
Title: Radio buttons triggering an AJAX callback to load form elements are pre-selected after navigating back to form in browser
My form looks like this:

```
  $form['field_1'] = array(
    '#title' => t('Field 1'),
    '#type' => 'radios',
    '#required' => TRUE,
    '#multiple' => FALSE,
    '#ajax' => array(
      'callback' => '_myform_ajax_field_2',
      'wrapper' => 'field-2-wrapper',
      'method' => 'replace',
      'effect' => 'fade',
    ),
  );

  $form['field_2_wrapper'] = array(
    '#prefix' => '<div id="field-2-wrapper">',
    '#suffix' => '</div>',
    '#weight' => 2,
  );

  if (isset($form_state['values']['field_1']) && $form_state['values']['field_1'] > 0) {
    $form['field_2_wrapper']['field_2'] = array(
      '#title' => t('Field 2'),
      '#type' => 'radios',
      '#required' => TRUE,
      '#multiple' => FALSE,
    );
  }

```

The problem occurs when I submit the form successfully and move to the next page, and then navigate back to this form using browser back button and the `field_1` radio button is remembered by the browser. This means that the radio is already selected however in this instance `form_state['values']` is empty so field\_2 does not display. From here the only way to get `field_2` to load via AJAX is to un/re-select the desired option in `field_1`.

I've tried the following solutions which failed:

1. Adding a JS file to `$form[#attached]['js']` to deselect any radio buttons on load, however this also gets loaded in AJAX calls. I'm not aware of a method to prevent this JS from running as a result of a traditional page load, but not on AJAX.
2. I've tried setting a `#default_value` on `field_1` however this has no effect.

Since writing this question, I've discovered a solution which I'm really not happy with:

I am checking for and adding a unique class name to the page body to check whether I've already deselected radios. If it's already there, then don't try again. This works, it just feels a bit dirty, so I'm hoping there's a more Drupally way to solve this?

# Answer
> 0 votes
OK after a bit of searching I found this: http://codekarate.com/blog/drupal-7-prevent-duplicating-javascript-behaviors

Specifically it mentions ***Drupal 7 integrates the Jquery Once plugin into Drupal 7 core***.

Therefore I can modify my `Drupal.behaviours.attach` to the following:

```
  Drupal.behaviors.uncheckRadioButtons = {
    attach : function(context, settings) {
      $('body').once('deselect_radios', function (){
        $('input[type="radio"]:checked').attr('checked', false);
      });
    }
  };

```

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


# Question
Title: EntityMalformedException: Missing bundle property on entity of type node in modal
I want to open create content type in modal, according to modal form and modal api example, I implement it, I test

the problem is here when I test it by contact form

```
    ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    // 'title' => t('Contact'),
    'ajax' => TRUE,
  );
  module_load_include('inc', 'contact', 'contact.pages');
  $output = ctools_modal_form_wrapper('contact_site_form', $form_state);

```

every thing work correctly and there is no problem,but when I change it to

```
ctools_include('modal');
  ctools_include('ajax');
  $form_state = array(
    // 'title' => t('Contact'),
    'ajax' => TRUE,
  );
module_load_include('inc', 'node', 'node.pages');
$output = ctools_modal_form_wrapper('page_node_form', $form_state);

```

return me \** An AJAX HTTP error occurred. HTTP Result Code: 500 Debugging information follows. Path: /drupal-7.24/share/ajax/1 StatusText: Service unavailable (with message) ResponseText: EntityMalformedException: Missing bundle property on entity of type node. in entity\_extract\_ids() (line 7724 of /includes/common.inc).\** , where is the problem?

I create a menu, and it open a modal,I want add content in that modal

# Answer
> EntityMalformedException: Missing bundle property on entity of type node

This means that at some point in code when the node entity should be handled, it is unclear what type (bundle) that is. Now when you look at node\_form() you see that it expects a node object as a parameter. If that's not given the node add form doesn't know what fields and properties to render because the node type can't be identified. Looking further into node\_add(), which is the function normally called to create a new node of a specific type, I think you could go along the following lines (completely untested):

```
global $user;
ctools_include('modal');
ctools_include('ajax');
$node = (object) array(
  'uid' => $user->uid,
  'name' => (isset($user->name) ? $user->name : ''),
  'type' => 'page',
  'language' => LANGUAGE_NONE,
);
$form_state = array(
  'ajax' => TRUE,
  'build_info' => array(
    'args' => array($node),
  ),
);
module_load_include('inc', 'node', 'node.pages');
$output = ctools_modal_form_wrapper('page_node_form', $form_state);

```
> 5 votes

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


title: Div around img tag in Drupal 7

text:
# Question
Title: Div around img tag in Drupal 7
I am using Drupal 7 with wysiwyg (7.x-2.0)module and CK editor 3.5.3.6655. I added an image in a block with link and the CK editor code is

```
<p>
    <a class="thickbox" href="example.com"> [[{"type":"media","view_mode":"media_original","fid":"751","attributes":{"alt":"contact","class":"media-image","typeof":"foaf:Image"}}]]</a>
</p>

```

But Drupal is adding some divs around the img tag and the resulting code is

```
<div id="block-block-11" class="block block-block">
      <div class="content">
         <p>
            <a class="thickbox" href="example.com">
                <div class="field field-name-file field-type-file field-label-hidden">
                    <div class="field-items">
                        <div class="field-item even">
                            <span id="styles-0-0" class="styles file-styles original">
                                <img typeof="foaf:Image" src="path to image.jpg" alt="contact" />
                            </span>
                        </div>
                    </div>
                </div>
            </a>
         </p>
      </div>
    </div>

```

Then I got the W3C error **document type does not allow element "div" here; missing one of "button", "map", "object", "ins", "del", "noscript" start-tag** as div is not allowed inside p and a. How can I solve this?

I added div instead of p but no use.

# Answer
The divs were added by the image module and the problem solved when I updated the module.

When adding an image through media file selector, click on image properties and remove the style sheet class value (media-image attr\_*typeof*\_foaf:Image img\_*fid*\_106 img\__view\_mode\__media\_original). This will show the image in img tag instead of some weird code
> 0 votes

# Answer
This is a field themeing issue. The field.tpl.php API docs and linked source is a good place to start. The comments on that page also have useful information for you.
> 1 votes

---
Tags: blocks, wysiwyg
---


# Question
Title: Failed to find the Facebook client libraries
While trying to configure Drupal for Facebook, I followed the readme and copied their code into my settings.php and placed the facebook-php-sdk file into the stated location under sites/all/libraries but I still get this error:

> Failed to find the Facebook client libraries at sites/all/libraries/facebook-php-sdk/src/facebook.php. Read the README.txt and follow the instructions carefully.

I went to publichtml\sites\all\libraries\facebook-php-sdk-master\src and www\sites\all\libraries\facebook-php-sdk-master\src to check if facebook.php exists to be sure and it's there.

# Answer
It's looking for the file in sites/all/libraries/facebook-php-sdk/src/facebook.php, while your file exists in publichtml/sites/all/libraries/facebook-php-sdk-master/src/facebook.php and www/sites/all/libraries/facebook-php-sdk-master/src/facebook.php. The difference is between facebook-php-sdk and facebook-php-sdk-master.

Change the folder name from facebook-php-sdk-master to facebook-php-sdk.
> 2 votes

---
Tags: social-network
---


# Question
Title: Top level directory files like readme.txt are served by apache
The content of the top-level server directory is publicly available by the web, e.g. files like example.com/readme.txt are readable.
Is it normal? How can i disable this?

(apache, ubuntu 12.04)

# Answer
> 2 votes
It is not normal. Test if your .htaccess file is there, and looks the same as one in the fresh copy downloaded from Drupal.org - if they are different, use the stock one.

If your .htaccess file is identical to the stock one, you need to make your Apache to respect this part:

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

```

How exactly you should do it would be off topic here, but may be asked on Ask Ubuntu.

**Note** that while default .htaccess protect most extensions you don't want served, it does not hide txt files you explicitly asked for. So just add that extension to the list, as you can see, it's pretty straightforward.

This will block txt files from all directories, except *sites/\*/files*, that have separate .htaccess files, with their own rules of access (since 7.22). If you don't want to serve core's readme.txt, then you probably don't want to serve modules' readme.txt too.

# Answer
> 4 votes
As I understood - you want to hide the txt files on the root direcroty (e.g. Changlog.txt) from prying eyes, therefore you can search Drupal.org for that question (its there..), and you'll see 3 types of solutions:
1. Leave those file as they are ( I don't like that option) 2. Just delete those files 3. Hide them using the site's .htaccess (My favorite option)

---
Tags: http-request
---


# Question
Title: Cannot assign calculated value to user field in Rules
Here is the situation and what I want to do:

* Users have a "days left" field of type integer.
* A user will set a date range while creating a "time off" content type.
* When he hits the save button, a rule will intercept, subtract the date range from his "days left" field and save the result as the new "days left" value.

here is what I have done:

* user clicks save button rule intercepts
* action - gets the duration and divides it by 86400 (to convert it to days from seconds)
* action - converts the result to integer
* action - subtracts the converted value from content authors "days left" field.

At this point I want to assign the result of the subtraction to the author's "days left" field. The node:author:field-days-left variable is available and I select it. But the result of the subtraction is not.

I also tried to convert the result of the subtraction to integer and then assign it, but it did not work too.

Any ideas why?

# Answer
I could not figure out why the result variable was not available; my solution was to change the order of the actions to:

After the user clicks save button, rule intercepts:

* get the value of author's "days left" field and multiply with 86400 (convert days to seconds)
* get the duration of content and subtract it from the previous value
* divide the result by 86400 (convert it back to days from seconds)
* convert the result to integer
* subtract one from this result (this turned out to be necessary, perhaps because of the rounding off during the type conversion)
* assign the result to content author's "days left" field.

I do not like having to make two type conversions but this is a working solution.
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Drupal 7: facebook comment for article only
I need Facebook comment for Drupal 7.

Which one can I use?

```
    <div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/fi_FI/all.js#xfbml=1&appId=409074972499544";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

```

If I use above code it shows me comment of any article for all article. I need to display comment for article.

# Answer
In Drupal 7 you can use

* **Facebook Comments Box** : This module gives your site the ability of using Facebook's Comments Box social plugin. It will create a **block** just configure only for **article**. You can check this video
* **Facebook Comments Social Plugin** : Implement Facebook commenting with settings on the level of both content type and node.
* Using **Facebook plugin code**

```
<div class="fb-comments" data-href="[CURRENT_ARTICLE_PAGE_URL]" data-numposts="5" data-colorscheme="light"></div>
```
NOTE :
    + **YOUR\_URL** : Updated **current URL** based on each article.
> 1 votes

---
Tags: comments, social-network
---


# Question
Title: Envoking a web service method with hyperlink
I have successful connected website with a web service SOAP. The SOAP PHP library is working great. So far I've used a forms that corresponds with the web service, but now I want to invoke a specific method of the web service by clicking on some link. For an example, the web service has a method "Logout" and I want to pass the xml string after clicking on user/logout. How can I do that?

# Answer
> 2 votes
You can implement `hook_user_logout()`:

```
function MYMODULE_user_logout($account) {
  // Make your web service call here.
}

```

That hook will be invoked whenever a user logs out, which includes them clicking on any link to user/logout.

---
Tags: services
---


# Question
Title: Create a new user in LDAP, not wherever Drupal normally creates it
We have an already existing LDAP of users, that we wish to use for our new site. Amazingly, the login seems to be only finding the users we want it to, and not the users we don't. We have to figure out why, because we'll probably want to change this in the future. (I mention, in case it's related to my main issue.)

However, the more important problem is that, when we create a new user, we want it to be created in the LDAP, not wherever Drupal creates it. As I understand, when it authenticates against LDAP, it simply copies the user to it's own database, and uses that from then on, which is also not what we want, in case the user changes their data. However, we'd still like the admin user to work, even if the LDAP dies or something. The documentation isn't much help with this.

So, how do I make Drupal (I'm using 7, but I don't know if it's 7 specific) use the LDAP for the creation of new users, and for existing LDAP users? (Hopefully, without totally removing the ability to use the users already in the Drupal db.)

# Answer
You will never be able to use Drupal's core user module without using the database's `user` table (and many others), without seriously modifying core Drupal.

It sounds like the only reason you want Drupal to not use it's own user + roles + permissions management (and all of the other contributed Drupal modules that depend on the user module) is so that if a user updates some data in LDAP it's also updated in Drupal. If this is the case, find a method for synchronizing your LDAP user info with Drupal's user info.

You can use the hook\_user\_ functions in Drupal to perform whatever actions you want to happen when a user account is created, updated, etc., in Drupal. For example, if a new user account is created in the Drupal user registration form you'd be performing whatever logic you need (via PHP, or potentially something else) to insert a new record into your LDAP server.
> 4 votes

# Answer
To configure LDAP with Drupal 7, you'll have to install and configure LDAP module (including ldap\_authentication and ldap\_user). Once enabled, you'll find the configuration at /admin/config/people/ldap.

First of all, you'll have to add and configure your 'LDAP Server Configuration' depending on your LDAP configuration (Servers tab at /admin/config/people/ldap/servers).

To configure LDAP Authentication in Drupal, choose the LDAP Server Configuration in Authentication tab at /admin/config/people/ldap/authentication.

At the end, to create LDAP entries on Drupal user creation, turn on 'Create or Synch to LDAP entry when a Drupal account is created or updated.' option and the other which you think are necessary and configure Provisioning from Drupal to LDAP Mappings according to your LDAP configuration (User tab at /admin/config/people/ldap/user).

See the configuration below:

Here is example configuration exported into code using Features:

```
<?php
/**
 * Implements hook_default_ldap_servers().
 */
function foo_ldap_default_ldap_servers() {
  $export = array();
$ldap_servers_conf = new stdClass();
$ldap_servers_conf->disabled = FALSE; /* Edit this to true to make a default ldap_servers_conf disabled initially */
$ldap_servers_conf->api_version = 1;
$ldap_servers_conf->sid = 'ldap_pv';
$ldap_servers_conf->name = 'LDAP: Local Provisioning';
$ldap_servers_conf->status = TRUE;
$ldap_servers_conf->ldap_type = 'openldap';
$ldap_servers_conf->address = 'example.com';
$ldap_servers_conf->port = 389;
$ldap_servers_conf->tls = TRUE;
$ldap_servers_conf->followrefs = FALSE;
$ldap_servers_conf->bind_method = 1;
$ldap_servers_conf->binddn = 'cn=drupal-test,ou=Services,dc=example,dc=com';
$ldap_servers_conf->bindpw = '';
$ldap_servers_conf->basedn = array(
  0 => 'ou=People,dc=example,dc=com',
  1 => 'ou=External,ou=Access,ou=Group,dc=example,dc=com',
);
$ldap_servers_conf->user_attr = 'uid';
$ldap_servers_conf->account_name_attr = '';
$ldap_servers_conf->password_attr = 'userPassword';
$ldap_servers_conf->password_attr_encoding = 'clear';
$ldap_servers_conf->mail_attr = 'mail';
$ldap_servers_conf->mail_template = '';
$ldap_servers_conf->picture_attr = '';
$ldap_servers_conf->unique_persistent_attr = '';
$ldap_servers_conf->unique_persistent_attr_binary = FALSE;
$ldap_servers_conf->user_dn_expression = '';
$ldap_servers_conf->ldap_to_drupal_user = '';
$ldap_servers_conf->testing_drupal_username = 'admin';
$ldap_servers_conf->testing_drupal_user_dn = '';
$ldap_servers_conf->grp_unused = FALSE;
$ldap_servers_conf->grp_object_cat = 'groupofnames';
$ldap_servers_conf->grp_nested = FALSE;
$ldap_servers_conf->grp_user_memb_attr_exists = FALSE;
$ldap_servers_conf->grp_user_memb_attr = '';
$ldap_servers_conf->grp_memb_attr = 'member';
$ldap_servers_conf->grp_memb_attr_match_user_attr = 'dn';
$ldap_servers_conf->grp_derive_from_dn = FALSE;
$ldap_servers_conf->grp_derive_from_dn_attr = '';
$ldap_servers_conf->grp_test_grp_dn = 'ou=External,ou=Access,ou=Group,dc=example,dc=com';
$ldap_servers_conf->grp_test_grp_dn_writeable = '';
$ldap_servers_conf->search_pagination = FALSE;
$ldap_servers_conf->search_page_size = 1000;
$ldap_servers_conf->weight = 0;
$export['ldap_pv'] = $ldap_servers_conf;
  return $export;
}

/**
 * Implements hook_default_ldap_authorization().
 */
function foo_ldap_default_ldap_authorization() {
  $export = array();
  $consumer_type = new stdClass();
  $consumer_type->disabled = FALSE; /* Edit this to true to make a default consumer_type disabled initially */
  $consumer_type->api_version = 1;
  $consumer_type->sid = 'ldap_pv';
  $consumer_type->consumer_type = 'drupal_role';
  $consumer_type->consumer_module = 'ldap_authorization_drupal_role';
  $consumer_type->status = TRUE;
  $consumer_type->only_ldap_authenticated = TRUE;
  $consumer_type->use_first_attr_as_groupid = FALSE;
  $consumer_type->mappings = 'a:1:{i:0;a:6:{s:12:"user_entered";s:18:"OV4 Pro Repository";s:4:"from";s:70:"cn=example-group-pro,ou=External,ou=Access,ou=Group,dc=example,dc=com";s:10:"normalized";s:18:"OV4 Pro Repository";s:10:"simplified";s:18:"OV4 Pro Repository";s:5:"valid";b:0;s:13:"error_message";s:106:"Role <em class="placeholder">OV4 Pro Repository</em>_name does not exist and role creation is not enabled.";}}';
  $consumer_type->use_filter = TRUE;
  $consumer_type->synch_to_ldap = FALSE;
  $consumer_type->synch_on_logon = TRUE;
  $consumer_type->revoke_ldap_provisioned = TRUE;
  $consumer_type->create_consumers = TRUE;
  $consumer_type->regrant_ldap_provisioned = TRUE;
  $export['drupal_role'] = $consumer_type;
  return $export;
}
?>

```

Read more:
> 2 votes

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


# Question
Title: Storing and retrieving custom field value of a webform in/from database?
I have altered a webform by adding a date field in different language like chinese in Drupal 7. But what steps are required to store custom field value in database and retrieving value when webform results are accessed?

I used `hook_form_alter()` to add custom date field in the existing webform, but its value doesn't get stored in database. Do I need to add some extra code to store value of custom field in db?

I am sharing my code.

```
function tekege_grievanceform_form_alter(&$form, &$form_state, $form_id) { //print_r($form_id);exit;
switch ($form_id) {
    /* for chinese */
    case 'webform_client_form_60224':
        $form['submitted']['dob'] = array(
            '#type' => 'fieldset',
            '#title' => t('出生日期'),
            '#weight' => 4,
            '#prefix' => '<div class="chinese_dob" id="webform_chinese_dob">',
            '#suffix' => '</div>',
            '#required' => 'true'
        );

        $form['submitted']['dob']['dob_month'] = array(
            '#type' => 'select',
            '#default_value' => array('month' => '月'),
            '#options' => array('month' => t('月'),
                1 => t('1 月'), 2 => t('2 月'), 3 => t('3 月'), 4 => t('4 月'), 5 => t('5 月'), 6 => t('6 月'), 7 => t('7 月'), 8 => t('8 月'), 9 => t('9 月'), 10 => t('10 月'), 11 => t('11 月'), 12 => t('12 月'),
            ),
            '#description' => t('Select month.'),
            '#required' => true,
        );

        /* for 31 days */
        $form['submitted']['dob']['dob_day_31'] = array(
            '#type' => 'select',
            '#default_value' => array('day' => '日'),
            '#options' => array('day' => t('日'), 1 => t('1'), 2 => t('2'), 3 => t('3'), 4 => t('4'), 5 => t('5'), 6 => t('6'), 7 => t('7'), 8 => t('8'), 9 => t('9'), 10 => t('10'), 11 => t('11'), 12 => t('12'),
                13 => t('13'), 14 => t('14'), 15 => t('15'), 16 => t('16'), 17 => t('17'), 18 => t('18'), 19 => t('19'), 20 => t('20'), 21 => t('21'), 22 => t('22'), 23 => t('23'), 24 => t('24'),
                25 => t('25'), 26 => t('26'), 27 => t('27'), 28 => t('28'), 29 => t('29'), 30 => t('30'), 31 => t('31')),
            '#description' => t("Thirty-One Days."),
            '#required' => true,
        );

        $form['submitted']['dob']['dob_year'] = array(
            '#type' => 'select',
            '#default_value' => array('year' => '年'),
            '#options' => array('year' => t('年'), 1 => t('2013'), 2 => t('2012'), 3 => t('2011'), 4 => t('2010'), 5 => t('2009'), 6 => t('2008'), 7 => t('2007'), 8 => t('2006'),
                9 => t('2005'), 10 => t('2004'), 11 => t('2003'), 12 => t('2002'), 13 => t('2001'), 14 => t('2000'), 15 => t('1999'), 16 => t('1998'), 17 => t('1997'),
                18 => t('1996'), 19 => t('1995'), 20 => t('1994'), 21 => t('1993'), 22 => t('1992'), 23 => t('1991'), 24 => t('1990'), 25 => t('1989'), 26 => t('1988'),
                27 => t('1987'), 28 => t('1986'), 29 => t('1985'), 30 => t('1984'), 31 => t('1983'), 32 => t('1982'), 33 => t('1981'), 34 => t('1980'), 35 => t('1979'), 36 => t('1978'), 37 => t('1977'), 38 => t('1975'),
                39 => t('1974'), 40 => t('1973'), 41 => t('1972'), 42 => t('1971'), 43 => t('1970'), 44 => t('1969'), 45 => t('1968'), 46 => t('1967'), 47 => t('1966'),
                48 => t('1965'), 49 => t('1964'), 50 => t('1963'), 51 => t('1962'), 52 => t('1961'), 53 => t('1960'), 54 => t('1959'), 55 => t('1958'), 56 => t('1957'),
                57 => t('1956'), 58 => t('1955'), 59 => t('1954'), 60 => t('1953'), 61 => t('1952'), 60 => t('1951'), 61 => t('1950'),
            ),
            '#description' => t('Select year.'),
            '#required' => true,
        );
    }
 }

```

# Answer
**Solved:** I was using devlopment version of webform module that was restricting my custom date fields of webform to get stored in database. It was required to be updated. Anyways thanks for replying.
> 0 votes

---
Tags: 7, webforms
---


# Question
Title: How do I import attributes with the feed mapper?
I have a Drupal 7 instance with Ubercart 3, and I'm also using the Ubercart Feed Mappers module to map out the importing of product fields. I have all the fields, images and categories working well, but not attributes.

I've searched high and low for an answer or a short how to for importing attributes and multiple attributes for each product but with no success. How can I achieve it?

# Answer
> 0 votes
You need 'UC Feeds Product Importer' a sub module built to import all the product related fields.

check this: https://drupal.org/node/1802908

1. Create an importer (at admin/structure/feeds/create). Or try my default importer module, which creates a csv importer from all Ubercart fields - including attributes - automatically. If you use it, please leave feedback on the issue!
2. Download the template from the import page (if you use the default importer above, it will be at /import/uc\_feeds\_product\_importer/template)
3. Fill in the template. For each attribute option you want enabled, fill in at least one of the cells for weight, price, or cost (a zero value works). If you fill in at least one of the three, any unfilled will default to zero. If you leave all three blank, that option will not be enabled on the imported product.
4. Import the completed csv at /import/uc\_feeds\_product\_importer (if you're using my module above), otherwise go to /import and choose the importer you created.

# Answer
> 0 votes
http://www.ubercart.org/project/node\_import\_uc\_stock#comment-55048 Node Import and Ubercart File Download Integration

I've extended node\_import\_supported\_v5.zip to add support for importing "Ubercart File Downloads". The only modification between my version and v5 is that I've added this patch to resolve an issue with node\_import and PHP 5.3

I've also included the additional doxygen generated API docs, so that hopefully others will be able to get a handle on the API and contribute improvements.

It would be best if we could get these ubercart extensions added into the core node\_import, so that others will find and use it. I think in order for that to happen though, cpILL's code will need to properly provide "$values\['nid'\]" in postprocess functions. Right now that'll mess up any other contrib modules which depend on that functionality.

---
Tags: 7, ubercart, feeds, importing-exporting
---


title: Show user content using subdomain

text:
# Question
Title: Show user content using subdomain
I have a social content publishing site maintained in Drupal 7. I want to show content only specific to a user when everyone visits the site using the user's user name as the subdomain.

For example when the mail site is www.example.com

And the user is john

When people visit the site using URL john.example.com

I want to show only the content created by John, like that is his own site or book.

When people visit the site www.example.com they shall see all content including John's content also. This may mean Drupal 7 content shall be as usual , only the subdomain shall show content created by John.

It is not clear whether this can be achieved by Domain Access module, hence asking here to get more targetted answer from any one who may have done something like this.

# Answer
You're really just passing an argument ("john") to a view (or multiple views, view blocks, etc.) to control what content is being displayed. I'm sure there is a way to do this in domain access but you can bypass that overhead by adding the logic in the view itself as a contextual filter. In rough detail:

* Create your view listing the content you would want to show
* Add a contextual filter based on Content: Author uid, and select 'provide default value'
* I would recommend using 'PHP Code' to provide your default value and having it return value from a custom function which you can place in a module for better maintainability, ex: return \_my\_custom\_function();

Your custom function should be returning the UID of the user you are looking for and could look something like this:

```
function _my_custom_function() {

  $domain = $_SERVER['server_name']; //reserved php variable
  $host = explode('.', $domain);
  $subdomain = $host[0]; // probably a more elegant regex to use here..

  // your code here that takes the subdomain 'john', sanitizes it, runs security checks, then pulls the uid for this username from the user table or wherever

  return $uid;
}

```
> 1 votes

# Answer
I've worked on Subdomain module in D6 so I can tell only about D6 version. Using it you can easily show users on each subdomain.

Here is what Subdomain page says:

> OVERVIEW:
>
> Automatically creates subdomains and places content on them. There are 4 modes:
>
> User: e.g. "Mary" and content at http://mary.example.com

You can create a View which lists user posts based on url or you can write a simple module which should be simple enough.

After you've done this, use Content Access module to decide what to show on which domain. You may not even need the Content Access module for what you want to do.
> 0 votes

---
Tags: nodes
---


title: Modify bulk_views edit user message

text:
# Question
Title: Modify bulk_views edit user message
I have been trying unsuccessfully to alter the text of the message in the bulk submit. The code, place inside \_views\_bulk\_operations\_direct\_process ,producing the message is:

```
$context['results']['log'][] = t('Performed %operation on @items.', array(
  '%operation' => $operation->label(),
  '@items' => format_plural(count($entities), '1 item', '@count items'),
));

```

How can I modify this? The message is displayed on any change made on the bulk view by the edit form(hook\_form\_views\_form\_og\_members\_admin\_default\_alter).

# Answer
Use the string overrides module \- anything passed through t() will be caught by this and it provides an admin interface similar to the localization functionality to make it easy to look up these strings and translate or change them as you like. It also recognizes variables so you can still use the context of the function. From the module:

> * Easily replace anything that's passed through t()
> * Locale support, allowing you to override strings in any language ...
> * Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you need a few easy text changes.

You can also do this in your settings.php file with a simple array, ex:

```
$conf['locale_custom_strings_en'][''] = array(
   'Performed %operation on @items.'      => 'Your Changes',
);

```

This handbook page covers both of these methods in much more detail.
> 1 votes

---
Tags: forms, views, status-messages
---


# Question
Title: Supplying current URL to "Path override" in Panels with Views pane
Sorry if this is a known bug but I searched and couldn't find a related issue.

I have a view which has a "Feed" display (xml), and a "Views Pane" display.

On the "Feed" display the supplied path/URL for the display is "feed/xml".

The "Views Pane" display has a contextual filter for "Taxonomy term" and also a pager that has "Expose the Items Per Page" set to on.

Now when the "Views Pane" is included in a Panel, the Contextual Filter value (term id) is supplied from the Panel context (Node being viewed: term field on node). So now when you view the panel page and try to change the Items Per Page exposed form, it tries to submit the form to the "Feed" display's path which is "feed/xml" and that's wrong. Ideally the `#action` of the exposed form should be submitting to the current URL.

So I went back to the view and edited the "Views Pane" display, opened to "Allowed settings" and set "Path override" to on. And then went to the Panel config, and I put `%node:url` as the "Path override".

All well and good so far, but now when I view the Panel page and look at the exposed form's `#action` its the correct url BUT with added extra parameter which is the Contextual Filter's taxonomy term id. For example: if my current page is `path/to/my/page` then the `#action` of the form is `path/to/my/page/115` where 115 is the ID of the taxonomy term currently supplied to the views pane through the panel context. So submitting the form produces a 404 in this case.

What I've tried so far is: \- Preprocessing the panel pane (theme\_preproces\_panel\_pane) which didn't help a great deal as the view was already rendered as HTML in the `content` key of the `$variables` array. At this point I realized preprocessing theme functions won't work. \- So I moved on to Views hooks and tried `hook_views_pre_render`. `dpm`-ing the `$view` from this hook, I can see that `$view->override_path` (string) is the correct URL (without the extra term id), but the exposed form was also already rendered here in `$view->exposed_widgets` (string, rendered HTML) with the wrong URL (with extra term id).

So before I go through all Views hooks, and maybe not even come up with a solution, I wanted to ask this question, if **anyone knows when exactly this exposed form is being rendered OR how I can stop the Taxonomy Term ID from being attached to `%node:url` token** (Perhaps a simple configuration that I've missed or.. ?).

**Edit**

So I went through all the Views hooks. Also implemented a `hook_form_views_exposed_form_alter`. From the order the `dpm`'s are being outputted, it looks like the order of execution is:

* `hook_views_pre_build`
* Exposed form gets built (dpm of hook\_form\_views\_exposed\_form\_alter)
* `hook_views_post_build`
* `hook_views_pre_execute`
* `hook_views_post_execute`

In `hook_views_pre_build` the `path_override` is correct. Form is not rendered yet.

In `hook_views_exposed_form_alter` the form render array is built, and `$form['#action']` shows the wrong path with the extra term id.

So I need to somehow get in between these 2 functions and supply the correct #action...

# Answer
Although this doesn't answer why exactly the term id is being attached (hoping someone might shed light on that), the simple solution thanks to @Letharion was to use the `hook_form_views_exposed_form_alter`:

```
function hook_form_views_exposed_form_alter(&$form, &$form_state) {
  $view = $form_state['view'];

  if($view->name == 'exhibitions' && $view->current_display == 'panel_pane_3') {
    $form['#action'] = $view->override_path;
  }
}

```
> 1 votes

---
Tags: 7, panels, views
---