title: How to convert xml into array in php?

text:
# Question
Title: How to convert xml into array in php?
I want to convert the XML structure below into a PHP array.

```
<BillingApplyRq>
    <FatoryId>xxxxxx</FatoryId>
    <TotalNum>2</TotalNum>
    <Records>
        <Record>
            <ReturnMsgNo>1</ReturnMsgNo>
            <ReturnMsg></ReturnMsg>
            <TradeSeq>00001</TradeSeq>
        </Record>
        <Record>
        <ReturnMsgNo>1</ReturnMsgNo>
        <ReturnMsg></ReturnMsg>
        <TradeSeq>00002</TradeSeq>
        </Record>
    </Records>
</BillingApplyRq>

```

Does anyone know how to do that?

# Answer
> 1 votes
Although this is not related to Drupal but anyway you must convert from XML to array by using the sample code below from PHP.net

```
$simple = "<para><note>simple note</note></para>";
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "Index array\n";
print_r($index);
echo "\nVals array\n";
print_r($vals);

```

Ref: xml\_parse\_into\_struct — Parse XML data into an array structure

---
Tags: input-formats, theming
---


# Question
Title: Prevent password reset urls from being redirected at login
I'm using the following code to redirect users at login (Drupal 6):

```
function hook_user($op, &$edit, &$account, $category = NULL) {
switch ($op) {
    case 'login':
        if (_cns_user($account)) {
            unset($_GET['destination']);
            unset($_REQUEST['destination']);
            drupal_goto('user/'. $account->uid .'/training', NULL, 'steps');
        }
        break;
    }
}

```

The problem I have is that this doesn't allow for users to be redirected to the password reset page (user/reset/) when needed. Is there a way to prevent the reset url from being redirected? Thanks in advance.

# Answer
> 1 votes
The simplest way would probably be to just test for the path, which you can get access to via `arg()`. Something like this would do the trick:

```
function hook_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    case 'login':
      if (_cns_user($account) && !(arg(0) == 'user' && arg(1) == 'reset')) {
        unset($_GET['destination']);
        unset($_REQUEST['destination']);
        drupal_goto('user/'. $account->uid .'/training', NULL, 'steps');
      }
      break;
  }
}

```

---
Tags: users, redirection
---


# Question
Title: Auto import Facebook page photos as nodes for views display
I have some experience using feeds and views, and I've looked at a few modules designed to integrate Drupal with Facebook. But I'm unable to figure out how to set up an importer to automatically pull Facebook photos from a page and turn them into nodes. I'd also like to map three fields for views display: image, description and FB album title to Drupal taxonomy term.

Suggestions on how best to approach this?

# Answer
> 2 votes
JSON parser did the trick with a feeds importer properly mapped. Once I figured out how to get the data from Facebook, it was really just a matter of configuring the importer properly with the right expressions. I was pleasantly surprised to find that I could get the data without any token because the data comes from a public page, rather than a private profile. The url structure: http://graph.facebook.com/\[album id\]/photos.

---
Tags: views, feeds, social-network
---


# Question
Title: How do I display an entire node content on the front page?
How do I display an entire node content and not just some intro text on the front page? It seems anything I promote to front page, is also truncated and I can't figure out how to turn this off.

# Answer
> 14 votes
The easiest way is to create a view.

Follow these steps:

* Download, extract the Views module
* Enable the Views UI module and accept enable the modules that provide the dependencies
* Go to the views admin page (admin/structure/views)
* Enable the frontpage view (click the link)
* Edit the frontpage view (click the link)
* Under the format heading, there is an option "show" click the teaser link
* Change the view mode option to full and untick the show links checkbox
* Click the Apply (all displays) button
* Click the save button
* Visit the site information page (admin/config/system/site-information)
* Change the default front page URL to "frontpage" (without the quotes)
* Click Save configuration

It show now just work.

# Answer
> 10 votes
Enter your site configuration to set **Default front page** and set the node path (node/\[id\]) as path to default front page.

# Answer
> 5 votes
Consider Using Panels and Views (as pcambra suggest). Here are some tutorials:

With Panels and Views your limitation is only your imagination

# Answer
> 2 votes
One solution would be to turn on the "Emulate Frontpage" View in views.module and modify it to show the full node, not only the teaser.

# Answer
> 1 votes
the front module might work for you too. There is an "alias" option that you could use to show a certain node page as the front page.

# Answer
> 1 votes
Depends on the complexity you want, but probably the Default front page solution proposed by Shoaib is the simplest one.

You could also use panels for this if you're already using it if you're not, it's not worthy to install it just for the frontpage, same thing happens with the Views solution.

# Answer
> 0 votes
From the admin menu go to **Structure \> Content Types**. From the list select **Article** and then click **Manage Displays**. Now at the top you will see 2 items **Default** and **Teaser**. Select "**Teaser**" and change the Body **Format** from **Summary or Trimmed** to **Default**

# Answer
> 0 votes
Bas G's solution is good, but if your front page is a "page" and not an article, you have to change to **default** under

```
/admin/structure/types/manage/page/display/teaser

```

but then there still is a **"read more"** link on the bottom of the front page content, even if you see the whole content. I managed it it by going to

```
/admin/config/system/site-information

```

and setting there the direct link to the frontpage node under **Default front page**, like this

```
http://www.example.com/content/<node_title>

```

---
Tags: 7, nodes
---


# Question
Title: How do I handle multiple arguments with `hook_drush_command()`?
I have to implement a drush command with multiple arguments. How should I handle them in `hook_drush_command()`?

# Answer
> 1 votes
In the 'official' `make-me-a-sandwich` command:

```
function sandwich_drush_command() {
  $items = array();

  // The 'make-me-a-sandwich' command
  $items['make-me-a-sandwich'] = array(
    'arguments' => array(
      'filling' => 'The type of the sandwich (turkey, cheese, etc.). Defaults to ascii.',
    ),
  );
}

```

Arguments is clearly an array. Add new keys to it.

---
Tags: drush
---


# Question
Title: Is is possible to access views from a module file?
I have created a view in drupal. My question is, is it possible to access the contents of the view or value stored in the view from the module file.. Need any details or code plss comment.

# Answer
You can use drupal function
`views_get_view_result($name, $display_id = NULL)`

**$name** : name of the view
**$display\_id** : On the edit page for the view in question, you'll find a list of displays at the left side of the control area . e.g. 'MASTER', 'Page'

This function will return **An array containing an object for each view item.**
Reference :https://api.drupal.org/api/views/views.module/function/views\_get\_view\_result/7
> 3 votes

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


# Question
Title: Custom Date Format Not Available to my Date Field
I'm sure I'm missing something super simple, but for some reason, my date field that I've created cannot make use of the "custom format" option in Views. I'm using D7 7.22 and the Date Module, 7.x.2.6

I've noticed that the field that I created is labelled differently than a normal date field which is "content: post date".

Mine is labelled, "Choose how users view dates and times"

The regular field is labelled simply "date format"

I've created a content type that has a date field with day, month, year, and time specified for each node. It doesn't matter which formatter I select - plain, time ago, date and time - I do not have the option for a custom format for this field and I'm baffled. I can see the custom formats I created at admin/config/regional/date-time but no option for a custom format in Views.

I need to reformat the output of the values in contained in that field so that I can theme it appropriately, and will roughly be following this: http://highrockmedia.com/blog/theming-views-post-date-drupal-7-date-parts

Any ideas on why this would not be an available option? I've cleared all caches, removed and recreated the field - everything I can think of but I can't find anything on why I cannot use that field in Views.

You can see the difference in this screen grab: http://bit.ly/1cGQMkY

Thanks in advance

# Answer
> 2 votes
They seem to be build differently, you really can't do that I guess. But do this:

Add a new format at admin/config/regional/date-time/formats. Then add a new Date type at admin/config/regional/date-time and here select your new format. Then you can select this in the view.

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


# Question
Title: How do I add images in pager for views nivo slider?
I am using Views Nivo Slider for displaying a slideshow of banner images on my site. And i wish to show the pager in the form of images. I tried using Image pager in views slideshow and it worked there. But there are no settings specific to adding an image preset for it. I was able to add numbers instead of bullet. Please suggest a way to add image particularly.

# Answer
> 0 votes
The module(views Nivo slider) does not support using images as pagers by default. If you want such functionality you would have to write a custom module to extend the views nivo slider module. So I would advise you to go back to using the views slideshow module to achieve that. Even the original plugin created by nivo slider itself does not support such functionality. See demo site

---
Tags: 7, views
---


# Question
Title: Why do I get the following errors when I install themes and modules on the website locally running on my Mac?
I'm just up and running and everything looks OK. Developing locally on a Mac with XAMPP, I have changed httpd.conf to suite my user and group, and FTP is OK. Now I want to install a new theme using "Install from a URL," but when I paste in the URL for my theme and click install, I get the following error:

> Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-cache-26f2422c/responsive-7.x-1.6.tar.gz) \[function.unlink\]: Permission denied in drupal\_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color/base.png) \[function.unlink\]: Permission denied in drupal\_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color/color-preview.png) \[function.unlink\]: Permission denied in drupal\_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color/color.inc) \[function.unlink\]: Permission denied in drupal\_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color/colors.css) \[function.unlink\]: Permission denied in drupal\_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color/preview.css) \[function.unlink\]: Permission denied in drupal\_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: rmdir(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color) \[function.rmdir\]: Permission denied in drupal\_rmdir() (line 2361 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/css/layout.css) \[function.unlink\]: Permission denied in drupal\_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/css/responsive-style.css) \[function.unlink\]: Permission denied in drupal\_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: rmdir(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/css) \[function.rmdir\]: Permission denied in drupal\_rmdir() (line 2361 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/favicon.ico) \[function.unlink\]: Permission denied in drupal\_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
> Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/flexslider.css) \[function.unlink\]: Permission denied in drupal\_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).

The file permissions are already set to 777.

# Answer
Go to **/admin/config/media/file-system** and change the 'Temporary directory' from /tmp to tmp
> 2 votes

