title: How do I re-import menus and blocks?

text:
# Question
Title: How do I re-import menus and blocks?
I've got a local install that has turned bad. I want to quickly re-import block settings, block content, and menus.

How can I achieve this?

# Answer
You can export blocks with the Features Extra module, or better yet, use the Boxes module, which is designed to be exportable.

Using MySQL dumps is an advanced trick that gets harder with each version of Drupal as the API becomes more complex. It's not recommended and definitely not for the faint of heart.
> 5 votes

# Answer
If your importing to a brand new install then a selective dump of the menu and block tables should be ok, this way it won't overwrite any existing custom menus.

If the export site isn't too messed up then you can always look at exporting the menus and blocks as a feature and then import it into the new site.
> 1 votes

---
Tags: 7, blocks, importing-exporting
---


# Question
Title: multi price in drupal commerce in drupal 7
I have a shop created with drupal commerece modules,I enabled 2 currency in my shop , but only show one of them, I want to show price in 2 currency

something like this
**price : 10$ / 20 IRR**
I use **multi currency module** to achieve this job, but I my problem is in payment phase, I use multi currency module to achieve this job,in multicurrency module's setting I don't want use synchronize method, if you want have two field in my product , one form $ and another for IRR, I did this job by this method

first enable IRR currency in
**admin/commerce/config/currency**
then in
**admin/commerce/config/currency/handling**
under *Enable dedicated price fields for Product* check **Iranian Rial**
by doing this another field added you my product ( \** Price for IRR\** ), this is good , after this I enable **currency selector ** block ,in checking out process by switching the currency I don't see any change in current currency of billing and cart. :( why changing currency not changing cart currency?

# Answer
> 3 votes
Commerce Multicurrency module enhances some of the multi-currency capabilities of Drupal Commerce. You can show ***two or more currency*** for a product and check this video tutorial and this one

> Current features:
>
> * UI for fine granular definition of exchange rates.
> * (Every currency combination can be defined separately if needed)
> * Synchronization of currency exchange rates directly from the European Central Bank (ECB).
> * UI to specify which rates shall be synchronized and which are handled manually. Generation of currency specific price fields inclusive generation of rule-set to handle them.
> * hooks for easy integration of custom currency exchange rate sources.

this tutorial will help you without sync http://mcaleaa.wordpress.com/2012/04/08/drupal-commerce-multicurrency-recipe/

---
Tags: 7, commerce
---


# Question
Title: Displaying URL taxonomy term as page title
How can I display a taxonomy term in the url \[example.com/taxonomy/% (% being the term)\] of a page as title for that page - no view involved?

I assume it will require a block with some PHP or some hacking of a template.

In either case, what's the PHP and where do I put it?

I use D7 and Bartik.

Thanks. :)

# Answer
Taxonomy Title is the only module that let's you control that title individually for **every term**. (You can also override the title generally by using a **view** or a **pannel**.) An additional "Taxonomy Term Page - heading" field wil appear on the taxonomy term edit form, allowing administrators to configure a specific heading for each term page.

> The taxonomy title module also provides tokens which can be used in conjunction with the Page title and Meta tags modules.
>
> This module was designed to update the heading tag at the top of the taxonomy term page. The contents of this H1 (or sometimes H2) tag are *extremely* important for ***SEO (Search Engine Optimization)***. People interested in SEO may prefer to add more user-friendly, keyword-rich, and descriptive words to this heading element.
> 1 votes

# Answer
Another approach: override default taxonomy term display callback and do whatever you want with $term object. For ex., how do I usually do this with taxonomy\_override module: 1. Define callback:

```
function MODULENAME_taxonomy_override_define_callback() {
  return array('my_term_display_callback' => 'Display Callback');
}

```

and callback itself:

```
function my_term_display_callback($term) {

  //Title display. DO WHATEVER YOU WANT
  drupal_set_title($term->name);
  //or
  drupal_set_title($term->tid);
  //or
  drupal_set_title($term->vid);
  //or
  drupal_set_title($term->tid . ' -> ' . $term->name);
  //...

  // Build breadcrumb based on the hierarchy of the term.
  $current = (object) array(
    'tid' => $term->tid,
  );

  $breadcrumb = array();
  while ($parents = taxonomy_get_parents($current->tid)) {
    $current = array_shift($parents);
    $breadcrumb[] = l($current->name, 'taxonomy/term/' . $current->tid);
  }

  $breadcrumb[] = l(t('Home'), NULL);
  $breadcrumb = array_reverse($breadcrumb);
  $breadcrumb[] = '<span>' . $term->name . '</span>';
  drupal_set_breadcrumb($breadcrumb);

  // Set the term path as the canonical URL to prevent duplicate content.
  $uri = entity_uri('taxonomy_term', $term);
  drupal_add_html_head_link(array('rel' => 'canonical', 'href' => url($uri['path'], $uri['options'])), TRUE);
  // Set the non-aliased path as a default shortlink.
  drupal_add_html_head_link(array('rel' => 'shortlink', 'href' => url($uri['path'], array_merge($uri['options'], array('alias' => TRUE)))), TRUE);
  // usual part of term ends

  // DISPLAY.. DO WHATEVER YOU WANT
  if(someKindOfCheck) {
    return views_embed_view('viewName', 'blockOrPage');
  }
  elseif(anotherCheck) {
    return views_embed_view('viewName', 'blockOrPageWitchArgument', $term->tid);
  }
  else {
    return render(someRenderArray);
  }
}

```
> 1 votes

---
Tags: taxonomy-terms, blocks
---


# Question
Title: How to theme the user picture to appear in lightbox
I want to enable viewers to click on an image and have it displayed as a lightbox.

in my user-profile.tpl.php I have access to '$user\_profile\['picture'\]'. After I dsm($user\_profile) I see an array of $user\_picture with #markup and #weight elements.

I'm not quite sure if this is the right approach and how to go about altering the markup before it's displayed so i can add 'rel="lightbox"'

# Answer
> 0 votes
An alternative approach to wrapping the user picture around the necessary tag for lightbox, would be to append a custom CSS class to the user picture. Then navigate to /admin/config/user-interface/lightbox2/automatic (D7), down to custom class images and type in the name of the CSS class you chose before.

# Answer
> 0 votes
Another approach: copy user-profile.tpl.php to your theme folder and modify like this:

```
<?php

  global $user;

  $imgAvatarFid = isset($user->picture) ? $user->picture : NULL;

  if($imgAvatarFid != NULL) {
    $imgAvatarFile = file_load($imgAvatarFid);
    $imAvatar = image_style_url('large', $imgAvatarFile->uri);
  }

  ?>
  <div class="profile"<?php print $attributes; ?>>
    <?php print render($user_profile); ?>
  </div>

  <?php if($imgAvatarFid != NULL): ?>
  <div class="imgAvatarPop">
    <div class="close">
      <span>Close</span>
    </div>

    <div class="imgAvatar">
      <img src="<?php print $imAvatar; ?>" />
    </div>
  </div>
  <?php endif; ?>

```

and in your css file add:

```
.imgAvatarPop {
      display: none;
      position: absolute;
      left: 30%;
      top: 25%;
  }

```

and in your JS file:

```
$('.profile > .user-picture > a').click(function() {
      $('.imgAvatarPop').css({display: 'block'});
      return false;
  });

  $('.close span').click(function() {
      $('.imgAvatarPop').css({display: 'none'});
  });

```

if you want you can customize this. Or even you can add overlay to page.tpl.php and show it on user-picture click.

---
Tags: users
---


# Question
Title: Custom image style is not honored on new content
On drupal 7 I created two new image styles. Now when I save new contents, I expect the new images to be saved in the new image styles as well but this does not happen. Images are only saved in the ordinary thumbnail, medium, large and square-thumbnail sizes.

How can I make the new image styles be honored?

**Edit**: So Mołot and Bala made it clear that a certain image style has to be called to generate an image of that style. Yet, I would like to call for a smaller image in the code, and then load a larger version for wider screens.

Is this possible? Note: I am using ZEN as the theme.

**Edit 2**:

What I want to do is to load an initial small image like:

```
<img class="resp-image" src="very-small.jpg" />

```

Then, according to the screen size, I will replace the image with a larger version. This version of the image is provided by an image style:

```
if($(window).width() > 768) {
    $('.resp-image').attr('src', 'large.jpg');
});

```

The problem is, since I do not refer to `large.jpg` in the content type's display settings, it is not rendered to the given style and thus does not exist yet.

I was going to put this up as a new question but I found out that it is already discussed here and here.

Mołot's answer best described the situation referred to in the inital question. So I accepted it.

# Answer
Images are only rendered to a given style when something actually tries to use that style. If you want to force generation, you need to use `image_style_url` to obtain URL for the image, and then download it via regular HTTP request. It becomes more complicated if you don't want to download (aka show) it. In that case, use `image_style_deliver`.
> 1 votes

# Answer
Go to **manage display** and set the style you want under the format, see the below screenshot and choose the image style you created.
> 1 votes

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


title: How do I use this code?

text:
# Question
Title: How do I use this code?
I have this code, but I don't know how to wrap it in Drupal.

```
$(document).scroll(function () {

  var y = $(this).scrollTop();
  if (y > 100) {
    $('.bottomMenu').fadeIn();
  } else {
    $('.bottomMenu').fadeOut();
  }

});

```

I've already activated the .js file and added the detail in .info, I can see it from the firebug that is OK, but from the Firebug console I can see that I have syntax errors.

From Drupal website I can see this example.

```
(function ($) { // Here code javascript })(jQuery);

```

Can someone show me how the code above should look like into Drupal? Thanks.

# Answer
> 6 votes
Here you go:

```
(function($) {
  Drupal.behaviors.yourCustomName = {
    attach: function (context, settings) {

      $(document, context).scroll(function () {
        var y = $(this).scrollTop();
        if (y > 100) {
          $('.bottomMenu').fadeIn();
        } else {
          $('.bottomMenu').fadeOut();
        }
      });

    }
  };
})(jQuery);

```

Be sure to read the docs.

---
Tags: javascript
---


title: Search Files and Helper Apps

text:
# Question
Title: Search Files and Helper Apps
I am new to Drupal.

How do I use the helper apps with the search files module.

were to i put them or how do i apply them?

serach files: http://drupal.org/project/search\_files