---
Tags: installation
---


title: Similar module to splashify?

text:
# Question
Title: Similar module to splashify?
I'm looking for alternative modules to create splash pages, similar to this: https://drupal.org/project/splashify

This is the only one I've found but I'm sure there should be more of this.

To make the search I used the "splash" keyword.

Does anyone know any other?

The idea is to popup a "colorbox" frame when the user log in, then the user would be able to check "I don't want to see this information anymore?

# Answer
> 3 votes
Try out tinybox simple splash

> TinyBox module uses TinyBox, a lightweight and standalone modal window script. The main purpose of this module is to provide Splash Screen/Window as simple as possible.

---
Tags: 7
---


# Question
Title: Why does Views PHP give me NULL for $row->path?
I have a views block to display only the titles of some few nodes. Titles linked to the single node. I want to have a CSS class `.active` added to the title's links when the linked path matches the actual called path. As mentioned in the comments below, I didn't got that class by default.

So I added a `Global: PHP` field right after I added and excluded a `Content: Path` field to access `$row->path` in the `Global: PHP`'s output code field. But `$row->path` seems to be empty. `dpm($row)` gives me a `path: NULL`. `Content: Path` displayed gives me the right paths. But where's the path gone in the PHP field??? When was the moment it got nulled?

I still managed to do what I want with the `nid`. Though without the beautiful alias paths I'ld like to have.

# Answer
Found a workaround for using the alias path in Views PHP: \[SOLVED\] Views PHP $row-\>path showing Null

```
drupal_lookup_path('alias', 'node/' . $data->nid)

```

Question still unanswered. Will report issue.
> 2 votes

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


# Question
Title: How to add tri-state checkboxes to form created with Form API?
I want classical tr-state checkboxes, like the ones on the picture below:

Checked would mean "true for node and all it's children", intermediate "true for some children, leave it as it was" and uncecked "false for all children". Desired values (but that's not a must) are:

* checked - `TRUE`
* unchecked - `FALSE`
* intermediate - `NULL`

Is there a module to provide control like this? Or to provide intermediate value for regular checkboxes?

I need it for Drupal 7, but I'll gladly welcome answers for 6 and 8 too.

# Answer
From what I understand, the `indeterminate` property of a checkbox is purely a visual thing, and also cannot be set with HTML, which in turn means that you won't be able to use the FormAPI or create an indeterminate element without JavaScript.

Chris Coyier sets out some example situations though in this blog post, but an important quote is below (in case the post goes down).

> Here are some things to know about indeterminate checkboxes:
>
> **You can't make a checkbox indeterminate through HTML.** There is no indeterminate attribute. It is a property of checkboxes though, which you can change via JavaScript.

I should imagine you could probably use `Drupal.settings` to your advantage here though, and run the check server-side for "*true for some children*", and pass an array of ID's through to `Drupal.settings`. Following that run something *like* the following in a Drupal behaviour:

```
 // This is an array of IDs
 trueForSomeChildren = Drupal.settings.myModule.trueForSomeChildren;

 $(trueForSomeChildrenjoin(', ')).attr("indeterminate", true);

```

Howeverm I don't think there's an already-built module to do what you want. There is a patch here for the FacetAPI where they allow for `indeterminate`, but it kind of follows this example.
> 3 votes

---
Tags: forms
---


# Question
Title: When programmatically adding views, what is a more efficient way to add them other than include them in mymodule.views_default.inc?
I have written a module that writes views programmatically, and my mymodule.views\_default.inc file is enormous. Currently there are 150 individual views, and 780 will be the target.

But, even with the test group of 150 several things are happening.

1) when enabling the module via drush, php memory usage goes through the roof. It climbs into the gigs (TOP command), but it finally loads.

2) but, when I then try to view the site I get WSOD, and the top command shows apache2 climbs into the gigs for memory usage until the Apache process actually crashes. Of course there is not enough memory to load it, and it's of course unrealistic to put php memory limit in the gigs.

What's going on here? How is the code in mymodule.views\_default.inc actually handled once it's loaded? Where is it being loaded to? Is it loaded into memory for each Apache process? If I can actually get it loaded will my Apache process footprints actually shrink back down to something normal?

Can this file be divided up into individual files, and would this even help? Is it better to someway put them into the database instead of using the file at all?

In other words, how can I get almost 1000 views loaded and continue doing business as usual?

note, if you are curious, this is a census data project. I don't want to use filters or arguments as each set of data needs to to have its own individual page URL and other criteria unique to that data set.

# Answer
I'm not 100% sure if it'd help performance-wise, but it is possible to separate the Views into different files. In your case, this is probably useful anyway as that's a LOT of Views.

If you create a folder in your module called "views" (or whatever you want), then you can just add the following to your implementation of `hook_views_default_views`.

```
function MYMODULE_views_default_views() {
  $files = file_scan_directory(drupal_get_path('module', 'MYMODULE'). '/views', '/.view/');
  foreach ($files as $filepath => $file) {
    require $filepath;
    if (isset($view)) {
      $views[$view->name] = $view;
    }
  }
  return $views;
}

```

**DISCLAIMER/CREDIT:**

This code was taken from this blog post, and this comment, so make sure you pop over there and say thank you :)
> 2 votes

---
Tags: views, performance
---


# Question
Title: What does cron error "exit status 4" mean in syslog? (Ubuntu)
I've never seen this before, my Status Report page says the last cron run was 35 minutes ago at 10:35 today. So I went to watchdog logs and could see that `Cron run completed` at `10:30`.

I've set the cron to run on `0` and `30`th minutes of every hour, so twice per hour using `sudo crontab -e` so it's using the root user's crontab with the following command (cron key intentionally removed):

```
0,30    * *   *   *     wget -O - -q -t 1 http://localhost/cron.php?cron_key=

```

I'm not using the `cron.module` aka `poormanscron` in D6

I've manually run the cron and it updated the Status Report page after that.

What could cause this weird behavior? I'll admit that I haven't tried flushing the caches, but could caching be the cause of this? Or is there something more sinister?

---

I've dug around in syslog and found an error relating to the cron, but I have no idea what this means (cron key intentionally removed):

```
Aug 16 10:30:01 drupal-1 CRON[31372]: (root) CMD (wget -O - -q -t 1 http://localhost/cron.php?cron_key=)
Aug 16 10:30:01 drupal-1 CRON[31370]: (CRON) error (grandchild #31372 failed with exit status 4)

```

I can see the `grandchild #31372` is referring to the first line `CRON[31372]` but what does `exit status 4` mean?

I just wanted to also let people know that the cron has run without any problems so far afaik. But it could be that this is the first time I've noticed this as well.

# Answer
> 2 votes
Ok, I'm such an idiot sometimes.

I've edited the `.htaccess` file this morning to redirect without `www.` to `www.domain.com` and that has caused my cron going to `localhost` to be redirected to `www.localhost` which caused the cron to fail. /facepalm

But to answer `exit status 4`'s meaning for `wget` according to this page it means `Network failure` (Kudos to @Clive)

---
Tags: 7, cron, status-messages
---


title: Handle file requests

text:
# Question
Title: Handle file requests
I'd like to be able to intercept calls to files (.pdf for instance) in order to run some custom code before the user accesses/downloads the file, and add a cover page accordingly.

From what I understand this can't be done by Drupal alone, and requires some server-side configurations as well. Could anyone guide me towards a solution and/or the hook to intercept file downloads? (hook\_file\_download seems appropriate on the first glance)

# Answer
> 1 votes
Yes `hook_file_download()` is the one you want to implement, assuming you're using the private file system. The docs have examples of how to use that hook.

There's no built-in way to do this (at least no way that involves Drupal) for public files, as those are served directly at the web server level without the application ever getting involved.

You'll be able to implement a solution for public files based on modifying the .htaccess file to *not* pass those files straight through, and implement your own path system similar to the core private files one; the particular functionality will obviously depend on your exact requirements, if you decide to go this route I'd recommend spending some time looking at the core system and file modules to see how the mechanism is implemented.

Unfortunately it's not a few-lines-of-code job so I can't provide an example, it's something you'll have to put together yourself.

---
Tags: files, .htaccess
---


# Question
Title: Limit options when creating content according to selected value
I have three content types, `Events`, `Disciplines` and `Championships`. An `Event` has entity references to `Disciplines` and `Championships` and `Championship` has an entity reference to `Disciplines`.

```
 ----- 1..n    1..n ------------
|Event|------------|Championship|
 -----              ------------
   |0..n               |0..n
   |                   |
   |                   |
   |1..n               |
 ---------- 1          |
|Discipline|-----------/
 ----------

```

When users are creating new `Event` nodes they initially select which `Disciplines` are involved from a list of checkboxes and then similarly the `Championship`(s) involved.

At the moment all `Championships` nodes appear, allowing users to potentially select `Championships` for `Disciplines` which are not part of the `Event`.

Is it possible to use the conditional fields module to create a dependency to display only `Championships` where the `Championship`'s Discipline field matches the `Discipline`(s) selected when the dependency is triggered?

How would one fill the 'Set of values' in the conditional fields module?

For example when creating `Event1`, I select `DisciplineA` and `DisciplineB`. The list of `Championships` should only contain those which have `DisciplineA` or `DisciplineB` associations and not contain any `Championships` that do not have the correct associations

if event.disciplines were a list of selected disciplines I'd like something along these lines (with the dynamic aspects of conditional fields)

`SELECT championships c WHERE c.discipline IN (event.disciplines)`

**edit**

Dependent Fields seems to do the sort of thing i'd like but there's no D7 version...

**edit 2**

Changed the structure a little.

I suppose `Discipline` didn't need to be an entity in itself and have created a taxonomy vocabulary Discipline instead with terms for each discipline. `Event` and `Championship` now have term references to the same `field_discipline`.

Using the Reference field limit option module the `Championship` entity reference in `Event` has the 'Limit this field's options according to the matching field values' option selected and the matching field being `discipline (field_discipline)`.

When creating an `Event` the list of `Championships` is empty but when I select the `Discipline(s)` the expected `Championships` do not appear.

`No options are available for the current form values. Try selecting different values for the following fields: discipline.`

**edit 3...**

Firebug suggested that the ajax wasn't actually firing for checkbox/radio button but was for select menu. Applied this patch and the section is now updating but still not finding any values. There are appropriate `Championship` nodes to find.

**edit 4!**

The `Championship` nodes didn't have the discipline taxonomies selected...

# Answer
> 0 votes
Another way i found to do this uses entity references, reference option limit and views modules.

```
  -----               ----
 |Event|-------------|Race|
  -----  1..*    1..* ----
   *|                  |*
    |                  |
  1 |                  |
 --------- 1           |
|Organiser|------------/
 ---------

```

An `Event` is made up of `Races` An `Organiser` can organise `Event`(s) and/or `Races` according to two Boolean fields Event? and Race? in the `Organiser` content type.

When creating, for example, an `Event` node we want only the possible options to be those `Organiser` nodes with Event? field set to 'true'.

Assuming the content types already defined, with `Event` having an entity reference to `Orgainser`, first create a new view...

In this case I called the view 'Event Organisers - Limit Options' and set it to **show Content** of type `Organiser`. Untick create Page then click **Continue & edit**.

With the blank Master view, click **\+ Add** and select 'Entity Reference'.

Add the field Event? to the **FIELDS**

In the *Format* Settings select the Event? field.

In the **FILTER CRITERIA** add Event? and set **Operator** to `is one of` and select `true` from the **Options**.

Then edit the Entity Reference field in the `Event` content type which links to `Organiser` type.

**Entity Selection** in **Mode** select 'Views:Filter by an entity reference view' then select the newly created view.

This is obviously applicable to any use case and seems a simple enough way to implement. I did pretty much exactly the same to limit available race organisers too.

Hope this helps someone, i spent quite a while scratching my head over this...

# Answer
> 1 votes
I got this sorted (eventually...)

Rather than having `Discipline` as a content type (since it was only really storing the name) I created a taxonomy vocabulary called Discipline and added all the relevant discipline names as terms.

Removed the entity references to `Discipline` in `Event` and `Championship`. Added a term reference (`field_discipline`) to `Event` and the **same** term reference to `Championship`.

Using the Reference Option Limit module (and patch; see question) in the entity reference in `Event` to `Championship` added the 'Limit this field's options according to matching field values' and selected the matching field `field_discipline`.

So now when creating an Event node the user is presented with a list of checkboxes to select the discipline(s) involved and when each is selected the appropriate championships are added to the list of available championships.

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


# Question
Title: How to use use db_rewrite_sql() with db_query() in D7?
I read article where it was written to use `db_rewrite_sql($query)`. In Drupal 7, you need to use `addTag('node_access')` along with \`db\_select().

I have a query with 8 columns and 4 conditions; for simplicity I am using `db_query()`.

How can I use `db_rewrite_sql()` with `db_query()`?

# Answer
You have to use db\_select() with the addTag() modifier.

The query you mention doesn't sound too crazy so it should be fine for db\_select(). The only downside is it can be a bit slower.

As per the db\_query() api docs:

> Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db\_select() instead.
> 2 votes

---
Tags: 7, database
---


title: Getting form submitted date

text:
# Question
Title: Getting form submitted date
I have a date picker in my form, when user hits submit button, the date which entered in date field is displaying in list view. But I want to display the date the form submitted also.

Any help appreciated.

# Answer
In the Views module you can add this field:

Content: Updated date, The date the content was last updated.
> 0 votes

---
Tags: forms, datetime
---


title: Tableselect with textfields

text:
# Question
Title: Tableselect with textfields
Is it possible to build tableselect form with textfield in each row?

function nowayform\_form($form, $form\_state) {

```
      $xsroads = array(
      array('id'=>'PrArcabilPodvoyskaya','xsr_name'=>t('Archabil/Podvoyskiy')),
      array('id'=>'PrArcabilSovetskaya','xsr_name'=>t('Archabil/Sovietskaya')),
      array('id'=>'PrArcabilLenina','xsr_name'=>t('Archabil/Lenina'))
      );

      $header = array(
      'xsr_name'=>t('Crossroad names')
      );

      $options = array();
      foreach ($xsroads as $xsroad){
        $options[$xsroad['id']] = array(
        'xsr_name'=>$xsroad['xsr_name']
        );
      }

      $form['table'] = array(
      '#type'=>'tableselect',
      '#header'=>$header,
      '#options'=>$options
      );

```

Thanks

# Answer
> 4 votes
in the options you can put another field like this:

```
foreach($xsroads as $xsroad){
  $options[$xsroad['id']] = array(
    'xsr_name' => $xsroad['xsr_name'],
    'xsr_input' => array(
      'data' => array(
        '#type' => 'textfield',
        '#value => 'so you wanned a field',
      ),
    ),
  );
}

```

# Answer
> 3 votes
Out of the box -- no you cannot. It is possible with a bit of playing around though:

* add the form field definition in the 'data' property of the cell you would like to have the element rendered
* make sure it has the #name property set, since it wont get a name otherwise
* add a value element to your form definition with blank value

and you're golden!

An example definition of a form callback ( called by `drupal_get_form` ) with a two row tableselect with textfields:

```
 function ds_test_form() {
   $options = array(
     array(
      'title' => 'Tableselect element',
      'content_type' => 'with textfield!',
      'status' => 'great',
      'comment' => array('data'=>array('#type'=>'textfield',
      '#default_value'=>'', '#title' => 'Comment',
      '#title_display'=>'invisible','#name'=> 'comment[row1]'
     ),
    ),
  ),
  array(
    'title' => 'Enjoy',
    'content_type' => 'the',
    'status' => 'action',
    'comment' => array('data'=>array(
      '#type'=>'textfield',
      '#default_value'=>'',
      '#title' => 'Comment',
      '#title_display'=>'invisible',
      '#name'=> 'comment[row2]'
        ),
      ),
    ),
  );

  $header = array(
    'title' => t('Column 1'),
    'content_type' => t('Column 2'),
    'status' => t('Column 3'),
    'comment' => t('Fields'),
  );

  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No content available.'),
  );

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

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

  return $form;

}

```

A more detailed walkthrough of the above with some screenshots, and why it works that way is at my blog. The above, when submitted, created the following array structure on `$form_state['values']` :

```
Array(
  'table' => Array(
    '1' => '1',
    '0' => 0,
  ),
  'comment' => Array(
    'row1' => 'Comment field text for row1',
    'row2' => 'Comment field text for row2',
  )

```

)

---
Tags: 7, forms
---


# Question
Title: How can one add superscript character like TM or Reg on a block title
I was wondering how to add superscript characters like trademark to Drupal block title.

# Answer
Block Class Styles may be useful:

> Extends the Block Class module to incorporate styles (or themes) rather than css classes. Adds style-based tpl suggestions. Allows HTML in your block titles.

Other options would be to create your block in code, and set the `$block->subject` to be your `<sup>` inclusive title, or to override the `block-XYZ.tpl.php` for the your particular block and add the title in there.

By default, Drupal core runs `check_plain` on any UI created blocks, so through the UI I don't think there's another option.
> 3 votes

# Answer
Trademark ™ is just a character, it doesn't need html. There is no reason why you can't have special characters in block titles.

Superscript as in sup tags is a different story, see the other answer.

How to type symbols? http://www.wikihow.com/Type-Symbols-Using-the-ALT-Key
> 2 votes

---
Tags: blocks
---


# Question
Title: Run my JS after views slideshow has finished loading?
My javascript executes on window load, resize and orientation change.

```
jQuery(window).bind("load resize orientationchange",function (e) {
//do something
});

```

This worked fine until I started using the views slideshow. My code runs before the slideshow. As it measures elements on the screen it doenst work properly. If I resize the browser (so the code re-fires) then it works as expected.

How can I make my code run after views slidehow has finished loading? I also need to re-execute the code every time a slide changes.

# Answer
> 1 votes
I faced the same issue many times (especially when I used lightbox2 module), you can use the `theme_preprocess_views_view` hook or one of Views template files and add the JS using `drupal_add_js`.

**With your code**

```
drupal_add_js('jQuery(window).bind("load resize orientationchange",function (e) {
//do something
});', 'inline');

```

Thanks :)

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


# Question
Title: hide all of node form except a file upload field
Bit of a weird one....

I'd like to call a node edit form into an overlay but have it only show a file upload (cardinality unlimited) fieldset and the save button

I know I can program the formAPI bits, get the files and save the node myself, but In this (possibly strange) case I'd like to use the existing form.

Obviously can CSS it, but I'd rather have it in PHP.

So far I've set up a loop in a conditionally invoked form alter that finds form elements and then... well, unsetting/hiding them gets them off the screen but then the upload field doesnt work

```
foreach($form as $key => &$value) {
  if(is_array($value) && isset($value['#type'])) {
    if(  !in_array($value['#type'], array('hidden', 'value'))
      && !in_array($key, array('field_my_file_field', 'actions'))) {
      unset($form[$key]);
      //or $form[$key]['#type'] = 'hidden';
    }
  }
}