# Answer
I have this installed and am using the search directories part successfully. the attachment submod doesn't seem to work right. but I do have the directory part installed.

Directory Path sites/all/files/pdfs/criminal

The directory path to be searched for files. Relative pathes are kept and currently based on /var/www/html. URI Path http://docresource.org/sites/all/files/pdfs/criminal

The URI path to retrieve files from the directory above. Usually some http:// download URL. Warning : no test access done.

my PDFs are in the folder shown above. you have to have the relative path and the urL.

you also have to have a helper app installed. I installed xpdf via YUM in Centos. then, you can adjust the indexing to suit the capacity of your server. I have thousands of PDFs to scan so i have to tweak it.

let me know if you have additional questions.
> 0 votes

---
Tags: 7
---


# Question
Title: Feasability of module or submodule for user picture migration
It seems like there would be a fairly large number of Drupal 6 websites with user pictures that will need to be migrated to Drupal 7 at some point and that the difficulty of migration might be keeping some sites from migrating.

There are various posts here and there about the code needed to migrate user photos but this may be daunting to some users. Would it be difficult to create a module that the user could configure with source and target directories using the configuration menu and that would then perform the migration, so that user could avoid getting into Drupal's internals?

It would also be nice if drush could be used for this migration, but the solution above would probably be accessible to more users.

I'm not a developer, so creating and maintaining a module seems to be more than I could commit to, but I'm wondering whether this would be easy for someone with more experience.

# Answer
> 1 votes
I hadn't realized that the dev versions of migrate and migrate\_d2d now support migrating user pictures.

The UI asks for the location for files in the installation one is migrating from. In my case, pictures were stored under files/pictures but I only had to specify "...files". I don't know if it would work if user pictures are stored in a directory with a different name.

In any case, once I switched to the dev versions, it seemed to work.

---
Tags: users, migrations
---


# Question
Title: Form API submit handler does not get called
I am using FAPI with dynamic fields. The code I am using is:

```
function email_action($form, &$form_state) {

$result = db_query('Select * from my_action_plan_settings ORDER BY action_type');
$records = array();
foreach ($result as  $record) {
  $records[] = $record->poa;
}

for ($i = 0; $i < count($records) ; $i++) {

  $form['action'] = array(
    '#type' => 'fieldset',
    '#title' => t('Action #@num', array('@num' => $i)),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  $form['action'][$i]['poa'] = array(
    '#type' => 'textfield',
    '#title' => t('Point of Action'),
    '#default_value' => $point_of_actions[$i],
    '#description' => t("Enter first name."),
    '#required' => FALSE,
  );
  $form['action'][$i]['email'] = array(
    '#type' => 'textfield',
    '#title' => t('Email Address'),
    '#required' => FALSE,
  );

}

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

return $form;

}

function email_action_submit($form, &$form_state) {
  dsm($form_state);
}

```

The submit handler never gets called, I used a custom submit handler also, it does not get called. If I limit the count of loop to 20, the submit handler gets called and everything works fine but without breaking the for loop, the submit handler never get called, is there a limit to number of fields? Or am I doing something wrong. Not sure what the issue is.

# Answer
> 1 votes
You can try the following :

```
 function email_action($form, &$form_state) {

    $form['#submit'][] = 'email_action_submit';

    }

    //submit function for the form

    function email_action_submit($form, &$form_state) {

    // write your submit code here
    }

```

---
Tags: forms
---


# Question
Title: How to access image style url from jQuery code?
`image_style_url()` generates proper links, but sadly it's only a PHP function.

Let's assume I want to substitute file icon with preview image on hover:

```
(function($) {
  Drupal.behaviors.ImagePreview = {
    attach: function (context, settings) {

      $('.form-managed-file', context).on('hover', function(){
        $(this).find('img').attr('src', $(this).find('a').attr('href'));
      });

    }
  };
})(jQuery);

```

Not the smartest code in the world, but simple, works and illustrates my example. Now, it will show image in the resolution user uploaded. But I need a thumbnail. It's a built in style so I don't need to test if it exists, but I do need valid security token and I need to respect all the Drupal file system settings, just like `image_style_url()` does. How can I achieve this with jQuery?

Note: In my case both input and output need to happen on jQuery side, as the image may not even be on the server when page is rendered.

# Answer
For a single image style, I tack it on as a data attribute to the image. Then in my JS, I use that.

This is how I handle retina images, using src switching (edited to just show the relevant portions):

```
function MYTHEME_image_style($variables) {
  // ...

  if (in_array($variables['style_name'] . '_2x', array_keys(image_styles())) {
    $variables['data-retina'] = image_style_url($variables['style_name'] . '_2x', $path);
  }

  return theme('image', $variables);
}

/**
 * Implements theme_image().
 */
function MYTHEME_image($variables) {
  // ...

  if (isset($variables['data-retina'])) {
    $attributes['data-retina'] = file_create_url($variables['data-retina']);
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

```

This in the JS (again, lifted and edited):

```
$('img').each(function (i, img) {
  var $img = $(img);

  if ($img.data('retina')) {
    $img.data('src', img.src);
    img.src = $img.data('retina');
  }
});

```

The key is to generate the style URL on the server side, so that the URL includes the itok and that all hooks get fired to allow modules like CDN to work. You just need to figure out the proper place to do it from. In your case, I suspect you may need to do it from a `theme_field`.
> 4 votes

---
Tags: javascript
---


# Question
Title: Using menus anywhere on page - how to stop them expanding by default when not used in menu region ( e.g. in a block or panel)?
I am trying this with superfish but the menu options are expanded by default.

What would I need to do to get it to behave like it does in a menu (i.e. collapsed by default).

I want to use the menu drop down within the content (**Edit** i.e. within a panel or a block so that I can have drop-down menu functionality anywhere on the page (hence the tags).

# Answer
> 1 votes
The solution I chose in the end was to hand-code a drop down, based on the HTML markup output by a Views Exposed Filter form that I am already using (this also means that the look and feel is consistent).

So I created a block in the usual way and added the code shown below, and then in my 2-column minipanel added this block to the 2nd column and then added my minipanel to the panel page. The other column, 1st, of the columns contains the views exposed filter as discussed. See screenshots below, after the code:

```
<form>
<select name="field_type_value" class="form-select" onChange="document.location = this.value" value="GO">
<option value=""  selected="selected" disabled="disabled">Add something to our map!</option>
<option value="node/add/local-resource">person</option>
<option value="node/add/local-resource">organisation</option>
<option value="node/add/local-resource">project</option>
<option value="node/add/local-resource">wifi hotspot</option>
</select>
</form>

```

Other features in the code above:

Remaining thing to do:

# Answer
> 0 votes
Check out the Menu Block module. It allows you to create a block that displays a menu, and it comes with a bunch of settings to control how the menu is displayed.

---
Tags: 7, routes, blocks, panels, navigation
---


title: Modules to set credits/points

text:
# Question
Title: Modules to set credits/points
I'm looking for a module to allow myself or other moderators to set credits/points for each site member. The site members can use the credits to purchase items in the store. I don't want to use any real world currency for the transactions, just virtual points.

This site is for an online guild. My hope is to set up a reward system and give each member points for being active in the guild, they can turn around and use the points to get content for their characters in game.

Is there any module that would help me achieve this?

# Answer
> 0 votes
I did a google search and found the Commerce Credits module; it sounds like what you're looking to do.

> Commerce Credits allows you to have users buy or win credits. The credits these users buy or win are fully configurable and can expire after some time. The process used for these credits is also fully configurable through Rules. It allows you to entirely define your own process for the payment and the use of these credits.

---
Tags: 7
---


title: Access field on relation from rule

text:
# Question
Title: Access field on relation from rule
I am using the Drupal 7 Rules and Relation modules. I have a relation between a user entity and a node content type (membership). The relation has an added field (relationship type). I was able to define a rule to create a new relation entity and set the relationship type field when creating a new membership node.

Now I am trying to write a rule with a condition that checks the value of the relationship type field at the time some event referencing a user or membership entity fires. The Relation module provides actions to fetch endpoint entities, but I cannot find a way to fetch the relation entity itself. What I'm searching for is a way to load that relation entity, tell Rules the relation type to expect, then be able to access the field (relationship type) on that relation.

Thanks in advance for any advise.

# Answer
I believe `Rules` lets you write custom `php`. Relation has an API. You can query for a relation directly using `relation_load` and giving it a `relation_id`. You can also search for a relation by supplying 1 endpoint and the type of relation you are looking for (or empty to return all relations of that endpoint, using the relation\_query() function.

```
/**
 * Returns a query object to find related entities.
 *
 * @param $entity_type
 *   (optional) The entity type of one of the endpoints.
 * @param $entity_id
 *   (optional) The entity id of one of the endpoints. Can also be an array of
 *   entity IDs.
 * @param $r_index
 *   (optional) The index of the search entity in the relation to be found
 *   (0 = source, 1 = target).
 *
 * @return RelationQuery
 *   The query object itself.
 */
function relation_query($entity_type = NULL, $entity_id = NULL, $r_index = NULL) {
  return new RelationQuery($entity_type, $entity_id, $r_index);
}

```

The `RelationQuery` is simply a small custom extension of the core `EntityFieldQuery`. You can use `relation_query()` and pass it a `UID` and a `NID` as the endpoints -- relation\_query will return the `Relation` ids (RIDs) for those objects. You can inspect the relations further by calling `relation_load($rid)`.

You can then do whatever you need to with the relation(s). A small example. In my app students have surveys assigned to them to complete; using Relations. When they're done with a survey I want to change a flag on the Relation that the survey is completed ...

```
function _mark_student_survey_as_completed($user_id, $survey_id) {
  // using relation query we want to search for a $user and a
  // specific survey they should have been assigned. Many arguments
  // to relation_query are optional, you can more results; like
  // if you just supply a UID, you'll get all relations that use
  // that UID as an endpoint.
  $relation_ids = relation_query('user', $user_id)
      ->related('custom_survey',$survey_id)
      ->execute();
  $relations = entity_load('relation', array_keys($relation_ids));
  if (count($relations) == 1) {
    $relation = reset($relations);
    // survey_is_completed is an attached field, to the Relation;
    // not an endpoint.
    $relation->survey_is_completed[LANGUAGE_NONE][0]['value'] = 1;
    // Save our field change on the parent relation.
    relation_save($relation);
  } else {
    watchdog('survey_check', 'Duplicate Survey!'.$user_id.'::'.$survey_id.'::'.print_r(array_keys($relation_ids), TRUE), WATCHDOG_ERROR);
 }

```

Lastly, since RelationQuery is just a class ... I've seen people extend it to make custom "relation logic" more easy, or even Views-like listing easily. Look at this blog post for such ideas (not my blog post): http://www.phase2technology.com/blog/building-energy-gov-without-views/
> 1 votes

---
Tags: rules, entities
---


# Question
Title: How do I hide the entire parent (top) level in superfish?
Using the Superfish module, I need to show just the second level and below. That means, hide the entire first (parent) level and only show the child level based on the current page.

Is this possible?

I tried editing the Superfish block and changing the menu depth, but it doesn't allow me to choose the depth to exclude above it.

# Answer
The simplest way of doing this would be with CSS.

What you want to do is set all menu items to be hidden via `display: none;`, and then override that property for child items.

Something like this (will need to be adapted to your specific DOM/selectors):

```
.my-nav ul {
  display: none;
}

  .my-nav ul ul {
    display: block;
  }

```
> 2 votes

# Answer
Menu block module allows you to choose which level to show, and how deep.

It won't integrate with superfish module, but allows you to build the submenus you're looking for. Moreover, those submenus may be themed to use basic superfish:

```
function THEMENAME_menu_tree__menu_block__1($variables) {
    return '<ul class="menu sf-menu">'. $variables['tree'] .'</ul>';
}

```

`1` in the function name is the delta of the custom menu\_block created.

Although posible, there's no straight way to leverage advanced superfish configuration / styling within a menu\_block: APIs are not isolated enough as to theme a menu\_block with a complex superfish style in a few of lines.

Just note also that a closer integration of both modules is feasible (I think of superfish using menu\_block API).

So, although incomplete, I think menu\_block + superfish is the best alternative.
> 2 votes

---
Tags: navigation
---


# Question
Title: footer link to a page with hash changed content ready
I have set up the pages like this (using some php and jquery):

On this page, I have some tabs, using jquery to hide and display the content on click each tab. The url will change to #this\_tab\_name accordingly.

For example, www.mysite.com/thispage#tab1 will be showing the content of tab1 only when someone clicks tab1 on thispage.

Now I want to set up a footer site map, I want some of the menu items link directly to urls like www.mysite.com/thispage#tab1 and also display the right content while hiding the rest. Embedding "thispage#tab1" will only link to thispage, but without the right content.

Any suggestion? Many thanks!

# Answer
You need to add your jquery to document.ready as well as click, that way when a user goes to the page it will load the proper tab for you.

Something like this:

```
jQuery(document).ready(
    function()
    {
        //bind click event
        jQuery("#tab1").click(show_tab);

        //handle document load
        show_tab();
    }
);

function show_tab()
{
    ...
}

```
> 0 votes

---
Tags: routes, javascript, navigation
---


# Question
Title: HTML5 web app: How do I create a dynamic manifest file with drupal?
I hope this is the right place to talk about this...

I'm planning to create an HTML5 web application which basically download new contents, something like the financial times app. I want to use drupal such as base where I can upload contents and the export it such as json view. In the web app I would like to create a local database where i will add the contents. To keep it update I will compare the last content creation date in the app with the last content creation date on drupal, if they are not the same it will download the latest contents and add it into the db. This is "quite simple", let's move to my problem now... I've got one image per each content and, to see the images offline, I need to add it to the manifest file every time a new content is added.

How can I get this? Or if you think I should use another method, let me know.

Thanks in advance.

# Answer
images should be attached to content via image field(if not I know another way, just ask), so you can create a new views and fetch only these images

add page display to that views and use it to create manifest, in this way you have dynamic manifest. if you want write it to file, small module is needed.

in this case you need have more than one manifest (multiple manifest), one of them is for your images

steps to create images manifest:

1. create views to fetch images: named `manifest_1`
2. create page display in that views: named `page_1`
3. create a small module to create your manifest, dirty sample:

```
function mymodule_menu() {
  return array(
      'manifest/images' => array(
          'page callback' => 'mymodule_manifest',
          'access arguments' => array('access content'),
          'type' => MENU_CALLBACK,
      )
  );
}

function mymodule_manifest() {
  $images = views_get_view_result('manifest_1', 'page_1');
  //sent header text/manifest
  //output image paths
  die();
}

```
> 2 votes

# Answer
The original question mixes up two different elements of html5: app caching and off line storage. The question concerns the local storage not of application parts but of data: the images concerned are to be used as data. So therefore topic 2, completely different: off line storage.

1. App caching via a manifest file. This facility serves to cache application parts on the user device. Of course that is only useful for static parts; images, Javascript files and CSS files are good examples.
2. Off line storage. HTML5 contains a spec for local persistent storage, based on key/value pairs, let us say a generalized cookie idea. You can find plenty Javascript examples on the Net how to sync and manipulate this. Additionally, two other ideas are floating around: a local SQL implementation based on SQLite. This was thrown out of HTML5 because it turned out to be impossible to arrive at a single implementation proposal. The last idea is IndexedDB from Mozilla; no more than an idea. It might become more and then it might not.

So, for now local storage in key/value pairs is the official way to go. Take a look at http://diveintohtml5.info, my favorite site on HTML5. I hope this helps you.
> 0 votes

---
Tags: caching
---


# Question
Title: Content type with taxonomy in single exposed filter
i want to a single exposed filter with content types and taxonomy for a single content type, like i have 3 content types Parts,Tools,Equipments and have a taxonomy for parts with terms Hardware,Instruments and components, now i want a views exposed filter containing both of the them to filter. Is there any method to do that ?

# Answer
> 0 votes
Finder module will filter both of the fields, You can select taxonomy term, node title, body, fields, ..etc to perform the search.

> There are many ways to put together finder's functionality to get the sort of search form you need. There are also many hooks and theme functions allowing full customization of finder's output.

It is used for these purposes:

```
As a search tool to find a group of nodes or users.
As a way to navigate to a specific node or user page that matches criteria.
As an alternative to exposed filters for a Views module display.

```

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


# Question
Title: After updating to user_restrictions-7.x-1.0 in drupal7, I can no longer run cron from another host
I've been updating several drupal7 installations from one browser on the same host as ONE of them. I just did this, updating to user\_restrictions-7.x-1.0 on both machines. This caused no problems on the host where my browser was running, but on the other host drupal will no longer run cron manually at my request, and clicking on the "To run cron from outside the site, go to http:///drupal/cron.php?cron\_key=..." link yields an "Access Denied" message.

Under the circumstances, I must conclude that something significant has changed in user\_restrictions-7.x-1.0 that enforces some exclusion on the basis of IP address that didn't exist before or was not previously being enforced.

How do I grant my other host permission to use the cron\_key in question?

# Answer
The User restrictions module just restricts which users can log in basing on their username and email address; if the username or the email address matches a regular expression set in the module settings, the user is not allowed to log in. At the same time, the module doesn't allow users to change their usernames or email addresses to values that match those regular expressions.

The modules doesn't restrict user access basing on their IP, since that functionality is still present in Drupal 7 core, although Drupal core just allows you to set an IP address, not a range of IPs to ban.
If you are experiencing what you reported, then it could a module bug. Report it in the project queue, once you verified there isn't a issue already opened for that, and that the module is really the responsible for that behavior.

### Disclaimer

I am the maintainer of the module, although I didn't change the module code recently. I don't plan to develop any Drupal 7 module, since I am focusing on Drupal 8 development.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Add a views exposed filter block into my theme using template.php
I would like to render a views exposed filter block in my node theme. This is what I am doing:

```
function MYTHEME_preprocess_node(&$vars) {
   $search_form = drupal_get_form('views_exposed_form');
   $search_box = drupal_render($search_form);
   $vars['search_box'] = $search_box;
}

```

This way I could simply add variable $search\_box into my theme and the filter block would be displayed.

I have confirmed and 'views\_exposed\_form' is the correct form\_id. The problem is that this is throwing a nasty error that doesn't log the error message. My template gets broken (still appears, but broken) and no error message is logged.

It does work if I try to display, let's say, a regular search box. The code is the same, all I have to do is change to the search block form id (search\_form) like this:

```
$search_form = drupal_get_form('search_form');

```

Right now, I am almost pulling my hair, have searched up and down the web. Any help is appreciated. Thank you!

# Answer
You're actually having an error if you check the php logs:

```
PHP Fatal error:  Call to a member function get_exposed_input() on a non-object in
.../sites/all/modules/views/views.module on line 1950

```

You can't just call drupal\_get\_form('views\_exposed\_form') because drupal wouldn't know *which* exposed form you want to render. Remember that a view or view display have its own exposed form.

If you check where the error is, you'll see that it's caused by not having a view object in the form\_state variable.

What I suggest you do is use the Admin Block UI `(/admin/structure/block)` and just restrict which node types where you want to display the exposed filter.
> 1 votes

---
Tags: blocks, views, theming
---


title: Taxonomy terms with a scale?

text:
# Question
Title: Taxonomy terms with a scale?
Not quite sure how I should even google this. I've got a Content Type "Trips", the image shows what I want to see in my trips node page. Adventurus, relaxing, educational etc are my taxonomy term categories. It seems to me like each taxonomy term should have a scale of 0-5. Which is the better way to achieve this? Any module around? (using drupal 7)

# Answer
> 0 votes
I used Star Rating module. Exactly what I was looking for. In contrast with Fivestar module, it is intended for rating only by the author of the node. Plus no dependencies. \[Thanks to @jimajamma\]

# Answer
> 0 votes
In drupal 7, you can add fields to taxonomies. Use the following steps:

1. Install the star rating formatter mentioned by @Nim, then configure
2. Can two posts have a different # of categories?

* If so, I suggest you add such a single star rating formatter field to the desired taxonomy (http://example.com/admin/structure/taxonomy//fields). Make sure the field and the taxonomy are multi-valued.
    * If not, consider adding three separate taxonomy fields.

Amnon

---
Tags: 7
---


title: Editable webform submissions

text:
# Question
Title: Editable webform submissions
Requirements for user submissions are:

1. anonymous user is able to submit form data
2. admin can delete any submission
3. admin can edit any field of any submission
4. form can contains fields which are not displayed to user, but admin can edit them
5. admin can sort and filter the submissions according to one field (date type)

There is webform module, but I do not know if it can solve all those requirements (the first one is OK, ofc ;)

# Answer
I would recommend using the Webform module and the Webform Report module.

So

1. webform module
2. webform module
3. webform module
4. when adding a field to your form there are two checkboxes at the bottom (Disabled and Private) which will do what you need it to do.
5. webform report module
> 2 votes

# Answer
Webform is not necessary for the tasks you've outlined.

Simply create a content type, and grant the Anonymous user role access to create content of that type.

To have 'hidden' fields which the admin can still edit, you can either hide those fields with CSS, deny access to them via the `#access` property through a `hook_form_alter()`, or use the Field Permissions module to restrict access to those specific fields. Note that the Field Permissions module has some performance implications.
> 1 votes

---
Tags: webforms
---


# Question
Title: Conference Organizing Distribution (COD)
Is COD shipped as a module or an entire Drupal CMS modified to handle conferencing. I can't find any straight forward documentation installing this to an existing project.

# Answer
> 3 votes
COD is a distribution that you can start a Drupal project with, but you can also take the COD features and implement them into an existing site. It's just easier to start off with COD.

---
Tags: 7
---


title: autofill from taxonomy term fields

text:
# Question
Title: autofill from taxonomy term fields
I'm trying to connect a field of a taxonomy term to a field in a content type, something like this:

Auto-Fill from on content type to another

I tried this on a node and it's working, but now I have some problems with the taxonomy term, is for this part?

```
// load node by nid
$node = node_load($nid);

```

Do I have to specify here the taxonomy? but I really don't know what to put in...

the field in content type is "field\_descrizione\_01" with empty field "field\_udm" the field with the data in the taxonomy terms is "field\_udm\_ti"

I've made this code (based on the link one):

```
/**
* Implements hook_field_widget_form_alter().
*/

function collegamento_field_widget_form_alter(&$element, &$form_state, $context) {

  if(isset($element['#field_name']) && $element['#field_name'] == 'field_descrizione_01') {
    $element['#ajax'] = array(
      'callback' => 'collegamento_auto_fill_callback',
    );
  }
}

function collegamento_auto_fill_callback(&$form, &$form_state) {

  $commands = array();

  if(isset($form_state['values']['field_descrizione_01'])) {
    // get selected item/node from dropdown list
    $nid = $form_state['values']['field_descrizione_01']['und'][0]['nid'];

    // load node by nid
    $node = node_load($nid);

    if($node) {

      if(isset($node->field_udm_ti['und'])) {
        // fill text field
        $commands[] = ajax_command_invoke('#edit-field-udm', 'val', array($node->field_udm_ti['und'][0]['value']));
      }

    }
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

```

# Answer
> 0 votes
You need to load a taxonomy term using taxonomy\_term\_load

This should get you on the right track.

---
Tags: 7, entities, ajax
---


title: Full Calendar How to add Events

text:
# Question
Title: Full Calendar How to add Events
I'm using the Full Calendar module.It's all working fine, but I can't figure how to add events to it. I've read the docs, I can see you can set up a feed to a Google Calendar which is cool,but I want to enable the user to add events right there.

# Answer
> 1 votes
After reading the documentation of the module it looks like you need create a custom content type with at least one date field and then create your view to use that content type.

---
Tags: javascript
---


title: Clickable Link to Header

text:
# Question
Title: Clickable Link to Header
I'd like to have a header with PNG files, that are clickable.

I am using Drupal 7 and Omega Theme.

In the Omega default.css, I've added the following:

```
.branding-data {

    height: 250px;
    background-image: url('../images/slideheader1-object1441486291.png'),url('../images/slideheader1-object1068949429.png'),url('../images/slideheader1-object1159417376.png'),  url('../images/slideheader1.jpg');
        background-size: 100% 23.2%,49.55% 99.6%,39.51% 100%,  100%;
        background-position: 0px 192px,292px 4px,505px 0px,  0 0;
    background-repeat: no-repeat;}

```

It adds the images to my header. One of these should be a link to another page.

How can I do this?

# Answer
answer found.

I've resolved this by adding new Blocks instead of background images:

```
<p><a href="../link to somewhere"><img alt="" src="http://www.imagelocation/image.png" style="height:150px; line-height:1.538em; width:110px"></a></p>

```

Thereby adding Images, that are links to my header.

In the CSS files i then adjusted the position and opacity.

Greets, Chris
> 0 votes

---
Tags: media, navigation, theming
---


# Question
Title: Displaying a taxonomy term (token) in a block
How do I display the name of a taxonomy term page in a block?

For example, I am on the *ww.example.com/taxonomy/term* page and I want a title block on that page that displays TERM. Is there any PHP already written for this out there?

I tried a couple of suggestions made here using contextual filters but they do not work, either the block doesn't show or the term displayed is not the one in the URL (The taxonomy has children.)

Thanks. :)

# Answer
> 1 votes
I will answer my own question here:

* Create a block view (taxonomy term)
* Add relationship: "Taxonomy term: Content using *your vocabulary*)
* Add contextual filter "Taxonomy term: Term ID" (no depth)

Configure the filter to "Provide Default Value: Taxonomy term ID from URL" below,

Check "Override title" and type "%1" in the input box

Specify validation criteria: "Taxonomy Term"

check box that has your vocabulary,

Select the Filter value type: Term ID

That's it. No need to add fields or filters. You can remove all sorting criteria.

This works even if you have several levels of children. All it does is take the term of the vocabulary that is in your URL and displays it as the page title. Also works if the page or view, or whatever is there, is empty or returns no results.

Hope that helps. :)

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


# Question
Title: Contextual filter to show only nodes of the same type
I am trying to create a View that will be a sidebar block on node pages of various content types. The View is pretty basic, just a linked title. I figured I could use Contextual Filters (what used to be Views Arguments in Drupal 6) so I don't have to set up many Views that will all be the same and just use one for all.

My goal is to get only nodes in the sidebar block View of the same type to show up on a node page. So for example on a single Blog node page, the sidebar View will only show other blog stories. However, that same View on a News content type node page will only show other News stories in the View sidebar block and so on...

I have various content types including "News", "Services" and "Blog".

*Here is what I have tried so far.*

1. Set up the basic View, showing linked titles.
2. Added a contextual filter using `Content: Type`
3. `"When the filter value is NOT available"`
* Provide default value \>\> Content id from URL
4. `"When the filter value IS available or a default is provided"`
    * "Specify validation criteria" \>\> Validator \>\> Content \>\> Checked off the content types I want i.e. Blog, News, Services.

After I save this, no data shows up on any of the node pages. I also tried playing around with other various options in the Contextual settings but to no avail. My google-foo is also failing as everything I found for something like this deals with Taxonomy and that's not what I am after here.

# Answer
I don't think you can do it with a contextual filter (without using coding). Just build a view (with block output) for each of the types and then use a filter criteria "content type = news", etc.

It's pretty easy since you can clone the view, then just override the type and change the block name.
> 1 votes

# Answer
Add path aliases by pathauto for each content type. create a view with block and to show contents or fields of contents , then add the Contextual filter : Content: type. From WHEN THE FILTERT VALUE IS NOT AVAILABLE section choose provide default value then select "Raw id from the URL" with depth 1 and check the "use path alias" selected. the view block will work fine. you shoud user views3 to get this worked.
> 1 votes

# Answer
You could provide code like this answer, though PHP is often not available for good security reasons. Ultimately, you'd want to use (or create, if one is not available) a module that provides this functionality to the contextual filters section of the views module.
> 0 votes

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


# Question
Title: How to select from a specific choice of images on content forms?
Is there a way to have a specific set of images on an add new content form.

So for example the "article" content type, when setting the fields on the form the only option for image is an upload function so the user can upload an image, I would like for there to be a selectable list of predefined images they can choose from.

Not a single default image, but an option of say 5 images.

Thanks.

(Drupal 7)

# Answer
> 0 votes
You can use

function template\_preprocess\_node

then loop in the variable you want. For each value you have selected, you could add an to your imagetype variables. Then just display the variable in you node template.

---
Tags: media, nodes
---


# Question
Title: How to access an element's value in field validation function
Drupal form api reference example for `#element_validate` accesses element's value with `$element['#value']` in field validation function:

```
function myelement_validate($element, &$form_state, $form) {
   if (empty($element['#value'])) {
     form_error($element, t('This field is required.'));
   }
}

```

But `$element['#value']` is always empty for me. indeed in `print_r($element)` there is no key named `#value` in first dimension of the array. instead, it is in somewhere like `$element['und'][0]['#entity']....`

My code:

```
function mymodule_form_alter(&$form, &$form_state, $form_id) {
   if (isset($form['field_myfield'])) {
      $form['field_myfield']['#element_validate'][] = 'myfield_validate';

   }
}

function myfield_validate($element, &$form_state, $form) {

   //print $element['#value']; exit; // returns nothing

   if (!empty($element['#value']) && !is_numeric($element['#value'])) { // always false
      form_error($element, t('Error'));
   }
}

```

Is anything wrong?

# Answer
> 1 votes
Get a value using $form\_state like as follow

```
$form_state['values']['field_myfield'];

```

---
Tags: entities
---


title: Create/Select file from select field

text:
# Question
Title: Create/Select file from select field
I have a content type **video**. It has some fileds for file meta data and a file upload field. Upload and display works fine.

Now I want to add a second video file to this content type. This file can either be uploaded or selected from a select field.

So you can select a previously uploaded file or add a new one. The select box should show all files that where added for any post with content type video.

Any ideas how to do this? I am using drupal 6.

# Answer
FileField Sources module you are looking for, it is an extension to the FileField module. The FileField module lets you upload files from your computer through a CCK field. The FileField Sources module expands on this ability by allowing you to select new or existing files through additional means, including:

> * Re-use files by an auto-complete textfield
> * Attach server-side files uploaded via FTP
> * Transfer files from a remote server (cURL required)
> * Paste a file directly from the clipboard (Drupal 7 only)
> * Select existing files through the IMCE file browser
> 2 votes

---
Tags: entities, 6, files
---


# Question
Title: Drupal Commerce: line_item field in user profile?
Im trying to achieve the *add to favorites* function, but I cant reference the commerce\_product/product\_display becose the items that are sold in my situation get customized by the user (add text, images, whatever).

I have a custom line item type called *custom*, where I added the field to handle the customization my users can do.

For the *add to favorites* functionality, i thought to add a line\_item field in the user profile, put in it the custom line items created, and when he want to buy it all I have to do is create a new line item copying the fields value and then add it to the cart.

But i have some trouble: when i try to add (for test) the line items in the user's profile page throught the standard widget, I dont get any error message but the line items doesnt get saved..

Are them bounded to commerce\_orders only?

# Answer
At the end, I ended creating a new **content type (node)**, added all the fields I need/use in the line\_item (product\_id, display\_product\_id, my fields where I store customer's customizations, etc..)

When the customer want to buy the item, I simply create the line\_item *on the fly* copying all the fields value from the node.

This allow me to handle more easly the display of those *favorites items*, becose they are just nodes: the only thing I did is to use hook\_node\_access to make those nodes visible only to administrator and to the customer who created them.
> 0 votes

# Answer
Yes, I would not use a line item reference field outside of the order entity type. You might try using an entity reference field instead with the inline entity form module for line item creation / editing.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: How to use simple modal jquery plugin to get a dialog of table?
I want to show a popup when I click on a link which is basically done by jquery plugin simple modal. In my **template.php file**,

```
function theme_name_preprocess_page(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'theme_name') .'/js/jquery.simplemodal.1.4.1.min.js');

    drupal_add_js(drupal_get_path('theme', 'theme_name') . '/js/theme_name.js');

}

function theme_name_process_views_view_field(&$vars) {
// $plus_icon is a variable defined inside this function.
 $output = "<a id='abc-modal-$nid' class='abc-modal' href='#'>$plus_icon</a>";
 $output .= "<div id='abc-modal-content-$nid' class='abc-modal-content'></div>";
 $vars['view']->result[$key]->field_field_flag[0]['rendered']['#markup'] = $output;
}

```

And in the theme\_name.js file

```
(function($) {
    Drupal.behaviors.abc = {
('.abc-modal').click(function (e) {
                var key = $(this).attr('id').replace(/^abc-modal-(\d+)$/, "$1");
                $.post(Drupal.settings.basePath + 'queue-log', {nid : key},
                       function(data) {
                           if (data) {
                               $('#abc-modal-content-'+key).html(data.html);
                               $('#abc-modal-content-'+key).modal();
                           }
                       }, "json" );
                return false;
            });

```

..... How can I get the simple modal jquery plugin working so that when I click on a link mentioned in $output variable() I get a popup displaying contents.

# Answer
Here is snippet which can be helpful for you to add open the link in simple modal plugin

```
// Get the click action on link
$('.abc-modal').click(function() {

// Get href attribute.
  var href = jQuery(this).attr('href');

 /*  Three things here
 1. Append a div to the pop-up body
 2. Keep it hidden.
 3. load the content on the link to the div(#content is the id from where you want to load the content to the pop-up) */

      $('<div id="any-id-you-want"></div>').hide().appendTo('body').load(href+' #content', function(){
        }).modal({
        overlayClose: true,
        autoResize: true,
        minHeight: 600,
        minWidth:800 ,
        opacity:80,
        overlayCss: {
          backgroundColor:"black"
        }
      });
      return false;
    });

```
> 1 votes

---
Tags: 7, javascript
---


# Question
Title: How do I enable users to have a browse button (by clicking on the image icon)so that they can upload a picture.
I added a user to my website and I gave him the permission to use blocks. I activated wysiwyg and TinyMCE so that he can add also images.

But he has a problem, when he clicks on the icon to add an image then it opens a window where u can add the image url, image description,... but there is no browse button so that u can upload a picture.

thank in advance!

# Answer
Wanted to thank evryone that tried helping me!

I found an answer on my question

go to confrigation\>IMCE\>\[profile\] and under Directories use php: return 'users/'.$user-\>name; It will create user folders in Sites\>default\>files\>users

And then the user gets a browse button to upload pictures.
> 0 votes

# Answer
You need a combination of the imce module and imce bridge module to do this

**IMCE**

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

**IMCE BRIDGE**

> Allows to use IMCE module with Wysiwyg module.
> 1 votes

# Answer
One Click Upload Module could also do this for you
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Recommended taxonomy/structure for destinations site
I am building a site with the primary goal of capturing detailed information about different destinations around the world. What is the recommended site structure for something like this using drupal 7?

**So far I envision:** my nodes would be a custom location type with the location's details expanded out using fields. I would then replicate the location hierarchy into a hierarchical vocabulary (Continent \> Country \> City, etc.) so users could search for a specific location. Should the hierarchy be flat (one vocab for Countries, another for Cities, etc.)?

# Answer
Think of Drupal as an interface to a database *(it is one)* and vocabularies, when used as the basis for fields associated with your content items, as a means for filtering for values in a table. If the terms in a hierarchy would have 1-to-many or many-to-many relationships, then you will want to have separate tables and therefore separate vocabularies so that you can use relationships to make selections. In your case, the relationship between continent-county-city is one-to-one *(with occasional duplicates such as two cities with the same name)* so a single vocabulary, using a hierarchy, makes more sense.

The Views module is basically a UI for queries to the database, so you will use Views to make selections from your table, and menus can be structured as hierarchies to present selections to users using the same multi-level logic of your location vocabulary. You may choose to create content by defining a new content type article that has a field attached to it associated with the location vocabulary and perhaps a second vocabulary to identify the type of information it contains. This second vocabulary would have terms such as geography, government, cuisine, hotels, restaurants, etc. When creating an article about hotels in Paris, you would label the two fields from the vocabularies so that the articles can be filtered accordingly. This is, in simple terms, how Drupal assembles sites.
> 1 votes

# Answer
You can create a vocabulary with a term hierarchy so that the top level is each country, the second level is states or provences, and the third level is cities and towns. With this setup the Hierarchical Select module is very effective. Another approach is to use the Address Field module with Search Api's facet search. If someone chooses Boston then the only state and country in that facet will be Massachusetts and United States. Of course, if there is a Boston, England in the database that will show but for most instances it's effective.
> 0 votes

# Answer
There is a module called Reference Field Option Limit https://drupal.org/project/reference\_option\_limit that is perfect for a structure of destination vocabularies such as Country -\> Region -\> City

For a structure like this: Country -\> Region -\> City you need to create 3 vocabularies

Region and City need to have a term referenced field on them.

The module is well documented. https://drupal.org/node/1596310
> 0 votes

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


title: Create a pager between fields

text:
# Question
Title: Create a pager between fields
I have a content type that has no limit on how many body fields it can have.

You can say that each body field represents a page in a book. You are supposed to switch page to see the next body field.

The client I am developing this site for needs to support visitors that have javascript disabled.

Is there a solution that makes it possible to add a pager for these fields using PHP?

# Answer
I managed to solve my own question.

I add a GET-parameter to the template to check what 'page' you want to view and print that out.

```
$chapter = $_GET['chapter'];
print $content['body']['#items'][$chapter]['safe_value'];

```

This is not necessarily the 'Drupal' way (Add dozens of modules to get it to work) of doing this but it works and it's lightweight!
> 0 votes

# Answer
If you can use Views, it'll be simple.

Views can provide each field's value as a row. Set it up to display fields, add your multivalue body field, filter by node id, and you can set up views pager to show one row per page.

Then, use Pathauto to create nice addresses for nodes of that type, like `/multibody/[nid]`. In views, use the same address and voila - node pages got overriden with your view. Use Global Redirect to redirect from `/node/[nid]` to `/multibody/[nid]` to make sure users will not end up reading whole node at once.
> 1 votes

# Answer
It is always better to check for contributed modules: The Smart Paging module seems like your solution.

> Provides splitting up long Drupal content into sub pages by number of characters/words or by a placeholder HTML tag for node, user and taxonomy term entities.
>
> ### Features
>
> * Smart Paging feature can be applied only to CCK fields (with text format) of node, user and taxonomy term entities. (Note: "Description" field of taxonomy term is not a CCK field.)
> * URL for sub pages is made more SEO friendly and works even for aliased URL path.
> * The user has more control over Smart Paging configuration. An option is provided at "Manage Display" page of an entity type whether to control Smart Paging display behavior during content editing or at "Manage Display" page itself.
> * Weight and visibility of Smart Paging can be controlled at "Manage Display" page of an entity type (bundle).
> * It integrates with the WYSIWYG module.
> * URL appended query argument ?nopaging=1 to display Smart Paging split pages as one page.
> * It provides additional page SEO.
> * It provides pagination with `rel="next"` and `rel="prev"`.
> * It provides support for the Token module.
> 0 votes

---
Tags: 7, entities, paging
---


# Question
Title: Change url alias for user profile pages based on role
I have two sets of users, faculty and staff, with corresponding Profile2 profiles.

I can't figure out how to get different paths for users dependent on roles, e.g, staff/userid or faculty/userid.

I've been trying with both Rules and Pathauto. Seems like it should be simple but can't get work it out.

# Answer
One way would be to create a hidden field on the user account page, and populate that field with Rules during registration. For example, for someone with the *Staff* role, give it the *staff* value; for user with the *Faculty* role, give it the *faculty* value.

Then, with the Pathauto module, define a pattern for user paths, for example *\[user:XXXXX\]/\[user:uid\]*, where XXXXX is the name of the hidden field you created, prefixed with *field*.
> 0 votes

---
Tags: 7, path-aliases
---


title: Can't change image attribute src

text:
# Question
Title: Can't change image attribute src
I want use Lazy Load jQuery Plugin. So, I must change image src to data-original path.

```
<img class="field-slideshow-image field-slideshow-image-1 image-style-slides"
typeof="foaf:Image" src="/sites/all/themes/mytheme/images/myimg.png"
width="490" height="370" alt="" title="" style="">

```

And I added this code to my template.php:

```
function mytheme_preprocess_image(&$variables) {
   if ($variables['style_name'] == 'slides') {
       $variables['attributes']['class'][] = 'lazy';
       $variables['attributes']['data-original'][] = file_create_url($variables['path']);
       $variables['path'] = '/sites/all/themes/mytheme/images/grey.png';
   }
}

```

Yes, this code add data-original attribute. But not add grey.png image to `src`

```
<img class="field-slideshow-image field-slideshow-image-1 image-style-slides
lazy" typeof="foaf:Image" data-
original="mytheme/files/styles/slides/public/slides/myimg.png" src="/sites/all/themes/mytheme/images/myimg.png"
width="490" height="370" alt="" title="" style="">

```

What's problem? How can I fix it? Thanks.

# Answer
```
function mytheme_preprocess_image(&$variables) {
   if ($variables['style_name'] == 'slides') {
       $variables['attributes']['data-original'][] = file_create_url($variables['path']);
       $variables['attributes']['class'][] = 'lazy';
       $variables['path'] = '/sites/all/themes/mytheme/images/grey.png';
   }
}

```

Regards
> -1 votes

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


# Question
Title: Render a CCK field with only the node object in Drupal 6
If I have a node object and would like to render just a given CCK field, how would I do so? I don't mean on a node template page or in a nodeapi hook, just in general.

My custom CCK field's `theme_mymodule_formatter_default` function takes an $elements array - when this function is called on the node page, $elements is an array with keys including the following:

* #formatter
* #node
* #field\_name
* #theme
* 0
* 1

...where 0 and 1 point to arrays of values in the multi-valued CCK field.

Now if I want to render this field, and all I have is my formatter function and a node object, how do I format it? If I call `theme('mymodule_formatter', $node->field_my_cck_field[0])`, what gets passed to the $elements array of my formatter function is an array with only the following keys

* 0
* 1

But rather than even having to call the theme() method, I'd like to call something like drupal\_render() that will pick the default theme formatter function. I imagine there's a way to do something like this, I just don't know how.

# Answer
> 2 votes
In D6, you can render CCK fields with:

content\_format

e.g:

```
print content_format('field_my_cck_field', $node->field_my_cck_field[0], 'default', $node);

```

See also content\_view\_field for an alternative option.

If you're in a node template and the field is set to display, you can also just go:

```
print $FIELD_NAME_rendered // where $FIELD_NAME is the field name

```

# Answer
> 2 votes
```
$field = content_fields('field_my_cck_field', $node->type);
$rendered_field = content_view_field($field, $node, FALSE, TRUE);

```

# Answer
> 1 votes
**Rendering CCK Field values in Drupal 6.x**

If you have a copy of the node and you need to output the rendered value of a field or fields, then you need to

1. Set the view mode to either 'full' or 'teaser'
2. Push the node through node\_build\_content
3. Output the 'view' key of the fields you want to render

Here's an example:

```
<?php
$nid = 12345;
$node = node_load($nid);

if ($teaser_view_is_what_you_want) {
    $build_mode = NODE_BUILD_PREVIEW;
    $teaser = TRUE;
    $page = FALSE;
else {
    $build_mode = NODE_BUILD_NORMAL;
    $teaser = FALSE;
    $page = TRUE;
}

$node->build_mode = $build_mode;
$node = node_build_content($node, $teaser, $page);

content_alter($node);

echo $node->field_myfield[0]['view'];
?>

```

# Answer
> 0 votes
The funcitons field\_view\_value() and field\_view\_field() may help you in this case?

Have a link on this article about these functions: http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way

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


# Question
Title: Using sticky-enabled Table Headers causes IE10 to crash on printing
A customer complained that printing a Views page on my Drupal 7.23 (Marinelli 7.x-3.0-beta11) Site causes IE10 to error ("Internet Explorer has stopped working"). And he's right. Works fine on Firefox, Chrome, Opera, even IE9 (but not IE 10 Browser Mode IE9). It does work in IE10 in Document Mode 'quirks'.

On investigation it boils down to using sticky table headers - use them fail, turn them off fine! I found that code in misc/tableheader.js lines 12-14 (below) 'helps' IE10 create the problem.

So, I have a crude workaround, but would prefer to do something more elegant. Anyone encountered this problem and have a workaround (short of not using IE10?).

```
$('table.sticky-enabled', context).once('tableheader', function () {
  $(this).data("drupal-tableheader", new Drupal.tableHeader(this));
});

```

Update - I guess it is naïve of me to expect someone to identify the error either in Drupal core, the theme, Views or my code which causes this problem. Certainly not without providing more information. I was hoping it might 'ring a bell' and thus satisfy my curiosity.

Can I ask for more specific advice? I found elsewhere the code below to include in template.php as a more elegant way of disabling sticky headers than no-oping the function in drupal tableheaders.js. Can anyone please suggest how I can restrict this to print requests only? Thanks Ron

```
function marinelli_js_alter(&$js) {
  unset($js['misc/tableheader.js']);
}

```

# Answer
> 0 votes
In the last paragraph you talk about hook\_js\_alter.

Basically the first part should be a name of your template or custom module, so if your module will be named `ie_workaround.module` function should look like this:

```
function ie_workaround_js_alter(&$js) {
  unset($js['misc/tableheader.js']);
}

```

It's important to do your best to have this hook executed when this element is already set by the module or theme that sets it. You can do this using hook\_module\_implements\_alter and placing your hook at the end of hooks array.

---
Tags: javascript
---


# Question
Title: Changing the field date type from 'datetime' to 'unix timestamp' without losing data
I am investigating how could I convert the date format in the 4 database tables: field\_data\_field\_article\_publication\_date from the actual **datetime** format: 2013-09-10 12:43:03 to its **unix timestamp** equivalent: 1378816983 with a minimal negative impact on data integrity of the actual articles on a production environment.

UPDATE

---

My guess scenario would be:

1. Update the field type in my feature: MYFEATURE.features.field.inc // changed to timestamp \[EASY\]
2. Alter the table field structure from 'datetime' to 'timestamp' in a hook\_schema\_alter \[EASY\]. This should be performed using db\_change\_field().

RISKY AS I CAN LOSE DATA WHEN MOVING CONTENT. I MIGHT TRY TO DUPLICATE COLUMN DATE (INTO DATE2) FIRST.

1. I NEED HELP HERE: Convert all existing dates for articles found in 'field\_data\_field\_article\_publication\_date' table to the new format unix stamp. \[NOT SURE HOW\]

Any further help?

I am interested in minimizing querying time by using MYSQL: UNIX\_TIMESTAMP(date) somehow.

My approach on No.3

loop over all 4 tables {

```
   - create a new column date2 of type: int (or datetime?)
   - copy all dates from date to date2 passing them through strtotime()
   - delete column date
   - rename column date2 to column date

```

}

That would be a start in MYMODULE.install:

```
function MYMODULE_schema_alter() {
//...loop over 4 tables
  $schema['TABLENAME1']['fields']['DATE2'] = array(
    'type' => 'int', //or timestamp
    'not null' => TRUE,
    'unsigned' => TRUE,
    'default' => 0,
    'description' => 'Field added by my_module',
  );
//…
}

/**
 * Content types using date fields should be using timestamp instead datetime
 */
function MYMODULE_update_7192() {
//define their names or get them from schema
$tables = array('TABLENAME1', 'TABLENAME2', 'TABLENAME3', 'TABLENAME4');

foreach ($tables as $table) {
       //create a new column date2 of type: int (or datetime?)
       $schema = drupal_get_schema($table);
       db_add_field($table, 'DATE2', $schema['fields']['DATE2']);
       db_update($table)
      ->fields(array(
          'DATE2' => strtotime('DATE'),
         )
         )
       ->execute();
      db_drop_field($table, 'DATE');
}
}

```

# Answer
> 1 votes
The strtotime() php function will be helpful for converting date to unix timestamp

---
Tags: datetime, database, updating
---


# Question
Title: How can I create a custom variable to use it in my layout template page?
For my new project, I'm using the brand new Omega4 theme. It comes with a lot of cool and nice features build in, so no complain about that!

But when I try to use a custom variable in my `theme-layout.tpl.php` with the `hook_preprocess_html()`, nothing is passed...

```
function theme_preprocess_html(&$variables) {
  $variables['my_variable'] = 'My New Variable';
}

```

When I try to access my new variable in my `theme-layout.tpl.php` page with `<?php print render($page['my_variable']); ?>`, nothing is appearing.

Although, if I `dpm` my `$variables` in both my template and my `html.preprocess.inc` file, the `dpm` in my template is printed first... So it looks like the template is printed first and then the preprocess hook is called.

How can I create a custom variable to use it in my layout template page?

# Answer
> 2 votes
Your approach is right but this has less to do with omega than with the order in which Drupal is preprocessing your hook. The html template hook is too late in the process, this is just for rendering the html wrapper and already assumes the existing variables. Instead, following the 1st handbook link above, use the base preprocess hook to establish your variables, ex:

```
function theme_preprocess(&$variables) {
  $variables['my_variable'] = 'My New Variable';
}

```

# Answer
> 2 votes
Looks like the problem is how you're printing the variable.

Instead of:

```
<?php print render($page['my_variable']); ?>

```

Do this:

```
<?php print render($my_variable); ?>

```

You only need the render() function if your variable is a renderable array. So you most likely only need:

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

```

---
Tags: 7, theming
---


# Question
Title: How do I redirect users from the registration page to Paypal?
Only users with a "Sign Up Code" are allowed to sign up to the website. If they provide a valid signup code, they will be directed to a sign up page where they can provide user information, and PayPal processing is used to process the fee. On completion of payment an account is created.

How can I redirect user to Paypal?
How can I check the payment is paid by user?
How can I create the account if the user paid?

# Answer
Use the Drupal Commerce module.

1. Add the Paypal payment method module; hook the login/register form to provide a different redirect page, or use the Rules module.
2. You can look at the generated transaction.
3. I would create the account anyway; set a flag, or something, for payed accounts.
> 1 votes

# Answer
My suggestion for you is to use hook\_user($op) implement it in your module, and work with `$op`.
I personally have done work like you want with that hook.
> 0 votes

# Answer
I guess using Drupal commerce will be extra load(not sure).

> Custom Way:

* Over ride drupal registration form with your custom form
* submit handler of your custom form will keep all submit value in session

> How can I redirect user to Paypal?

* You can create a custom payment script
* commerce paypal module will be helpful to see the payment process.commerce paypal module has both off-site and on-site payment options.

How can I check the payment is paid by user?

* IPN is what paypal returns after a payment(success or failure).
* You can check IPN response to get the payment status. How can I create the account if the user paid?
* If successful payment is done create user from session values using user\_save() .
> 0 votes

---
Tags: users
---


# Question
Title: Why does the default image for an image CCK field not show in a view?
I have a File/Image CCK field with a default image set and the Use default image checkbox is checked. I am rendering this field in a view- but the default image does not show for nodes where an image has not been uploaded.

How do I get the default image to show in a view?

Ive tried re-uploading the image, re-setting the checkbox, clearing cache. FYI, if I do upload an image, it does show in the view.

Any further ideas?

# Answer
> 0 votes
OK. So my solution was to use Customfield to write some PHP to check if the image field is empty. If it is, then I output some HTML to render a default image. I had to hard-code the image URL which is not ideal.

---
Tags: views, 6, media, entities
---


title: Php function to clear cache for regions

text:
# Question
Title: Php function to clear cache for regions
I made a custom module, in which I dynamically add regions. The thing is, I want to make just the region part of the cache to refresh after. So drupal\_flush\_all\_caches(); isn't the solution, since this takes too long, as well as it sometimes crashes the site.

Could anyone tell me which function I need to specifically clear the region/blocks cache? I tried all logical functions from the drupal\_flush\_all\_caches(); function. I also couldn't find the right call from cache\_clear\_all();.

Any help would be appreciated.

# Answer
You are looking for `cache_clear_all`. You want to set first argument `$cid` to `NULL`, as you want expire all your objects. Now you only need to figure second argument, `$bin`. For sure you have to clear `cache_page` bin. If it's not enough, look inside your database for `cache_%` tables (where `%` means any string, per SQL standard) to know what bins are available to you.

Last but not least, dynamic regions may be huge performance hit. Think twice if that's what you really need.
> 2 votes

---
Tags: 7, theming, caching
---


# Question
Title: Locations geocoding to province, not country
I previously asked a question but since have done much research and am getting more focused on my problem.

I have a locations cck field in a profiles 2 profile. Here, I get users to select just countries (no cities or provinces) and they are geocoded to points and displayed on a user specific map. Many of the countries are not accurate. I have discovered the locations are being geocoded by their province code. Example: the country code is being ignored and it is selecting a province code.

I had a problem that Barbados was being displayed in Germany. Barbados has a country code of "BB", but I found that the point was being displayed in Brandenburg Germany, the province code "BB". Every wrong point can be explained this was but 3.

I have the geocoding setup to be at a country level accuracy. I dont think its a config problem and I have yet to find any other people with this problem.

Any ideas on what to do?

Thanks

# Answer
> 1 votes
The problem is not actually with that snippet of code in \_google\_geocode\_flatten(), but is just a result of google's geocoding algorithms.

For example, your search for BB finds 2 results, Brandenburg Germany & Barbados, however google puts the former as the first result, possibly due to popularity of searches or something.

See http://maps.googleapis.com/maps/api/geocode/json?address=bb&region=bb&sensor=false

The solution I can see is to also pass in the component param when requesting from google geocoder, which allows you to specify specific parts of the address in addition to the full address string.

See https://developers.google.com/maps/documentation/geocoding/#ComponentFiltering

I have posted a patch back to your issue on drupal.org

# Answer
> 0 votes
Looks like each geocoding service is responsible for 'flattening' the address to a string, so that's where you need to look. The default one included with Location is the Google Geocoder. In its `_google_geocode_flatten()` function you'll find this interesting piece of code (the comment being especially interesting):

```
// @@@ Fix this!
if (substr($location['province'], 0, 3) == $location['country'] . '-') {
  $address .= substr($location['province'], 3);
  watchdog('Location', 'BUG: Country found in province attribute.');
}
else {
  $address .= $location['province'];
}

```

So I'm going to take a guess that's where the problem is.

As for fixing it, I'd strongly recommend liaising with the module maintainers on Drupal.org, as it looks like this is a known bug.

---
Tags: google-maps, location
---


# Question
Title: How do I override the username in forum views?
I have created a module that overrides the real user name with the string "Anonymous" when a node is displayed. I use hook\_node\_view() to do this. This works fine.

However, to keep the user truly anonymous, I need to override the display of the user name in other contexts as well, for instance in the views of last post in a forum, or in the forum topic list produced by the core forum module (Drupal 7).

The screenshot below illustrates the problem. It shows a forum post by a user "bob" that is supposed to be Anonymous. As shown, "bob" is not Anonymous in the first two views, only in the last view of the node itself.

What I am looking for is a hook (or something else if there is no explicit hook for this) that let me override the display of the user name in these views produced by the core forum module.

# Answer
> 0 votes
Took me more than two months to figure this one out, but the answer is obvious once you know it.

Yes, there is an explicit hook for this. It is named: hook\_username\_alter.

D'oh!

---
Tags: hooks, nodes
---


title: Visibility rules if field is filled in

text:
# Question
Title: Visibility rules if field is filled in
We made a visibility rule to display a field when a second field has been filled, and display another field when the second field is empty. It works well, but since we updated Ctools and some Drupal modules, it gives false output.

What I did is:

* Adding a field with a visibility rule to display the field based on another field value (I left the value empty to display the field when it is empty.)
* Duplicating that field, and adding the same visibility rule, for which I then selected "Reverse" to display the field when it contains any value

The problem is that the visibility rule doesn't apply for the case when the field is empty, but it works well when the field is not empty, even if I disabled the second rule.

How does the plugin (for the visibility rule) know about empty and non empty fields?

I know that it could be solved with PHP code, but I need to know what I am doing wrong.

# Answer
> 0 votes
Thanks guys the problem wasn't caused by visibility rules.

We found an issue with image actions module update not ctools

# Answer
> 0 votes
Probably it is the difference between if `field['und][0]['value']` is set or not. Even if `field['und][0]['value']` is empty, it's different with not instancied field.

Try a default value on this field and add an other visibility condition on this default value

---
Tags: chaos-tool-suite, blocks
---


# Question
Title: Where should I place .htaccess to take effect in a particular site?
We have an Apache web server that contains several Drupal 7 installations. Where should I place a .htaccess file in order for its contents to take effect on a particular website?

I tried putting it here `/opt/apache/var/www/html/drupal-7.19/sites/thewebsitename` but it didn't work.

# Answer
> 3 votes
If you have a multi-site Drupal installation (ie. folders other than 'all' and 'default' in your `/opt/apache/var/www/html/drupal-7.19/sites/` directory), then you cannot have a separate .htaccess file for each site, and must place your changes in the common .htaccess which should already exist in `/opt/apache/var/www/html/drupal-7.19/`. Note that as these changes will apply to all of your multi-sites, you need to ensure your rules don't break sites you're not interested in.

If you have a more traditional installation of one site per one Drupal instance, then you'll still be modifying the same .htaccess file in `/opt/apache/var/www/html/drupal-7.19/`, but don't have to worry about breaking other sites.

---
Tags: .htaccess
---


# Question
Title: Unable to add new OpenID identity in Drupal 7
I have been using OpenID authentication in Drupal 7 for quite a while, using an myopenid.com identity. Now, since myopenid.com has announced that they are going away, I want to add a new OpenID identity to my account.

However, I am not able to add another identity. When I try to add another identity, the browser starts loading a page, but then stops loading. I am not taken to the provider's login page, whether or not I am logged in to the provider's site. (I am already logged in to my Drupal 7 site -- I am adding the new ID from my profile's OpenID Identities tab.)

When I manually go back to that OpenID Identities tab, the myopenid.com identity is there, but the new one is not.

There is nothing in the Apache error log or access log suggesting what is going on.

Any idea how to debug what is going wrong?

# Answer
Thanks to Mołot's comment, I was able to figure it out. The problem was the administrative overlay.

Using the Chrome Developer Tools console (Chrome Menu/View/Developer/Developer Tools) I was able to see the request history. The last request included:

```
referer:http://mysite.com/user/1/openid?render=overlay&render=overlay

```

The response from Google also contained a header that looks like an error, although it may not have been relevant:

```
p3p:CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."

```

I don't know if the referrer header was the actual problem, or if it just reflected a problem caused by including "render=overlay" in the request going on in the background between my server and the OpenID provider. In any case, by turning the administrative overlay off (Admin/Modules/Core/Overlay), I was able to add and use my new OpenID. It worked for both Google and Yahoo.

I would also add, as noted elsewhere, the URL to use to set up the OpenID for Google is:

```
http://www.google.com/accounts/o8/id

```

That initially confused me because that does not appear to be a unique ID. However, using that ID both to add the OpenID for Drupal, and to log in using OpenID, works. The string stored as my "OpenID" is different, and has what appears to be a unique identifier, but the user never has to enter that long, unique string.

Not only did the Administrative Overlay prevent the OpenID from being added, it also prevented me from seeing the error message when I used the wrong string to add the OpenID.
> 2 votes

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


# Question
Title: Boost not caching anything. is_cacheable always set to false
I have the problem that my installed and correctly (I hope so) set up boost module isn't caching anything. Turning on the debug mode, it always says is\_cacheable = FALSE for every page - which would explain the behaviour.

There is no "is\_cacheable\_reason" flag set, but I found the part of the boost.module file where is\_cacheable is set to false for me:

```
...
elseif (!drupal_page_is_cacheable()) {
$_boost['is_cacheable'] = FALSE;
return;

```

}

Its line 276 from the boost.module file - right in the function boost\_exit(). drupal\_page\_is\_cacheable() seems to be a native drupal function, but I don't know where drupal decides that no page should be cached.

# Answer
> 1 votes
Looking at drupal\_page\_is\_cacheable, it appears that there are 4 functions that use the cacheable flag. `drupal_page_get_cache` and `drupal_page_set_cache` are to be expected, and use it simply as a flag. Unfortunatley, `drupal_session_initialze` and `drupal_set_message` set cacheable to false.

In session initialize, if a user has visited your site at all and has a session cookie and any session variables are set then the page will not be cached. Similarly, if you set any messages during the page generation, it will also not be cached. While the former may have benefit, the later (IMO) is completely ridiculous.

Also, this issue on Drupal.org, but that really only addresses the first issue of session variables and cookies.

... commenting out the 'return' fixed the issue for me. 404 and 403 still not cached and you can specify other pages to be excluded in the boost settings page.

---
Tags: caching
---


# Question
Title: Page Manager and Panels settings — where do they live?
I'm continuing my quest to make every piece of common site architecture into something that can be displayed in a View. Right now I'm on Panels panes and Page Manager pages.

I have a site that is most assuredly making use of Panels panes and Page Manager pages on the node display, node edit form, and a few other places. However, when I inspect `page_manager_pages`, or any other table in the DB that begins with `page_manager_` or `panels_`, the table appears to be completely empty. (I'm using PHPMyAdmin, and it gives me that red cursor with an 'x' in it.)

I haven't been able to find an API call that lists all Panels panes, Page Manager pages, or other relevant data either. And when I have looked through the sites I own to see ones that *do* have something in the `page_manager_pages` or `panel_panes` tables, it seems to be much less than I would expect. (E.g. a large site that is **heavily** themed with Page Manager and Panels shows up in the db with just two entries in the `page_manager_pages` table.)

I've even combed through the SQL queries that Drupal does when I click "enable" on a disabled Page Manager page (e.g. the node edit form, the node display), but haven't found anything that looks meaningful.

# Answer
> 0 votes
This ended up requiring API calls, since Panels and Page Manager definitions can live in code or in the database.

First I got the tasks with `page_manager_get_tasks()`.

This gave me a list of tasks, which appear to be high-level Page Manager stuff. My Workbench, Node add/edit form, Node template, User template, User edit form, and Custom Page were the tasks.

Custom Page had subtasks that included all my custom pages, so I did `page_manager_get_task_subtasks()` on each tasks that had subtasks, and then `page_manager_load_task_handlers()` on each subtask. Within the handlers, there is information about the Panels and other objects that go on that page.

---
Tags: panels, chaos-tool-suite
---


# Question
Title: specific htaccess in some sites on multisite
i have several drupal sites running as multisite (same core + modules code), just moving to shared hosting

Some sites should be kept password protected. (AuthType Basic)

Is there a way to tell in .htaccess in drupal root that for certain HOSTNAME's
the password section should apply or at least a new .htaccess (in site subfolder) shall override .

# Answer
Apache does not support this. You can use REWRITECOND to conditionally match rewrite rules, but there is no way to conditionally hide AuthType directives, except to separate the Drupal sites into different Drupal root folders. Putting an .htaccess file in the sites/mysite folder won't work, because settings.php is read via php, not served up by the webserver.

Use Drupal features to protect your content. If you turn off the "Access Content" permission for anonymous users, then a Drupal login will be required to view any page; all others will get "Access Denied".
> 1 votes

# Answer
The Shield module allows you to store HTTP access settings in the database on a site-by-site basis. Just enable the module for the sites you want protected.
> 1 votes

---
Tags: multi-sites, .htaccess
---


# Question
Title: Photo-swipe is not loading in my website
I'm using drupal -7 with mobile\_jquery(https://drupal.org/project/mobile\_jquery) as theme

and PhotoSwipe .

The PhotoSwipe is not working in the gallery page.When we click on the thumbnail ,the image will not load first time and show the blank screen with below message

> undefined

and we can see path of the image in the address-bar.***When we refresh the page the PS will work.But something missing ...*** website: http://www.w3qatar.info/aldarmobi .

***`properties >> please click on any property and you can find more images >> Click on any image to see the PS.`***

I don't know what is the reason for this.Please help me to solve this issue.

Please suggest me any other image gallery module which works on ios,android devices.

# Answer
I am using the Juicebox module in my Drupal 7 site for swiping. With my iPhone 4, it is working super. I have tried other solutions, without luck. The free version of Juicebox allows you to place 50 pics in a box.
> 1 votes

---
Tags: media, javascript
---


title: Mobile Tools or Media Queries?

text:
# Question
Title: Mobile Tools or Media Queries?
I have always used CSS media queries on past sites for a responsive layout. Recently bumped into Drupal Mobile Tools dev.7 and liking it thus far. Trying to understand the purpose of it besides another method for a mobile site.

**CSS Media Queries:** Great if desktop / mobile sites are similar in functionality. Easy.

**Drupal Mobile Tools:** Need to load a different theme for major desktop/mobile site differences. Contextual layout. Exportable configurations.

Mainly looking for what is best practice out there. Can too many media queries put a major strain on a website with tons of hits or is Mobile Tools bit of overkill for any small/media site?

Thanks.

# Answer
> 1 votes
What about using Adaptive Theme or sky (based off the first)? These are designed with multiple screen sizes in mind and you have a community of folks to share knowledge with.

---
Tags: theming, mobile-tools
---


# Question
Title: When to use custom nodes? How to display custom fields?
I am a newbie to Drupal. I have a custom content type **blog\_post**, with some custom fields, like **subtitle**.

I have the following two divs, which I want to render for this **blog\_post** like that:

```
+--------------+--------------------------------+
| 9 Sept 2013  | Good weather on the West coast |
|    2013      |           (title)              |
|   (date)     | Winds are blowing hard in NY   |
|              |          (subtitle)            |
|              | According to the Department... |
|              |          (content)             |
+ -------------+--------------------------------+

```

My solution: amend **node.tpl.php** like that:

```
<aside>
    <?php print $date; ?>
</aside>
<article>
  <a href="<?php print $node_url;?>">
    <?php print $title; ?><br />
    <?php print $subtitle; ?>
  </a>
  <?php print render($content); ?>
</article>

```

How do I pull $subtitle from the database? Best way I found so far, looks somewhat ugly:

```
<?php
  print $field_subtitle[LANGUAGE_NONE][0]['value'];
?>

```

# Answer
> 2 votes
Custom layout options can be managed in numerous ways. Just a few of the options:

1. Use Display Suite (KyleTaylored's answer).
2. Use separate node templates and render the fields you're after manually via `field_view_field()`. See Rendering Drupal 7 fields (the right way).
3. Use a single node template with conditional statements based on `$node->type`
4. Use CSS to extensively modify layout
5. Modify the node content through a hook, such as `hook_node_view_alter()`.

These days I prefer to go with option 1, as it does what I want 99% of the time. You can alter displays on a per-entity (node) and per-view (full, teaser, etc. - you can create custom views, too), so it's quite flexible.

Option 2 is another alternative that can be fairly clean. Drupal's theming/rendering engine looks for multiple template "suggestions" (variations of the file name), and picks the first option found. The template suggestions can be modified and expanded in a pre-processing function/hook. You could add suggestions based on any data you have available. I have an old blog post (Extending Drupal Templating) which provides examples of how to do this for Drupal 5 and 6, but the same principle applies to Drupal 7.

Option 3 is simple enough to not need an explanation, but unless you're adding very small changes, (different layout is not a small change) I'd advise against it.

Option 4 will obviously depend on your markup. A lot can be done with CSS, but drastic layout changes are rarely a good idea.

Option 5 is another extreme. Useful for tying in to the rendering process at a fairly early stage, but also not something I'd use in your case.

# Answer
> 4 votes
Best suggestion, don't start doing custom template overrides. With site building tools like Display Suite, you no longer have to continue writing custom node templates. By using Display Suite, you can set a view mode you defined to a two-column template, and then set the fields you'd like into each region.

You can see in the example below how easy it is to achieve something like this without having to build custom templates. Of course if you need to do anything extra, you can always customize on top of that.

---
Tags: views, theming, nodes
---


# Question
Title: Is there a way to alter a node save confirmation form?
I would like to add a confirmation form that is presented to a user on node update/delete operations triggered through the UI.

Specifically, I would like the form to present more than two choices for the user. i.e. instead of Submit/Cancel I would Option A/Option B/Option C.

Is this possible?

# Answer
Yes. I was writing a huge response before regarding confirm\_form in Drupal 7. I recommend you google and look at the examples module for confirm\_form usage.

In short you probably want to:

* use hook\_form\_alter to override the #submit or #action (or pre-pend to the list) the form will send to.
* then you want to show a new form -- just like confirm\_form does and do more logic in your custom confirmation form submit handler.
* then redirect wherever using `drupal_goto` for instance or `$form['#redirect']`.

This may sound vague -- but the Form API can do all of this. You just have alot of learning to do. I have used confirm\_form. I've made workflows for 8 Node forms to wizard through 8 Node add forms; and even made a "login" form fake login people from a login form completely overridden with a dropdown list of students on a Test server (to mock out users) using hook\_form\_alter().

Drupal can do all of this -- you just have to read the API and look at examples and experiment until you get what you want.
> 3 votes

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


# Question
Title: How to show a block only on the nodes which the user created
I have a block that I only want to display in nodes that the current user created. What's the best way of going about this?

**Thoughts so far**

I can access `$user` (and therefore the UID) anywhere, so I need to compare this to the node author UID. The only problem is finding a place where I can also pull in the current node information to find out it's author.

I really don't want to put php in a block (bad practice and all) and I couldn't see where I'd do this in *context*.

If I can't find a better way then the backup plan is to create an automatic field on node creation which contains the authors UID, then use this in page.tpl.php to set a class which will apply display:node to the block whenever the author UID =! user UID.

**EDIT: Solution**

The block I was trying to effect was in a custom module, so I took Yuriy's code and put into the modules hook\_block\_view. The result was this:

```
function mymodulename_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'mymodulename_form':
            if (preg_match('#node/([0-9]+)#', $_GET['q'], $matches)) {
              if ($node = node_load($matches[1])) {
                global $user;
                if ($user->uid !== $node->uid) {
                  $block['content'] = array();
                } else {
                  $block['content'] = drupal_get_form('mymodulename_form');
                }
              }
            }
    break;
  }
  return $block;
}

```

I think this is what's going on:

`preg_match` and $\_GET are used to take the node path from the current page. This returns: "node/xx". This is then used to load the correct node which is then matched against the global UID. An `if` function then either empties the block content or fills it.

# Answer
I would implement hook\_block\_view\_alter() and remove the block's content (resulting in hiding the block). Something like this (untested):

```
function hook_block_view_alter(&$data, $block) {
  if ($block->module == 'somemMdule' && $block->delta == 'someDelta' && preg_match('#node/([0-9]+)#', $_GET['q'], $matches)) {
    if ($node = node_load($matches[1])) {
      global $user;
      if ($user->uid !== $node->uid) {
        $data['content'] = array();
      }
    }
  }
}

```
> 0 votes

# Answer
I don't understand your reluctance to use php in a block, particularly in the block visibility settings.

If you set the block to display only on the pages where the following php code returns true, then the following, or something similar, should do the job for you.

```
<?php
global $user;
$node = menu_get_object();
return ( $user->uid == $node->uid );
?>

```
> 0 votes

---
Tags: 7, blocks, users
---