```

I'm guessing I'm compromising the form array, so it's not working in a callback somewhere.

Any ideas? Or a better suggestion for getting just the field upload fieldset onto a page?

Thanks!

# Answer
> 0 votes
You can use Field Permission module to hide all those fields which you don't want to show on node edit or node create form for all user type which you want.

---
Tags: forms
---


title: ckEditor Uploading Issue

text:
# Question
Title: ckEditor Uploading Issue
I installed ckeditor and all went well but now the issue is it can not allow me to upload an Image : when I drag and drop an image it shows a blank line . and if I click on the image icon, it opens but when i try uploading and image it takes me to the page where I was. and nothing happens.do I need any other module to help it upload ? . please I am asking for any help

# Answer
> 1 votes
We use a module called IMCE (https://drupal.org/project/imce) to upload images/files via ckeditor. Works really well and has a nice interface.

---
Tags: wysiwyg
---


# Question
Title: Geocoder not working with “Geocode from another field”
I'm trying to make Geocoder work but encountered the following issue: I installed Geocoder 7.x-1.2, and I want to use it with content from another field, namely Location 7.x-3.0-rc2. I installed Leaflet to try to display my nodes. When I create new nodes, the Geofield is not filled in anymore(it remains empty whatever the address I try to use). I installed Address Field 7.x-1.0-beta4 instead of Location but the same issue persisting.

Are there common issues that would make the geocoding fail? If not, is there a procedure to try to debug this?

# Answer
The issue can be solved by installing the other version of geofield module Geofield 7.x-2.0-beta1 (don't use the 7.x-2.x-dev version).
> 1 votes

---
Tags: 7, location
---


title: Phantom template file?

text:
# Question
Title: Phantom template file?
I've *inherited* a site running a custom Zen sub-theme.

It uses standard CCK content types with several "page-node-" and "node-" template files for layout control.

The original designer used the .tpl files to manually embed various views and blocks (with specific HTML structure for styling) into different pages throughout the site. As you can imagine, these views and blocks can not be directly configured through the UI.

One page however has some block like sidebar image elements that cannot be manipulated through the UI and appear to be embedded via a template file, but I can't find a template file in either the sub-theme or base theme (zen) directory that would affect this page at the page level. There is a node level template, but it only affects the content area, not the right sidebar.

From the source, I can see that they are not actual blocks as they simply have "`<p>`" tags around them

```
<div id="sidebar-right-inner" class="region region-right">

    <p><a href="myurl" title="title"><img src="path/image.png" alt=""></a></p>

    <div id="block-block-39" class="block block-block region-even even region-count-2
     count-6 with-block-editing"> ...

```

The element between #sidebar-right-inner and #block-block-39 simply has a `<p>` tag with no drupal classes or ids. This is what needs to go. Block-block-39 has been configured through the "blocks" administration page and is supposed to be there.

If it were indeed embedded via template file, I should have a file like sites/all/themes/mytheme/pages/page-node-15.tpl.php, but I don't. I've checked Page.tpl.php in both sub-theme and base theme (and every other .tpl file) and cannot figure out how these elements are getting there! Is there somewhere else that a block of HTML could be embedded?

I've tried disabling Javascript on my browser with no change. And if it were created through the UI somehow, I'm thinking it would have additional divs wrapped around it or other classes / ids.

I think I have a pretty good handle on how templates work (hierarchically speaking), and I've spent days searching for an answer. I'm sure I'm missing something silly, but I'm pretty stumped at the moment.

I basically need to just get rid of them.

# Answer
Ok, these elements do not display an "edit block" option when I am logged in as an admin and mouse hover them, nor do they display any of the HTML class / id properties which are typically associated with a block. So It had to be somehow injected or modified VIA a template file.

I did however, *finally* discover that they were in fact being added via a cryptically named block.

This meant that it was likely being acted upon by a "block-" template. Armed with the newly discovered block number, I found that the file "block-block-22.tpl.php" was stripping the edit link and other divs and formatting to prevent the block from having it's own background etc.

The standard "block.tpl.php" file writes all blocks in the sub-theme like:

```
<div id="block-<?php print $block->module . '-' . $block->delta; ?>" class="<?php print $classes; ?>">
    <div class="block-inner">

  <?php if ($block->subject): ?>
    <h2 class="title"><span><?php print $block->subject; ?></span></h2>
  <?php endif; ?>

  <div class="content">
    <?php print $block->content; ?>
  </div>

  <?php print $edit_links; ?>

</div></div> <!-- /block-inner, /block -->

```

Whereas "block-block-22.tpl.php" was overriding the default and writing it as such:

```
<?php print $block->content; ?>

```

effectively stripping all of the block's formatting so that only the images that it contained would show with no extra margin, padding, background etc.

I had a feeling I was missing something simple...

Furthermore, changing it to:

```
<?php print $edit_links; ?>
<?php print $block->content; ?>

```

Enabled the "edit block" link for administrators, so now it can be edited directly from the page.
> 0 votes

---
Tags: theming, blocks
---


# Question
Title: Drupal 7's States API: Why won't this code work?
Scratching my head on this. Trying to get a few fields in a node edit form to be visible only when a select element's value is 'sponsor':

```
function iv_persona_helper_form_persona_node_form_alter(&$form, $form_state) {
  $lang = $form['field_persona_type']['#language'];

  $sponsored_control_states = array(
    'visible' => array(
      ':input[name="field_persona_type['. $lang .']"]' => array('value', 'sponsor'),
    ),
  );

  $form['field_sponsored_url']['#states'] = $sponsored_control_states;
  $form['field_sponsored_text']['#states'] = $sponsored_control_states;
  $form['field_sponsored_description']['#states'] = $sponsored_control_states;

  $form['#validate'][] = 'iv_persona_helper_form_persona_node_form_validate';
}

```

I know the form\_alter is being invoked, but those fields visibility is not at all changed.

# Answer
Try `'value' => 'sponsor'` instead of `'value', 'sponsor'`.
> 3 votes

# Answer
It's hard to say exactly without seeing the form as well but I would guess your form has no field with the name of:

```
field_persona_type['. $lang .']

```

Does that definitely match the field you are trying to use.

You can look in the source code of the page and look at that form element and see what its "name" is and make your code use the same name.
> 0 votes

---
Tags: 7, javascript
---


title: issue with Clean URLS

text:
# Question
Title: issue with Clean URLS
I've just moved my drupal site from it's development server(just a VM on my home pc) over to it's new home, and all except the URLS are working.

I've setup the new server exactly like the development server, installed mod\_rewrite, copied .htaccess, apache2.conf and httpd.conf word for word, yet, regardless of which page/node is displayed, the only thing in the URL is the domain name. And if I try to navigate to a specific node via the URL, it loads the front page instead of the intended node.

I'm not sure if this is related, but when drupal provides a link to a node, like the Welcome email for first time login, it uses the server's IP address in the URL, instead of the domain name.

Any help with this would be greatly appreciated!

Cheers,

Matt

# Answer
> 1 votes
It sounds like with the 'Forward to' configuration for your domain, it may be iframed instead of the domain pointing directly to your server. When you type a direct url, the path isn't passed on to your actual site so it only serves the homepage, and when you click on links it only changes the url of the inner frame so the address bar doesn't update. You can check if the page is actually in an iframe by viewing the source of the page.

For setting up the DNS, you should be creating an 'A' record to point the hostname directly to your IP address.

# Answer
> 0 votes
It looks like my domain settings were the issue. I updated them after reading up on the configuration, and URLs are working perfectly

---
Tags: uri
---


# Question
Title: Why can anonymous users access private files using the system URL?
I have a private organic group with a private organic groups post. I have properly setup my private files system. If an image is uploaded to the private folder an anonymous user can still access it with the following URL:

```
/system/files/private/assets/image.jpg

```

However they are given a Forbidden: You don't have permission to access this on this server when access the URL this way:

```
/sites/default/files/private/assets/image.jpg

```

My guess is that Drupal is not doing it's job in the first instance; as I haven't set up private file system properly and Apache is doing it's job in the second URL due to the htaccess file in there.

Any pointers?

# Answer
`/sites/default/files/private/assets/image.jpg` will never work because of an .htaccess directive prohibiting direct access to that directory.

Beyond that, this strikes me as an issue with OG. I'd try executing a `module_implements('file_download')` and have a look at what modules might be interacting with determining if a given file is accessible.
> 1 votes

---
Tags: files
---


# Question
Title: How allow moderators to give a rebuke to user
I'd like to allow moderators to give a rebuke for users. If user has e.g. 3 rebukes, the account of user should be removed or blocked - automatically or moderator should be inform about it.

# Answer
You can use Flag module for that. You can set flag for users or posts created by users or something else as per your requirement.

Use rules to set rule on flagging & their counter value. There is very nice tutorial series on flag here by Johan Falk. You can see his rules tutorials to have better understanding about setting rules based on flagging.
> 1 votes

---
Tags: 7
---


# Question
Title: update a module in the front page after adding new content into another page
I want to create a block on the home page which highlights the latest news from the 'news' page. I would like to add new content into the 'news' page frequently. Every time when I add a piece of new article (news), I would like the block to show the image and the title of that new article automatically.

What is the best way to achieve this?

Thanks

# Answer
> 3 votes
Sounds like you should be using Views.

* Create a new view
* Create a page display and configure it to output the content you want.
* Create a block display and configure it to output the content you want.
* Add the block to your homepage

Now when you add new news it will show up on both the page and the block.

---
Tags: blocks
---


# Question
Title: Tooltip issue with tipsy and views tooltips
I have a table of images, which link to their content, and because some of the content titles vary in length, it's difficult to align each image neatly if the titles are displayed above them, as long titles push their image to the side. So rather than restrict title length, I'd like to remove the titles, and have them display inside a tooltip when hovering over each image in the table/gallery. Similar to imgur.com, which even shows the number of views for each node. I wouldn't mind showing creation dates too, if possible. But I'll be happy if I can just get the titles to show.

I've installed Tipsy and Views Tooltips, which for the most part seem great, but they aren't quite behaving as I'd like.

Views Tooltip provides the correct content title in the html, but it's div is outside of the Selector used to trigger Tipsy, so Tipsy isn't picking up the correct tip content. It just shows, 'null'.

The html looks something like(inspecting in chrome):

```
<table>
 <tbody>
   <tr>
    <td>
     <div class="field-content">
      <a href="...." original-title=""><img...></a>
     </div>
     <div class="views-tooltip" tooltip-content="Content title"></div>
    </td>
    <td>

```

and the list goes on..

So if I set the Tipsy selector to, '.field-content a', it triggers on hover over the images, but doesn't have anything to return. And if I set it to, '.views-tooltip' and 'tooltip content', the tooltip won't trigger when hovering over the images.

So the way I see it, is that I need to somehow set the 'a' selector's original-title to the same as tooltip-content. Does anyone know how I might go about doing that, or perhaps have another solution? Any help would be appreciated, as I've been stuck on this for almost 3 days now.

Cheers,

Matt

# Answer
I got around this with some CSS and custom field HTML for the title and other info that I wanted to display in the tooltip, so there's no need for tipsy anymore
> 0 votes

---
Tags: views
---


title: hook_file_download and style images

text:
# Question
Title: hook_file_download and style images
According this bug issue, hook\_file\_download is called twice when private style image is requested. The first time is requested original image without style and then the style image is called. Is there any workaround to skip checking access of original image?

In particular, I have a website, where user can share his private images on his facebook account. Then I need to allow facebook to send http request to download image. The problem is, that facebook hs limitations on size of images. Facebook doeasn't accept larger images when downloading thumbnails from my website. As I tested it, although my image thumbnails are small, drupal system check access against large original image so facebook doesn't accept the thumbnail.

Is there any workaround, how could I solve this problem?

thanks for advice Tomas

# Answer
**Disclaimer** \- Use this method at your own risk, it has security implications if you don't set up and test it properly :)

A quick and dirty way to override that functionality would be to implement `hook_module_implements_alter()`, remove the image module's implementation of `hook_file_download()`, and then implement your own version which has the desired logic. e.g.

```
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'file_download') {
    unset($implementations['image']);
  }
}

function MYMODULE_file_download($uri) {
  // Copy the code from image_file_download() and alter as required.
}

```
> 1 votes

---
Tags: hooks, media, files
---


title: Creating view with user's contents

text:
# Question
Title: Creating view with user's contents
I'd like to create view page with contents added by the user. In that page, every user can see contents only added by him. How can I do it?

# Answer
In your Views UI, at the right, expand "Advanced". Simply add a relationship of User: Author and then create a filter using field User:current and make sure you use setting logged on user
> 2 votes

# Answer
You can do that by using Contextual Filter in views. Do this --

* Under Advanced, add a new Contextual filter for `Content: Author uid`.
* Choose `Provide default value` and select `User ID from URL`.
* Under Page settings, set Path to **user/%/myview**.

When you navigate to **user/1/myview** now, you should see content from user 1. You can set it as page to be navigated from where ever you need.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Use an entity reference in URL as Views Contextual Filter
My site allows users to create a "booking request" node related to a "vehicle" node. I use an Entity Reference to connect the two by prepopulating a "Vehicle" field on the "booking request" node via a string in the URL:

http://example.com/vechiclename=&overlay=node/add/booking%3Ffield\_vehicle%3D84

I would like to display a views block on this overlaid page with more info from the related vehicle. As you can see, the NID of the vehicle is in the URL (84), but I don't know how to target it.

I'm familiar with grabbing a path component from the URL, but it's the &field\_vehicle=84 that is new to me. Any ideas?

# Answer
> 1 votes
I have never added a views block into the admin overlay (trying to get a parameter from the URL form the views block). But this is how I would approach the problem.

In your view, pick the 'Block' display. Add a contextual filter for the field that is referencing (Vehicle). Expand 'When the filter is not available'. Pick the option PHP Code. User the following code:

```
return (isset($_GET['field_vehicle'])) ? $_GET['field_vehicle'] : 'all';

```

I am using 'all' as fallback assuming that you will show everything if a value isn't available. But I guess you can use FALSE if you want it empty.

Save it. Add the block into your overlay/admin theme. Check if it works...

Best regards.

---
Tags: 7, views
---


# Question
Title: Getting current node ID for use in VBO operation
I have a view of nodes and I'm using VBO and rules to apply taxonomy terms to the nodes. What I want to do is:

1. Get the current node's ID (that is, the node with the view block in it).
2. Get the value of a term reference field from that node.
3. Apply that value to the term reference field of my VBO selected nodes.

But I'm having problems making menu\_get\_object work, or any other method of getting the current node's information.

I'm using the "Execute custom PHP" rules action. Here's what my code looks like:

```
$tagID = 'initialized';

$nodeVBO = $node;  // Storing the $node object sent from VBO

if ($node = menu_get_object()) {
  // Get the nid
  $nid = $node->nid;
  $nodeID = $nid;
  gets_tag_tid($nodeID);
}

function gets_tag_tid(&$nodeID) {
  global $tagID;
  $node = node_load($nid = $nodeID);
  // Get tag tid from node nid
  foreach ($node->field_tags[$node->language] as $item) {
    global $tagID;
    $tagID = $item['tid'];
  }
}

$nodeVBO->field_tags['und'][0]['tid'] = $tagID;

node_save($nodeVBO);

```

Sorry for the awkward code, it's adapted from another part of my module.

I get nothing out of the "if" or the gets\_tag\_tid functions. I have tried echoing the values and reforming the script various ways.

I have never written an operation or an action before so I'm not sure what I can and can't do. **I think the problem might be that when VBO performs the operation it changes the URL to /batch?op=start** or something like that.

Can anyone point out what I'm doing wrong or show me a better way?

Thank you

**EDIT:** I have tried reducing the code to the following:

```
$VBOnode = $node;
$nid = 'initialized';

$node = menu_get_object();
$nid = $node->nid;

$VBOnode->body['und'][0]['value'] = $nid;

node_save($VBOnode);

```

I was trying to print the nid to see if it was even being retrieved. Nothing is printed in the body field though (not even 'initialized'). To me this indicates that the script is calling menu\_get\_object(), getting nothing back because the current page is a batch page, thus $node (and subsequently $nid) are set to null values.

**Does anyone know of a way to make the VBO operation execute on the node page without switching to the batch page and redirecting back?** Or any other alternative solution that I could try? Thank you

# Answer
> 0 votes
You can patch VBO module - to get optional disable batch. https://drupal.org/node/1902104

It is working - i get normal token current page url, not batch url.

I need to get current NID - where VBO function runs.

when you will get result - please write it, maybe here.

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


# Question
Title: redirect to custom profile panel page of individual users
Ok As @Letharion rightly says, i need to rephrase my question. SO here it is:

I created a basic page and gave it an url alias as "Profile". This page is meant to be my profile page for users on my site. On this page there are 3 quick tabs,"My-Profile", "My-Content", "My-Flagged-Node". The "My-Profile" quicktab has a call back to a custom panel page "user-profile" which has the user name, user picture, and the user activity (created as a view with activity module), and the number of content created by the user. The "My-Content" has the content by the user. The "My-Flagged-Node" quick tab on clicking loads a view showing the flagged nodes by the user. I have created these views and these work properly. Now when a user goes to his relationship and clicks another user's picture then i want that the user is taken to the "Profile" page of this user (the user on which he clicked). I undersatnd this has to be done by passing arguments to views from panels and so on but i am not clear on that. While creating my view in the contextual filters and the relationships i added user id from url as a default value but this takes me to a blank screen or to the same user profile. I hope i am clear now on what i want. Some redirection rules and passing arguments.

Regards

# Answer
Try the entity-views-attachment module http://drupal.org/project/eva

This will solve the first part of your problem - having a view filtered by user as per /users/username. Check that you can access via this specific url before trying to redirect.

Answering the question of how to redirect with non-static parameter information - this can be done with 'drupal\_goto()' in a module. Copy one of the 'examples' modules. Customise the .info and .install file and delete everything from the .module file.

Assuming the module is called 'redirect' try a variation of:

```
redirect_init() {
  if (isset($_GET['q']) && preg_match('#^myusers/profile#', $_GET['q']') {
     $uri_parts = explode('/', $_GET['q']);
     $username = $uri_parts[2];
     drupal_goto('custompage/profile/' . $username);
  }
}

```

This compares the current url ($\_GET\['q\]) against a prefix url. It finds the user name at a specific part point in the path e.g. myusers/profile/username, with username being the 2nd index (starting from 0). This way you still have the parameter.

Enable the module before testing.
> 0 votes

# Answer
Panels provides a built-in way to override user profiles-- look for the link (disabled by default) in Page Manager called `user_view` (User Profile Template). Instead of using your own custom profile page, enable this page override (User Profile Template) and make your changes to that panel.

Then, to link to user profiles, you can just use the standard user profile links, no rewriting needed.
> 4 votes

# Answer
The EVA view is nice but not always easy to build as the logic behind it can escape many.

I would handle this in a very simple way: In your existing view, add a pane. In that pane, add a contextual filter uid (User ID) or author ID. In the configuration of that filter select "Provide Default value" and select *User ID from URL*. Save.

This means when a user ID will show up in the URL, clicking on the user's pic will take you to that user's profile page.

Now, to get the user ID into the URL you need to configure the view path. You can do that in one of two ways. The first, if your view is a page, go to *Page Setting - Path* and set the path to something like *user/%* or *user/%/profile* or *abcd/%/fghig* or whatever as long as your "%" is in there somewhere (with a slash before and one after.) The "%" will automatically change to the ID of the user **being viewed.**

The other way, if your view is not a page, click on *Advanced - Other- Link display* and select your path there, replacing the "%" token for the page above with "!1"

Save your view and add the views pane to your panel.

Hope this helps. :)
> 0 votes

---
Tags: 7, panels, users
---


# Question
Title: How do I hide an area in a template or layout if multiple regions have no content?
I am able to set this up using a single check for a content in a region, but what if say 3 regions must all have content before the area is displayed?

Here's what I use in my templates when checking for a single region:

```
<?php if ($content['region-1']): ?>
<p>Region 1 Content</p>
  <?php print render($content['region-1']); ?>
<?php endif; ?>

```

But for checking multiple regions, Something like this?

```
<?php if ($content['region-1']['region-2']['region-3']): ?>
<p>Region 1 Content</p>
  <?php print render($content['region-1']); ?>
<p>Region 2 Content</p>
  <?php print render($content['region-1']); ?>
<p>Region 3 Content</p>
  <?php print render($content['region-1']); ?>
<?php endif; ?>

```

# Answer
> 0 votes
This is what I tried just now & it's working --

```
<?php if ($page['footer_firstcolumn'] && $page['footer_secondcolumn']): ?>
  <div class="footer-firstcolumn">
    <?php print render($page['footer_firstcolumn']); ?>
  </div>
<?php endif; ?>

```

So I hope if you also try like this with your code with `&&`, it will work. Something like this--

```
<?php if ($content['region-1'] && $content['region-2'] && $content['region-3']): ?>
<p>Region 1 Content</p>
  <?php print render($content['region-1']); ?>
<p>Region 2 Content</p>
  <?php print render($content['region-1']); ?>
<p>Region 3 Content</p>
  <?php print render($content['region-1']); ?>
<?php endif; ?>

```

Otherwise you can take a look here on this documentation to see how you can check whether they are occupied or not in `template.php` and pass some value with variable to tpl. Then it will be easy to put in condition just like D6.

# Answer
> 1 votes
Your solution will work, but I think the best practice will be to make this check by preprocess 'theme\_preprocess\_page' and pass the result ( e.g. 'isRegionsEmpty') to the template. Then, in the template you only check one variable.

---
Tags: theming
---


# Question
Title: How to publish unpublished nodes programmatically
I have some unpublished nodes, for which I have their node IDs. How can I programmatically publish them? Is it correct to achieve it in custom module using a query like the following?

```
db_query("UPDATE {node} SET status = 1 WHERE nid = %d", $nid)

```

# Answer
Using `db_query()` is a Drupal 6 method, which is not used in Drupal 7. To achieve your job I suggest this code (without any manual query).

```
// load the node object
$node = node_load($nid);
// set status property to 1
$node->status = 1;
// re-save the node
node_save($node);

```

If you have more node ID, and you want to publish all those nodes, you can use the following code.

```
$nids = array();
// Load all nodes in one go for better performance.
$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // set status property to 1
  $node->status = 1;
  // re-save the node
  node_save($node);
}

```
> 23 votes

# Answer
when you are using node\_load(), node\_load\_multiple() for loading a(multiple) noad(s) there are many hooks would be invoked by modules, such as **hook\_node\_load**, **hook\_node\_operations**, **hook\_node\_prepare**, **hook\_node\_accesse**. But by performing query directly on drupal schema those hooks will be ignored and leads to many issues.

The Queries are:

```
db_query("UPDATE {node} SET `status` = '1' WHERE `nid` =:nid ;"
    ,array(':nid'=>$node->nid));

db_query("UPDATE {node_revision} SET `status` = '1' WHERE `nid` =:nid AND  `vid` =:vid;"
    ,array(':nid'=>$node->nid,'vid'=> $node->vid));

```

Just use above code If node\_load() or node\_load\_multiple() not working because of running out of available memory.
> 8 votes

---
Tags: 7, database
---


# Question
Title: warning: Illegal offset type in isset or empty
I am running drupal 6 and I get this warning on every page.

```
warning: Illegal offset type in isset or empty in /var/www/my-website/includes/common.inc on line 915.

```

And this is what I have from lines 914 to 917 in `common.inc` file

```
// Custom strings work for English too, even if locale module is disabled.
if (isset($custom_strings[$langcode][$string])) {    /* Line: 915 */
  $string = $custom_strings[$langcode][$string];
}

```

What could be the possible reasons for the warning and how to get rid of it? Any help is appreciated. Thanks.

**Edit:** This warning appears only for anonymous users and it is not visible for authenticated users.

# Answer
I have fixed the problem. I think this will help you. For me it works perfectly:

BEFORE:

```
// Custom strings work for English too, even if locale module is disabled.
if (isset($custom_strings[$langcode][$string])) {
  $string = $custom_strings[$langcode][$string];
}

```

AFTER:

```
// Custom strings work for English too, even if locale module is disabled.
if ($custom_strings[$langcode] && isset($custom_strings[$langcode][$string])) {
  $string = $custom_strings[$langcode][$string];
}

```
> 2 votes

# Answer
if you still need help solving the issue, you can try setting your own error handler to print a debug\_backtrace to see exactly where the source of error is.

More details: http://blog.ryantan.net/2012/12/debugging-illegal-offset-type-in-isset-or-empty-in-for-drupal-7/
> 0 votes

---
Tags: 6
---


# Question
Title: How can I restrict various roles with limit in creating nodes of a particular content type
How can I restrict various roles with limit in creating nodes of a particular content type?

# Answer
you can use node limit module to restrict nodes for various roles.

For `each roles` you can `create` a `node limit condition` with `certain limit` for `nodes` for tat `particular content type`.
> 2 votes

---
Tags: 7, nodes, users
---


# Question
Title: Programatically load title of a views page by its machine name
I would like to use the current title of a very specific views page in another template. Instead of just *manually* copying it and in order to stay flexible and always up to date, I would like to programatically load and insert it.

If my views page has machine name `views_page`, how do I programatically load its current title into a string?

# Answer
> 0 votes
Any of these should work:

Load the View and get the display title:

```
$view = views_get_view('views_page');
print $view->display['page_1']->display_options['title'];

```

Note: Change 'page\_1' to the name of your display.

You can also get the page title from the path:

```
$item = menu_get_item(drupal_get_normal_path('path/to/page'));
print $item['title'];

```

---
Tags: views, theming
---


# Question
Title: how to access node variables in region preprocess function?
I have variable in the node preprocessor:

```
function theme_preprocess_node(&$vars , $hook) {
    $vars['default_product_price'] = $vars['elements']['product:commerce_price'][0]['#markup'];
}

```

Currently, the variable 'default\_product\_price' is not available in the region--sidebar-second.tpl.php file. How would i make this variable available in region template file or page template file? Thank You

# Answer
> 3 votes
The template files for nodes and pages don't share any variable; that is true also for their preprocess and process functions.

Assuming we are talking of a node field implemented with the field API, then what follows applies:

* The page preprocess and process functions have access to `$variables['node']` which contains the node object, in the case the page is a node page

```
function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $node = $variables['node'];
    // …
  }
}

```
* The function to access the content of a entity field is field\_get\_items(), which returns its raw content
* The function to render a entity field is field\_view\_value()

The following code should work.

```
  function mytheme_preprocess_page(&$variables) {
    if (!empty($variables['node'])) {
      $output = '';
      $node = $variables['node'];
      $items = field_get_items('node', $node, 'field name');
      foreach ($items as $item) {
        $field_output = field_view_value('node', $node, 'field name', $item);
        $output .= render($field_output);
      }
      // Set $variables with the value you need.
    }
  }

```

Unfortunately, `$variables['view_mode']` is passed only to the node preprocess/process functions; that value would be helpful to `field_view_value()`, as its last parameter is the view mode.

# Answer
> 0 votes
I'm not sure in what I'm going to say, but maybe you can use the process hook instead of the preprocess, it should be available then.

---
Tags: theming, hooks
---


# Question
Title: How to render all the contents of a view in a custom module?
I have created a view with 4 blocks. Rose,lilly,sunflower,jasmine. All the blocks have common fields. Now i want to display all the contents of the view in my custom module. When I tried the below code, I can access only the first block (ie)Rose. How can i get all the values of a view in my custom module?

```
$view = views_get_view(myblock_block');
$view->set_display('Rose'); // page_1 or block_1 ... block_n, ...page_n
$view->set_items_per_page(0);
$view->execute();
$result = $view->result;

```

# Answer
I've always used views\_embed\_view to do this. The first parameter is the machine name of your view, the second is the display id. Example:

```
$view_rose_output = views_embed_view('myblock_block', 'rose');
$view_lily_output = views_embed_view('myblock_block', 'lily').

```

If your view takes any arguments you can pass that in to the views\_embed\_view after the first two arguments.

Note that views\_embed\_view returns the rendered html of the view. If this is what you want, great! Otherwise, I've used the views\_post\_render hook to alter the output. The function header looks like this:

HOOK\_views\_post\_render(&$view, &$output, &$cache)

where $output is the rendered html, and $view gives you the view object.
> 3 votes

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


title: blockquote breaking in the middle

text:
# Question
Title: blockquote breaking in the middle
When I post something with long blockquote, that's OK, but when this post appeared on front page, it's breaking is such way, that no one can guess that there are also a continuation of the post.

For example, the post: http://en.nuclear-plant.org/node/23

Front page: http://en.nuclear-plant.org/

How to solve this? How to give a hint to readers, how to make "Read more" label more visible?

I don't want to add \<!--break--\> to each post, because, I have very long quotations, and want to fold them.

# Answer
> 1 votes
In Drupal 7, the default is to use an excerpt (i.e. a trimmed value) of the full text as the *summary*. The summary is the text that is placed on the front page.

If I understand your question correctly, you do not want to use the default excerpt, because this confuses the reader.

Instead of this default, you can type in whatever you want as the summary to appear on the front page, e.g.:

> Here is a long and quite interesting quote about lorem ipsum dolor sit amet. To read the full text, just click on the **Read more** link below.

To add a hand-written summary, click in the "(Edit summary)" link just above the main body text field in the input form. Leave this field blank to use the trimmed value of full text as the summary.

---
Tags: 7, theming
---


# Question
Title: Extract Admin OG members from basic page with views
I have added a group reference field to basic pages. That is every book page belongs to an OG group. When displaying a basic page, I want to display the list of admin members of the OG group in a block.

So, I have a view in a block with the following :

## In contextual filters

Content: Nid

## In Relationships

OG membership: OG membership from Node
(OG membership from node) OG membership: Group Node from OG membership
(Group node from OG membership) OG membership: OG membership from Node group
(OG membership from node group) OG membership: User from OG membership

## In fields

(user from OG membership) User: Name (User name)

This view display all the users of the group associated to the current basic page. Now, how can I filter theses users to only keep the ones which have an "administer member" role ?

Any help would be greatly appreciated.

# Answer
I found the solution by doing the following

## In Relationships

OG membership: OG membership from Node
(OG membership from node) OG membership: Group Node from OG membership
(Group node from OG membership) OG membership: OG membership from Node group
(OG membership from node group) OG membership: User from OG membership
**(OG membership from node group) OG membership: OG Roles from membership**

## In filters

(OG Roles from OG membership) OG user roles: Role Name (= administer member)

The idea was to select the roles from the OG membership of the Group.
> 3 votes

# Answer
Create new block (showing users) with these settings:

**Fields:**

User: Name

**Filter criteria:**

User: Roles (= administer member)

**Relationships:**

User: Content authored

**contextual filters:**

(nodes) Content: \[your book reference field\]

*provide default value -\> Content ID from URL*

**Other:**

Query settings -\> tick: `Distinct`, `Pure distinct`.
> 1 votes

---
Tags: views, blocks, organic-groups, users
---


# Question
Title: Does Drupal have any security like Dexterity in Plone?
Is there anything in Drupal's security like Plone's Dexterity where I can wrap content in my webpage and have it displayed or not displayed based upon security roles?

EDIT: Thanks. None of these do what I'm asking, however. I want to wrap a piece of content on a webpage and based upon the user hide or display it,

```
<? if user in group or role x (?>
<input type=buttong value="approve employee for vacation time" />
<? else ?>
<strong>Supervisor not approved yet</strong>
<?)?>

```

Don't get hung up on vacation. I'm not looking for a workflow. It could have said anything. Show DOB, SSN, etc

I have to query outside databases like Oracle, SQL Server, and so on to get this information. It will not be resident in the Drupal database, only the security will be.

# Answer
Drupal has a powerful access control to allow users, site builders and developers grant or deny access to content created in it. The basic of access control is the triplet user-group-permission, where you have users associated to roles associated to permissions.

There's a lot of Drupal contributed modules to extend these features. Content Access is a cool module to restrict content to some roles based on it's own type. Domain Access is another control acccess module, a lil more complicated, which handle the access control to affiliate content to "subsites" (domains, subdomains or non-standard ports). So, if you make a little search in the Modules page of drupal.org for "ACL", "access control" or something like, you'll find a lot of resources to bootstrap your web software development.

Keep drupalizing!
> 4 votes

# Answer
```
<?php if user in group or role x ?>

```

translates to

```
user_access("some permission")

```

once you've assigned the permission to an appropriate role.

See user\_access().

However, mixing permission checks into your content seems like an obvious error, and should be avoided.

Instead you should employ something like Panels and Page manager to push the access permission to a much earlier stage in the page build, and keep access control separate from your content templates.
> 3 votes

# Answer
If i understood you correctly the module you need is Content Access. It allows to filter content per role and more.
> 0 votes

---
Tags: security
---


title: Displaying embeded image as background

text:
# Question
Title: Displaying embeded image as background
I would like to allow users on my site to be able to display a background image, not from their computer but from an outside source, for their profile page.

I assume the best way to do this is to add some kind of an image embed field on the front end of the profile page and tweak the CSS so that the image resides in the background (panel.)

If so, my question is twofold: (1) What is the best module to use to link to the image and, (2) how do I display the field to users? Do I create a content type and use exposed filters in views to display it?

Is there a better approach?

Thanks. :)

# Answer
> 1 votes
Try the Background Images module as a ready-built solution:

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

---
Tags: media, views, nodes
---


# Question
Title: How can I use NID Token with the Insert Module?
I have setup insert module to upload images in a body field. I want to set the path for the "FILE DIRECTORY" to the "node id" token but it does not show in the avaliable tokens.

The image field looks like

Browse avaliable tokens looks like

Why isn't the nid token available?

# Answer
> 3 votes
You want to use the filefields\_path module to add node tokens to your imagefield (or any other file fields):

> The File (Field) Paths module extends the default functionality of Drupal's core Upload module, the FileField module and many other File Upload modules by adding the ability to use node tokens in destination paths and filenames.

In my test environment with the insert module and this module enabled, I now have the capacity to use node:nid in the filefield path as well as a number of other useful tokens:

---
Tags: 7, media, wysiwyg
---


title: drupal database & code out of sync

text:
# Question
Title: drupal database & code out of sync
I've lost the PHP installation of a Drupal 7 site just before a lot of updates were about to be applied. I still have the Drupal database.

If I install a current version of Drupal, it may be out of sync with the database (missing columns that were added by some update etc).

So, how can a new Drupal installation be grafted onto an old database?

# Answer
> 1 votes
Treat this as an upgrade. You won't have a problem with missing columns, because those are in your database. You'll have a problem with missing plugins to access those columns.

1. First, of course, back everything up.
2. Then install Drupal. It makes sense to follow @Schnippy's hint and look in the database for the version number, and install that version of Drupal. Otherwise, install the current version; it will tell you if it needs to update the database.
3. Look in your database (hopefully you have phpMyAdmin available) for tables created by plugins. Use that and your memory to reinstall any modules. You might also look at `admin/reports/updates` and see if it'll list your missing plugins.

Later, I recommend installing the Schema plugin, which will report any mismatches between your modules and database tables. This gets reported on the Status Report page and is wonderful when developing a custom module.

If you lost your images and file uploads from your theme or `site/default/files` directory, you may be out of luck for that content. Good luck!

---
Tags: upgrading
---


# Question
Title: how could I access users profile using settings parameter in drupal behaviours?
I have a behavior as follows:

```
Drupal.behaviors.mymodule = {
  attach: function(context, settings){
    jQuery("#edit-user-address",context).change(function(){
      console.log(" user id and other fields "+settings.user.id);

    });
  }
}

```

How could it be achieved?

# Answer
You should use Drupal's `drupal_add_js` function with the 'settings' option (more info).

**Example:**

```
global $user;
$uid = $user->uid;
drupal_add_js(array('myModule' => array('uid' => $uid)), 'setting');

```
> 3 votes

---
Tags: users, javascript
---


title: superfish settings not visible

text:
# Question
Title: superfish settings not visible
I'm having a strange problem with the Superfish module. If I go to blocks \> superfish menu \> configure, I only see Pages, Pages Exclude, and Content Types. There's no other settings. I was somehow able to put the main menu into the Superfish 1 menu, but none of the settings are visible. I have the superfish library in `/sites/all/libraries`, and the superfish module in `/sites/all/modules`.

I'm using Navin, a subtheme of Omega.

Thanks for the help

# Answer
> 0 votes
The problem was that the mongodb block module disabled the normal block module. When I re enabled the block module, and disabled the mongodb block module, it worked fine.

---
Tags: navigation
---


# Question
Title: Calculate percentage between two entity fields in Drupal using Computed Field Module
I am trying to calculate a `%` of two entity fields in Drupal 7 using Computed Field module.

```
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_accounts_payable_bs'))) /
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_customer_deposits_bs')));

```

Display:

```
$display_output = number_format($entity_field_item['value'] , 1 , '.' , ',');

```

Current the value I get is ".20" But I want it "20.0"

# Answer
> 1 votes
First print\_r($data) in your Output code text area so you can see what you can work with. Depending on what you have, your Output code is going to look something like this:

```
$percent = 100 * $data->field_accounts_payable_bs['0']['raw']['value'] / $data->field_customer_deposits_bs['0']['raw']['value'];

print(number_format($percent, 1, '.', ','));

```

# Answer
> 1 votes
OK, I figured it out! In order to calculate a percentage from two Entity fields with the Computed Fields Module you have to do the following;

```
$entity_field[0]['value'] = array_pop(array_pop(field_get_items($entity_type, $entity, 'field_accounts_payable_bs'))) /
array_pop(array_pop(field_get_items($entity_type, $entity, 'field_customer_deposits_bs'))) * 100;

```

For the display use:

```
$display_output = number_format($entity_field_item['value'] , 1 , '.' , ',');

```

Thank you all for your help!

---
Tags: entities
---


# Question
Title: Modal notification box on the screen of every authenticated user
I want that every time I or any other admin (I have 2 more) post a new article each authenticated user should get a modal notification box on it's screen displaying a teaser of the Content Type I have posted.

I created an action 'Display a message to the user' for the trigger, 'TRIGGER: AFTER SAVING NEW CONTENT' and then tried saving new content and checked on a different account (which was already logged) for any message but nothing happened. Also, if this worked I'd like to show a modal box with the display settings (which I have in place already).

# Answer
> 0 votes
Drupal does not provide a way to send notifications to all site users by default. The action you are trying to use will only notify the user who triggers the action (you). Messaging can help you achieve what you want. You may also need the appbar module.

---
Tags: notifications, actions, privatemsg, rules
---


# Question
Title: How can I add password fields to the account creation page?
My site has recently gone live, and I'm finding that a lot of users are getting confused while signing up for an account. I have "require email verification" enabled, so users are receiving their email with the one-time login link, but they don't seem be setting their passwords with this login. So they enter their details, save the profile and then, for whatever reason, log out and can't get back in as they never set a password.

I know they can request a password reset to get back in, but is there any way to add the password fields to the account creation page and still keep email verification?

Any help would be greatly appreciated,

Cheers,

Matt

# Answer
Although it doesn't mention it on the module description page, this is one of the features of LoginToboggan, which also addresses a number of other common login confusions (ie: a user can log in with their email address or username, prompt for login instead of permission denied page).

From the documentation:

> **Set password** Ticking this will allow users to enter their desired password when they set up their user account.
> 1 votes

# Answer
The User Registration Password module directly address this requirement:

> Let users register with a password on the registration form when verification mail is required.
>
> By default, users can create accounts directly on the registration form, set their password and be immediately logged in, or they can create their account, wait for a verification e-mail, and then create their password. With this module, users are able to create their account along with their password and simply activate their account when receiving the verification email.
> 0 votes

---
Tags: users
---


# Question
Title: Clean way of receiving image_dimensions after applying image_style
I'm quite a Drupal-Newbie and am wondering what would be the best way to receive the dimensions of an image after applying some styles.

I have the URI of the image before the style and absolute URL after applying the style with `image_style_url`

# Answer
> 0 votes
I found one solution, which does not look neat, but works:

`$sizes = getimagesize(drupal_realpath(image_style_path('style', $imageURI)));`

---
Tags: files, media
---


# Question
Title: Logintoboggan- Providing the one-time login link in an admin view
Logintoboggan can be configured so that users are initially assigned an *unverified* role and only become authenticated users when they click the link in their e-mail for the first time.

However, sometimes users have trouble clicking the link (low technical ability, old cellphones that don't recognize the link, etc.) For this reason, sometimes the admin needs to activate a user's account on behalf of that user.

I have a view of users with the *unverified* role and I would like to add the one-time login links to the view so that admins can simply click them. Logintoboggan provides a token, `[user:one-time-login-url]`, but this token cannot be used in Views.

Is there some way I can show the link in Views?

# Answer
This is not an ideal way to do this, but since I am using the Panels module to display user profiles, I created a new variant for unverified users and added a piece of custom content on the variant (with a visibility rule restricting it to admin users) that showed the validation token.

Then I added a link on the view to the user profile; this is two steps instead of one, but at least it is a working solution.
> 0 votes

---
Tags: users
---


title: Override View Output for Shopping Cart

text:
# Question
Title: Override View Output for Shopping Cart
i am theming a template and currently working shopping cart section. The commerce module provides a view 'Shopping cart block' out of box. I am trying utilize this view, however, i am unable to rewrite the html code from the UI the way i need. So, i am looking to do the same in code using hooks.

```
function theme_views_pre_render(&$view){
    var_dump('got in pre view');
}

```

Is this the proper hook? Where is the output markup stored for views? Is there a render array of view output available that i could manipulate before its rendered? Thank you

# Answer
> 0 votes
What worked for me was: verride the 'shopping cart block' view with custom template block--cart-blockNameInClonedView.tpl.php(referece themer-info for exact name).

Populate the 'vars' array with total number of items and total amount of a shopping cart in block preprocessor function as following:

```
function THEME_preprocess_block(&$vars, $hook){
    if ($vars['block']->region == 'cart_in_header') {
            if ($order = commerce_cart_order_load($vars['user']->uid)) {
                $wrapper = entity_metadata_wrapper('commerce_order', $order);
                $bazar_cart = array();
                $bazar_cart['total-qty'] = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());
                $price_raw= commerce_line_items_total($wrapper->commerce_line_items, commerce_product_line_item_types())['amount'];
                $bazar_cart['total-price'] = substr($price_raw,0,-2).'.'.substr($price_raw,-2);

                $vars['bazar_cart'] = $bazar_cart;
            }
      }
}

```

In custom block template file, the variable '$bazar\_cart' is available to plug the values(total items and total amount of cart) as you wish in the html structure

---
Tags: theming
---


title: URL redirect for changed url structure

text:
# Question
Title: URL redirect for changed url structure
I changed my Drupal 6 website tag structure and got a new URL however old URLs are indexed in Google and are generating 404 errors.

My old URLs are

```
www.mydomain.com/topics/12345/widget
www.mydomain.com/topics/5783/widget2

```

numeral - 12345 in this URL was tag no in the database

new URL structure is

```
www.mydomain.com/topics/widget
www.mydomain.com/topics/widget2

```

Now I wish to create a redirect so that

```
mydomain.com/topics/12345/widget

```

goes to

```
www.mydomain.com/topics/widget

```

and remove the random numeral nos in URL.. How to do it?

# Answer
You can use Path Redirect module. Module page says -

> This module allows you to specify a redirect from one path to another path or an external URL, using any HTTP redirect status.

As I see you are talking about taxonomy terms, so alternatively you can use Taxonomy Redirect.

> This module allows the administrator to change the destination of Taxonomy Term links.
>
> * The module can now handle redirections at the term level.
> * You can specify a replacement character for spaces and + characters.
> * You can specify a list of characters or strings to remove from the path
> * You can enter php code that will create your path at runtime (In 5.x-1.3, variables for term ID ($tid) and term name ($tname) are available to use in your php code).
> 0 votes

---
Tags: uri
---


# Question
Title: Using drupal 7 block from another website luckily on same server
I have spent several hours searching for my solution. I found some but none of them is working. My problem is I have multi-site setup of drupal. Site A has a drupal views generated block of events calendar with next/back navigation of months (mini calendar). I want to use that block in another website of same drupal installation. Both of website has common user tables, theme and modules. I have tried following options until now

* Web Widgets module, web widget block does not have month header and the navigation. I believe I can not use it without IFRAME.
* I have also tried setting up REST setup between both domains using clients, OAuth, Services, Remote Views Block modules. Fotunately, connection is set up properly but Remote Views Block module is raising following errors when remote module is added to context.

`Notice: Undefined property: stdClass::$weight in context_reaction_block->options_form_submit() (line 104 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/sites/all/modules/context/plugins/context_reaction_block.inc).
Notice: Undefined property: stdClass::$weight in context_reaction_block->options_form_submit() (line 104 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/sites/all/modules/context/plugins/context_reaction_block.inc).`

and following errors on other pages when context of remote block is active

```
Warning: http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given in clients_connection_drupal_services_rest_7->makeRequest() (line 204 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/sites/all/modules/clients/connections/clients_drupal_rest/clients_drupal_rest.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 929 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 2 in drupal_http_request() (line 933 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 933 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).

```

Am I missing anything here? connection test works properly though and I double checked the module names.

* Embed widgets and Remote blocks are not available for Drupal 7.
* I read somwhere (I cant find the source right now) that Drupal 7.x.1.1 supports Remote Blocks in the sense that site has other database configured in settings.php. Do we have its documentation anywhere?

Any help would be much appreciated... I am stuck here..

# Answer
> 4 votes
Here's a Shared Blocks module for that purpose written by well known drupal community members.

> Features:
>
> * Allows publishing and subscribing of Drupal blocks
> * Changes to published blocks are updated on sites with subscription blocks
> * Published blocks provides a JSON endpoint at sharedblocks/{module}/{delta}
> * Block subscriptions are updated on cron with an adjustable refresh interval

# Answer
> 0 votes
If you don't mind managing some code, you could use Features to export the content types that you want to share into a custom module and keep it in the sites/all/modules directory. Keeping it in sites/all/modules allows the module to be shared across all of your sites and when you need to make changes to the content type, you make those changes on one site, then recreate the feature (there are drush commands to do this, or you could do it through the UI). Finally, you would "revert" the feature on all the sites where it's enabled.

CTools comes with a sub-module called ctools\_custom\_content which can be enabled and used in conjunction with Panels to create exportable content panes that can be placed across multiple Panels pages. CTools also allows you to create custom plugins (using code) that can be used like blocks on Panels pages.

There's also the option of coding a custom block and putting it in a shared location (i.e. sites/all/modules/mycustommodule/mycustommodule.module) and then using a hook to load and insert this block on whichever page you need.

I often use Features in combination with Panels, CTools Custom Content, and/or custom code when I need a reusable "block". I'm not familiar with a solution that does not involve managing a custom module at one level or another. I'd be happy to provide more details (or at least point to some good documentation) on any of these steps if you're interested.

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


# Question
Title: html.tpl.php is deleted and the site is down!
I'm mid-versed in WordPress, but newbie in Drupal, developing a Theme from scratch. I started with `page.tpl.php`, then extended the design with a custom front-page (`page--front.tpl.php`). Then for a custom structure I made `html.tpl.php`, after heard about it from a Drupal geek. But I found no connection with it to the site and `Shift`+`Delete` it. And my site is down now.

To retrieve the site, I copied the `page.tpl.php` and renamed it to `html.tpl.php`. But till there is nothing but an alt text of my logo. I even can't get access to the `/user`, Clearing cache section. But cleared the browser cache with no hope.

Developing environment: WAMP 2.1, localhost

# Answer
Found a solution. An unconventional solution though!

* **Step I:** I moved my custom theme from `sites/all/themes/` to one step up (`sites/all/`). So the system cannot identify the theme in place. I got access into the Drupal.
* **Step II:** I set "Bartik 7.22" as the Default theme.
* **Step III:** Then moved my theme back to its place again.
* **Step IV:** Renamed the file `html.tpl.php` to `html.tpl.php.BACKUP`.
* **Step V:** Then reactivated and set default my theme in the Appearance.

It's live!

> **Reason:** I think it's the Drupal cache. The process I followed was simply tweaking the caching in an alternative, but unconventional way.
> 1 votes

---
Tags: theming, configuration
---


# Question
Title: Drupal 7: Help me to wrap my head around EVA/reverse node reference
What I wanna do shoult be quite easy but but till now I've been without luck. I've read different approaches but none of them worked for me.

Setting: Drupal7/Views 3.6/References/EVA

We have 2 node types: "article" (e. g. "How to sleep better" and "What your dreams mean") "theme week" (e. g. "Sleep")

"theme week" has a node relationship field which points to the "article" node type (i. e. theme week "Sleep" has references to "How to sleep better" and "What your dreams mean").

Now I want to show that referenced articles in my "theme week" node which reffers them. I use EVA to attach a view to my "theme week" node.

Problem: I can't get to set up the view properly; my guess is that I'd use a reverse relationship to my reffering node "theme week", but till now I haven't been lucky with that.

Any advices (step-by-step) would be highly appreciated! Do I have to set up a contextual filter as well? Which fields/filters must use the relationship?

Thanks in advance to everyone sp

# Answer
> 1 votes
OK, i did it. Here's how:

**Node types:** I've set up 2 node types "article" and "theme week". "theme week" has a node reference field where nodes of the type "article" can be choosen.

**View:** \- I've set up one "EVA" view (requires EVA) Under "advanced", I've selected the relationship to my "article" node type. \- I did NOT set "require relationship". \- Unter "contextual filter" I've set "Content: Nid", "Provide default value -\> Content ID from URL". \- I've set all my fields and filter criteria to use that relationship

**Display Suite/EVA:** \- I've attached my View as a field in my "theme week" node type (requires Display Suite/DS).

Now when a "theme week" node is viewed, it shows the "article" nodes which have been referenced by "theme week".

I hope this might be useful to someone!

---
Tags: views, nodes
---