title: Feed items field from Feed node

text:
# Question
Title: Feed items field from Feed node
I'm looking for a way to make Feed items inherit a field value from its parent Feed importer node during the import. The idea is to later use this field value in views filter. In my case this field contains the nid value of referenced node that should be the same for Feed importer node and all of its feed items, and different for other importers and their feed items.

What I have found a quiet similar issue: http://www.zivtech.com/blog/feed-feeds-importing-referenced-rss-data

but unfortunately I'm not very good at coding and cant find out the reason why this solution doesnt work in my case. Maybe there is a way to do this through views relationships or any other module like Rules or Node Hierarchy?

I also found an module for Drupal 6 that might do this kind of stuff but it wont work for Drupal 7 and Feeds module: FeedAPI Field Inherit

If some one has an advice for this issue please help. Thanks!

# Answer
> 3 votes
The node ID of the parent feed node should be attached to each child feed-item node. Using this in either the template file, or within Views, you can get to the data you require.

For example :

In a Views listing. Add a relationship to the parent feed. Add a new field for content title - but attach it to the relationship - this gives the parent title. Same applies for any other fields you may have added to the parent.

In template.php -- do a `node_load($node->PARENT URL REFERENCE GOES HERE)` this will give you access to all the variables on the parent node. If this sounds alien to you then you probably don't need it.

Hope that helps :)

# Answer
> 0 votes
I'm using Feeds 7.x-2.0-alpha5, and its standard *Node processor* allows you to map fields from parent *Feed* node to children *Feed Item* nodes. Have a look under *Mapping* link in for *Node processor*. (Btw, if you're using standard importer, you would need to *override* it first and then *edit* to get to its settings.

---
Tags: 7, entities, feeds
---


# Question
Title: console.log() renders elements as "D.fn.D.init"
I have a strongly ingrained habit of using `console.log()` to pinpoint where an element is on the page. Usually if you had a page like this

```
<html>
    <div>hello Drupal.stackxchange.com This is my first question!</div>
    <div>goodbye</div>
<html>

```

and then you ran a jQuery function like this

```
console.log($('div'));

```

your console would spit out this

```
[▶<div>…</div>, ▶<div>goodbye</div>]

```

which works just as good as the element inspector. Hovering your mouse over one of these will make the actual element on the page be highlighted in yellow with a helpful tooltip. It's one of my favorite ways to work with markup, however the jQuery that comes with Drupal makes it impossible by spitting out the following alternative.

```
[▶D.fn.D.init, ▶D.fn.D.init]

```

which does NOT work with the highlighting feature because it's not the actual element being passed to the console, nor is it very descriptive visually.

Why?

# Answer
I've discovered the true answer. The problem is that Drupal 5, and older installs of Drupal 6 and 7 came with jQuery 1.2.6 which is *insanely* out of date and doesn't support that feature.

example: http://jsfiddle.net/rgbk/k839Y/

Seen here, as of this writing, most of the code in 1.2.6 is between 4 and 6 years old. Why has Drupal held on to such an outdated jQuer versions for so long? That's perhaps for another discussion thread. https://github.com/jquery/jquery/tree/1.2.6

Anyway, the solution is to install Drupal's jQuery Update module which will forceably upgrade jQuery to ... well not really a much newer jQuery, but at least past the 1.3 mark which is as old as jQuery can possibly be and support that feature.

So that closes the book on this question, but it raises another much larger concern. Now I'm worried about all the hundreds of other missing improvements that have happened since before I even knew jQuery was a thing.

---

Edit: Clive's answer about the 100-element limit is still relavant after the jQuery Update.
> 2 votes

# Answer
After a bit of digging around I managed to reproduce this on a couple of dev sites and I think I've narrowed down the problem.

The issue seems to be with the *number* of elements being passed to `console.log`.

This is what the output looks like with 100 `<div>` tags on the page:

And this is what it looks like with 101 `<div>` tags on the page:

So it seems either jQuery or `console.log` is imposing some sort of limit on rendering the output. I don't have time to look into it but my hunch would be that `console.log` is responsible for that.
> 4 votes

---
Tags: javascript
---


# Question
Title: Setting up a date field to require an end date
I'm attempting to create a custom content type for a module via hook\_install. When I create a date type (from Date module), I want it to require an end date (there's a checkbox when you're setting up the field via the gui). This is the settings array for the field:

```
'settings' => array(
    'enddate_get' => 1,
    'enddate_required' => 1,
),

```

This isn't working (the widget is still only asking for one date), so I'm guess that I have the wrong settings. Does anyone know how to properly set this up?

# Answer
I believe you would need to setup the requirement on the form you are building for the custom content type so you would add this to the date\_end form entry:

```
$form['CUSTOM_CONTENT_TYPE']['DATE_END'] = array(
...
  '#required' => TRUE,
...
),

```
> 0 votes

---
Tags: 7, entities
---


title: Restricting Field Access by Role

text:
# Question
Title: Restricting Field Access by Role
I'm working on a site in which I'd like anon users to be able to create nodes of a certain type, but I only want them to be able to see/edit some of the fields on that content type.

I can't go into details just yet, but the goal of the site is to crowd-source the collection of information and then have a few administrators who will approve and groom the data. That's why I want anon users to be able to create nodes and only access a few fields. Then admins will be able to supplement that data by adding values into the other fields and then publish that node.

How do I restrict access to fields basing on the roles the users have?

# Answer
> 10 votes
You want the Field Permissions module, it does exactly that:

> The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

It gives you granular access control based on role for every field, e.g.:

---
Tags: 7, entities, users
---


# Question
Title: Using views to display content based on taxonomy terms?
I have created a faculty profile system on our university departments site. Every faculty member is tagged with terms regarding an area of expertise (either in teaching or in research). What I need is to create a view that takes the areas of expertise from a specific faculty members page, and displays the other faculty members that also work within those areas. (but only those areas)

What I have done so far is a view that wants to show ALL the terms on EVERY faculty content type, but I need to have the view filtered somehow based on the specific page that is being viewed. Here is what I have:

http://sustainable.unt.edu/irene-klaver

Here is an example of what I need: http://sustainability.asu.edu/people/persbio.php?pid=188

The faculty nodes are a custom content type (CCK). The view uses Imagecache/Imagefield to use the thumbnails. The terms have their own vocabulary in Taxonomy, specifically for this purpose. I am using Drupal 6.

I have been told by a few that this might not be able to happen with Drupal, and that I have to create some custom php code in my node-faculty.tpl.php file. Since the ASU site aboves developer doesn't use Drupal, they couldn't really help me out much. I find it hard to believe that someone hasn't needed a function that is similar to this before... If anyone can at least point me in the right direction, I would greatly appreciate it!

Thanks!

# Answer
> 0 votes
I FOUND AN ANSWER! YAY!

Ok so I figured it out with the help of someone who knows WAY more PHP than I do (and could site me down and actually show me in person), so I'm not going to take credit for this. :) You have to edit the theme of your site, but I actually like this better way better because I can make it pretty with CSS a lot easier. (No more dull axing)

First, create a template file for the content node type (I called mine node-faculty.tpl.php). Then I added this code directly into my template file to call the view:

```
<?php

foreach( $node->taxonomy as $tid ) {
print views_embed_view('faculty_expertise_test2', 'default', $tid->tid);
}
?>

```

AND IT WORKS. Phew! Ok, but I couldn't do it without you. Getting as far as you got me helped someone else help me through the finish line. :)

# Answer
> 2 votes
Drupal Views can easily do this :)

1. Create your view and call it "example", and for this example, put Node Title in the Fields.
2. Add in an argument. Here select Taxonomy: Term ID.
3. In "Action to take if argument is not present:" select "Provide Default Argument"
4. There, select "Taxonomy Term ID from URL" and then click "Load default argument from node page, thats good for related taxonomy blocks" and if you want, you can also limit it to specific vocabulary(ies) by clicking "Limit terms by vocabulary" and clicking on the one(s) you want.
5. Create a "Block Display" and save everything.
6. Goto your Site Building/Block Admin Page and look for "Views: example" and put it in a region of your theme.

Now, if all is well in the world, that block will appear and will display the titles of all nodes that also have the same taxonomy term as the node it is displayed on. Of course, you will probably want this block displayed only on certain pages, but you can do that in your block UI as well. And of course you'll also probably want to be fancier than just the node title, etc, but there you would include the fields in the specific nodes, etc.

ADDITION:

This is what I see here for a taxonomy term id argument with D6 and Views3:

UGLY SOLUTION:

I was sure there would be a solution to this using just Views, but I can't figure it out for the life of me. Grrrr, I hope someone out there says *Duh, this is how you do it.* But, if you have the PHP Input Filter enabled, you can create a block that will do this instead of creating a custom module. The PHP Input Filter is UGLY. It should be killed with that dull ax I often use, but here goes:

Add a new block via the blocks UI with this as the block body:

```
<?php

$node=menu_get_object();

if (isset($node->type) && $node->type=='Faculty') {

  $vid = db_result(db_query('SELECT vid FROM {vocabulary} WHERE name = "Expertise"'));

  if (!empty($node->taxonomy)) {
    foreach($node->taxonomy as $term) {
      if ($term->vid == $vid) {
         print '<div class="expertise-name">' . $term->name . '</div>';
         print '<div class="experts">' . views_embed_view('faculty_expertise_test2', 'default', $term->tid) . '</div>';
      }
    }
  }

}

?>

```

Make sure you select PHP Code as the Input Filter. Select a Block description and title and save the block. Place it in whatever region you want. Cross fingers and see what happens :) Basically all this does is loop through all taxonomy terms of your Expertise vocabulary in the node shown and then calls the view with that argument. I think I have everything capitalized correctly from your examples, but the key things to customize about are Faculty, Expertise and faculty\_expertise\_test2, which are your node type, vocabulary and view. If all works, then it's up to you to CSS things to your liking. Hope this helps!

PS I just realized that the view will most probably return the faculty member her/himself but that can be dealt with another day :)

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


# Question
Title: Is it normal after editing an item in one display for Views to always go back to the first display
Drupal7 & Views 7.x-3.3 My site installation of Views has several working Views. There is a strange behavior in the GUI and its very annoying. After editing an item, Views always goes back to the first display!?!

For example, the included example view, "Front page (Content)", has two displays, Page & Feed. To recreate this annoyance edit the Front Page View, then:

1. Select the display Feed;
2. Edit any item, such as: Display name: / Page /
3. Make changes, then save;

Page refresh returns to Front Page's View edit page, and in my installation the Feed display is no longer selected. Now the Page display is selected. This happens every time for all Views. After editing an item in one display, the page refreshes back to the first display (at left). This was not the case with Views 2 and Drupal 6. Its the equivalent of changing tabs after saving something.

# Answer
> 0 votes
Its just a bug of `views/settings/advanced` and the setting "Disable JavaScript with Views".

At the time of asking this question, I was troubleshooting errors in the Views plugin Draggableviews that were appearing in the Views UI.

Related to this is another bug where its impossible to *remove* a `Filter Criteria` value without JavaScript enabled.

---
Tags: views
---


# Question
Title: Creating smaller menus from chunks of a bigger menu
I have this really big nav menu in Drupal 7. The top-level links go to child pages. Each of these child pages has several pages hierarchically under them.

On these child pages, I want a block that shows links to sibling pages and children of the current page (But not children of sibling pages).

It seems like it should be relatively easy, but I've been beating my head against a wall all afternoon. Any help? Thanks!

# Answer
> 1 votes
What you are describing is the primary feature provided by the Menu block module.

---
Tags: 7, routes
---


# Question
Title: How to refresh entity from entity_load(), reloading the entity as it is now?
If an entity has already been loaded, `entity_load()` retrieves it from memory rather than reloading it. Makes sense.

But: what can you do when you need to reload an entity that has already been loaded - when the entity's data has (or, may have) been changed in the database since it was loaded by another function, and you need the changed version?

The closest I can find to a way to reload an entity is to call `entity_load()` with the 4th parameter of `entity_load()` to true - for example, `entity_load( $entity_type, $entity_id, null, true );` \- however, this does much more than just reload the entity.

It also appears to reset the cache on the server, which can have a lot of undesired side effects (for example, I'm finding that calling this as a step in the process of saving an entity causes a cache to be created for the entity's fields that is missing field data, and this faulty created cache persists even as the entity is saved, causing it to seem like the entity's fields failed to save and a blank entity was saved, at least until caches are cleared). From googling around, I get the impression that setting this parameter is generally considered to be A Bad Idea (posts I've seen aren't specific about why, but my experience offers a clue).

So, how can I re-load an entity that has already been loaded but which I suspect has been changed since being loaded, with minimal other consequences?

Drupal 7, and while core-based answers are best any answers that use the Entity API contrib module or other robust contrib modules are fine.

# Answer
> 5 votes
There is `entity_load_unchanged()`, which does a reset cache itself as well, but however only for that specificy entity id.

This is already available by default in presave and insert/update hooks as $entity-\>original.

# Answer
> 1 votes
The short answer is that it depends on the entity in question, as it's up to the controller how to handle the `resetCache()` method call (if it overrides the default implementation provided in DrupalDefaultEntityController).

It's unclear what you mean by "reset the cache on the server" since all the default entity cache does in the case of core, is reset the $entityCache property on the controller which is just a singleton, so in this case this cache only persists through the lifetime of a single request. If you are using modules that try to persist this cache to the database that could definitely have more implications, but Drupal core by itself should have no affects past the lifetime of a single request by calling entity\_load with reset=TRUE. Even the EntityAPIController provided by the Entity API contrib module doesn't override the core behavior for entity caching.

Further, it's unclear what you are trying to accomplish here, the entityCache in core is only using a static cache anyway, so there is little chance of an entity changing during the duration of a request. I'm also unsure why you are trying to clear the cache while saving an entity, core and EntityAPI modules should always clear the cache while saving an entity. If you are trying to deal with concurrency issues, perhaps it would be better to check the state of the entity prior to invoking save, and then using the locking framework to prevent other updates to the entity while saving, rather than trying to update the entity and clear the cache while it is being saved.

---
Tags: 7, entities, caching
---


# Question
Title: Content Type Fields, populate field with usable data when adding new content
Trying to build a site that majoritly just uses Views and data structures defined within Drupal itself (aka: almost no programming on my end, though if it boiled down to it I will)

Trying to make a Music Album manager. Each album is a content type, and each track is a content type. I have in the Track content type a field called "Album" as a drop-down list which I wish to populate with existing Album records. Problem is, I have no idea how I'm supposed to do that..

Is there a method? is there a module? is there anything I can do? There must be a way somewhere, I would hate to have to drop the entire process here and start from scratch again

# Answer
Don't worry you don't need to start again, this is such a common use case there are actually 3 modules out there that you can choose between.

All 3 will allow you to add a field to your track content type that references an album node. You can choose from a select list, radio/check buttons or autocomplete widget out-of-the-box but I'm sure there are add-ons available if you need them.
> 2 votes

---
Tags: 7, entities
---


# Question
Title: How to add Parent and Child to a Views 3 table format using Groupping Field?
Working with views and a taxonomy list is a popular subject at DA. Many of the examples I've found refer to making a jump list of taxonomy terms and parent terms similar to what you may see with a nested vocabulary on your site's core taxonomy page \[1\] (following the *list terms* link on any given vocabulary). My Views view goal is just as simple and I'm nearly there except for two important requirements.

My Views view is a catalog of node content titles and truncated descriptions categorized by a two level vocabulary. (Think of finding something at a hardware store). The goal is a single page without a sorting requirement (think of it as a *very* small hardware store, so I skipped the answers suggesting wild card sorting in the URL). I'm nearly there using the table format where I've used the setting `Groupping Field Nr. 1: Content: My_Taxo` to organize the node content. This creates a separate table for each group and a caption element for each category.

The first missing requirement is the parent term.

The instructions for a simple vocab list say to add the Relationship, Term parent. This adds several new items to `Fields: add` list page. Unfortunately, none in this list are distinguished as `parent term`, which means I can't easily add a parent taxonomy term field, add a child term field, go back into `Table: Settings` set `Groupping Field Nr.1` to be the parent and `Nr.2` to child and be done with it. (9\_9)

* Content: All taxonomy terms
* Taxonomy term: Name
* Taxonomy term: Rendered Taxonomy term
* Taxonomy term: Term description
* Taxonomy term: Term edit link
* Taxonomy term: Term ID
* Taxonomy term: Weight
* Taxonomy vocabulary: Description
* Taxonomy vocabulary: Machine name
* Taxonomy vocabulary: Name
* Taxonomy vocabulary: Vocabulary ID

The second missing requirement, which may only be correctly answered by the first problem, is the captioned tables do not sort in the same order as the weights set on the taxonomy page list. To try to set this requirement I added, `Sort criteria: (menu_category) Taxonomy term: Weight (asc)`

---

# Answer
> 0 votes
Starting from scratch with a dummy content type that contains just a title and a taxonomy term.

1) Create the simple taxonomy: Category\_hierarchy {i.e. 1, 1.1, 1.2, 2, 3, 3.1};

2) Create the simple content type. {title, taxonomy \[Category\_hierarchy\];

3) Create the view:

> Format: Table
> \+ Settings
> \- Grouping field Nr.1: Category\_hierarchy
>
> Fields
> \+ Content: Title
> \+ Content: Category\_hierarchy
> -- Exclude from display.
>
> Sort criteria
> \+ Content: Title (asc)
>
> Relationships
> \+ Content: Taxonomy terms on node \[1\]
> -- Vocabulary: Category\_hierarchy
> -- \[custom\] Identifier: Category\_hierarchy\_child

\[1\] This is the only taxonomy-type Relationship available.

Results show the node titles grouped by the child relationship as expected.

4) Revisiting the View now that we see what we can simply construct, we try to get the parent term added to the display. Now, under the Relationships section is a whole new list of options titled "Taxonomy term". So we add one more to get the missing relationship, parent.

> Relationships
> \+ Taxonomy term: Parent term
> -- Relationship: Category\_hierarchy\_child
> -- \[custom\] Identifier: Category\_hierarchy\_parent

If we peek into Table's settings, we would hope this might make the new relationship an available option under `Grouping field Nr.1`. But the grouping field options are still only Category\_hierarchy and Title.

Just to be sure I added `Grouping filed Nr.2` with `Category_hierarchy` to see if Views can do something magical and sort out the relationships automatically.

Nope. But it was worth a try. Its clear there must be some other way to populate that menu. Maybe Views has made some kind of magical field we can add from under Fields?

And that's just what has happened. We now have a new type of *available* field, 'Taxonomy term':

Taxonomy term: Name
\- The taxonomy term name.
Taxonomy term: Rendered Taxonomy term
\- The Taxonomy term of the current relationship rendered using a view mode.
Taxonomy term: Term description
\- The description associated with a taxonomy term.
Taxonomy term: Term edit link
\- Provide a simple link to edit the term.
Taxonomy term: Term ID
\- The tid of a taxonomy term.
Taxonomy term: Weight
\- The term weight field
Taxonomy vocabulary: Description
-The taxonomy vocabulary description
Taxonomy vocabulary: Machine name
\- Machine-Name of the vocabulary a term is a member of. This will be the vocabulary that whichever term the "Taxonomy: Term" field is; and can similarly cause duplicates.
Taxonomy vocabulary: Name
\- Name of the vocabulary a term is a member of. This will be the vocabulary that whichever term the "Taxonomy: Term" field is; and can similarly cause duplicates.
Taxonomy vocabulary: Vocabulary ID
\- The taxonomy vocabulary ID

I've crossed out the unlikely candidates. And added each, in turn, to the Field section and looked for the field in Table's settings. Good gravy. They both worked!

I certainly don't expect tutorial answers. But I was already writing up a bug report for another problem I encountered so, my bug is your gain.

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


# Question
Title: Drupal 7.14 on IIS 7.5, MS SQL Server 10.5
I have been tasked with seeing if Drupal can be made to run on IIS (specifically, IIS 7.5 running on Windows Server 2008 R2) and MS SQL Server (2008 R2). I'm aware of Microsoft's WebPI Drupal package, but since we have an existing site which we wish to migrate to this new environment I'd prefer to add the pieces that are needed so that they can go into the source control environment with the others rather than use a black box package. I am doing the experimentation with Drupal 7.14, which is the latest release at this time.

I have got basic PHP scripts to run (Hello World, phpinfo, etc), and installed the sqlsrv driver 7.x-1.2 (recommended at the present time) into Drupal. The Drupal installation process gets as far as to the database settings screen without any complaints. However, if I select MS SQL Server as backend:

* if I enter invalid database credentials I get an error back, as expected.
* if I enter valid database credentials, after clicking proceed I get a HTTP 500.0 error from IIS saying about php-cgi.exe `The FastCGI process exited unexpectedly`.

I have enabled request tracing in IIS and found the error code `GENERAL_READ_ENTITY_END Reached the end of the file. (0x80070026)` in the resulting log file. Googling for the hexadecimal error code produced very little in terms of helpful information.

drupal.org reports 4772 sites reporting using the sqlsrv module, so the module obviously works. Any hints on how to get it to work, preferably other than "use the WebPI packages"?

By setting Instance MaxRequests to 1, keeping Standard Error Mode at ReturnStdErrIn500, disabling friendly errors in IIS and ditto MSIE (thanks for the link @DigitalFire which pointed me in the right direction for this), I was able to get at what I suspect is the actual command output, or at least as close to it as I can easily get in the web browser. What is shown in MSIE's "View Source" is a plain, almost-empty, boilerplate HTML document with an empty body. Before I turned off MSIE's friendly HTTP error messages (who came up with the idea of having that turned on as standard on Server, anyway?) it showed `HTTP 500`, so this is probably pretty close to the truth.

Using SQL Server's Profiler, I traced the database calls made and toward the end was the following, ignoring pure `SELECT` statements:

```
-- repeated a number of times
INSERT INTO system ([filename], [name], [type], [owner], [info]) VALUES (@P1, @P2, @P3, @P4, @P5)

UPDATE system SET [status]=@P1
WHERE  ([type] = @P2) AND ([name] = @P3) AND( ([status] <> @P4) OR ([status] IS NULL ) )

UPDATE system SET [bootstrap]=@P1
WHERE ( ([bootstrap] <> @P2) OR ([bootstrap] IS NULL ) )

INSERT INTO registry ([name], [type], [filename], [module], [weight]) VALUES (@P1, @P2, @P3, @P4, @P5)

```

The final `INSERT` occurs only once, with EventClass `SQL:StmtRecompile`. I'm not sure this helps much...

# Answer
After a lot more digging both by myself and a colleague, we finally ran across what appears to be the answer. In a TechNet Forum post in the thread MSVCR90 fault with Sql Server driver, Pierre Couzy mentioned the issue Error when executing empty queries in PHP 5.3.8 on drupal.org. Attached to that incident report is a suggested patch for the sqlsrv module which changes the substitution for `RELEASE SAVEPOINT` to a non-empty SQL statement in the file sqlsrv/database.inc.

What's interesting is that it looks like this fix is included in mainline 7.x-1.2, whereas both I and my colleague (downloading and installing the module independently over the last few days) apparently were running against version 7.x-1.1 of the sqlsrv module. It sincerely beats me how that happened (I was *sure* I'd downloaded 7.x-1.2), but manually applying the patch to the version that we had downloaded seems to have resolved the issue, and actually running 7.x-1.2 shows the same result.

Hopefully this keeps somebody from beating their head against this same problem.
> 0 votes

# Answer
Try commenting out extension=php\_gd.dll in your php.ini file and try again. I found this article in which the OP had a similar problem.
> 1 votes

# Answer
The first thing I was going to ask was what version of PHP and PHP to SQL driver you were using. We were receiving errors like this when using PHP 2.7 and PHP to SQL 2.x. I recommend getting the PHP drivers from Microsoft through the Web Platform installer and getting the latest version of Drupal and the MS SQL driver from drupal.org. Also if you change the MS SQL driver you must run update.php so the changes can be picked up. I highly recommend using Wincache as it will help your performance and can possibly be used as an alternative query backend. Drupal is kind of a database hog so if you are not using an alternative query backend and Entity Cache then you will most likely have performance issues.
> 0 votes

---
Tags: 7, iis, database
---


# Question
Title: What file and folder permission changes does the Microsoft Web Platform Installer make when it installs Drupal?
I have used the Microsoft Web Platform Installer to install both Drupal 6 and Drupal 7 on my Windows Server 2008 R2 servers running IIS 7.5. (see: http://www.microsoft.com/web/downloads/platform.aspx)

I'd like to know what file and folder permissions WebPI is modifying (and why) and the web.config additions it is making so that I can manually install Drupal under IIS for those times when the default installation parameters need to be tweeked (such as where the databases are housed).

Changes made to PHP to make it play nice with Windows + IIS would also be helpful.

# Answer
You may be interested in this question.

However, a manual install of Drupal has a few variables.

For all versions of Drupal you will need to install PHP. The recommended way to install PHP is with Fast CGI. (That is also how the WebPI installs it.)

Since you are running Server 2008, it is recommended that you use Mirosoft's URL rewriter if you want clean URLs. (That is also how the WebPI installs it.) If you are using Microsoft's URL rewriter, it will automatically look for a web.config file. Drupal 7 ships with a default one, which I believe will work for Druapl 6 as well.

Then, you need a database. For Drupal 6 your only practical option is MySQL. For Drupal 7 you can choose between MySQL and the more native MSSQL.

Once those three items are installed you are pretty much left with permissions. By default IIS uses C:\inetpub\wwwroot\ for all web served files. For IIS to read those files the local IUSR account needs read permissions. To write the local IUSR account needs write permissions. I believe the recommended behavior currently is IUSR gets read permissions to everything in C:\Inetpub\wwwroot. However write permissions are restricted to only where absoultly needed. The traditional location is ..\sites\[sitename\]\files as that is the default location for user uploaded files. However Drupal 7 has a fancy web installer for modules. For that to work ..\sites\[sitename\]\modules and ..\sites\all\modules need to be writeable by the local IUSR account. One final note. For the default Drupal install process to work ..\sites\[sitename\]\settings.php needs to be writeable by the local IUSR account. However, post install it is usually recommended that file be read onle.
> 2 votes

# Answer
I can't provide a specific answer, but I would try running Process Monitor during the installation. It should the provide some of the answers you are looking for.
> 1 votes

# Answer
I highly recommend using WPI to install all the IIS modules necessary like the latest version of PHP, PHP to SQL and Wincache only. Then going to drupal.org to get everything else. I do not think WPI has the most optimal setup and you will have a lot more control of your setup. It is pretty easy once you do it this way a couple times and you really get to understand what configurations are possible. Drupal provides all kinds of features like Multisite, Custom Installation Profiles, Custom DB abstraction layers etc. I find something new and useful every say just by reading their code and using api.drupal.org.
> 0 votes

---
Tags: iis
---


title: Related news block in taxonomy term

text:
# Question
Title: Related news block in taxonomy term
I'm trying to make a related news block on a term page instead of a node. I've done it on a node and it works fine, but when I try to do it on taxonomy term page it makes the whole block disappear.

This is what I have in the contextual filters and what I'm using as my relationship,

and here's whats in my taxonomy,

and this is what's in my content: nid

and finally whats in my relationship.

# Answer
> 1 votes
It looks like the block disappears because no content is returned by the view. You're filtering for both a taxonomy term id and a node id, while only a taxonomy term is present in the url of a taxonomy term page. Since there are no nodes that match the criterium 'no nid' there are no results. I believe this should work if you use only the taxonomy contextual filter. (This is if I'm understanding correctly what you're trying to do).

# Answer
> 0 votes
It does not seem like you have a relationship to do that, you would have to add another relationship to get the term id's node's taxonomy term's nodes. This will be quite a bit of joins and it might be easier to write some SQL first.

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


# Question
Title: Large Binlogs Generated When Reverting Features
We're using features to manage content types and field groups, and every code update, when we perform a `features-revert` to push out the latest CTs and field group changes, we get a huge amount of data written to our binlogs -- a gig about every 10 mins:

```
-rw-rw----. 1 mysql mysql 1073759569 Aug  1 02:31 mysql-bin.000138
-rw-rw----. 1 mysql mysql 1073766800 Aug  1 02:42 mysql-bin.000139
-rw-rw----. 1 mysql mysql 1074139941 Aug  1 02:50 mysql-bin.000140
-rw-rw----. 1 mysql mysql 1073954804 Aug  1 02:59 mysql-bin.000141

```

which quickly locks up our MySQL servers.

What might be causing the large amount of data to be written? What can we be doing on the MySQL side and the Drupal side to keep this in check?

# Answer
> 2 votes
DISCLAIMER : Not a Drupal Expert, Just a MySQL DBA

There are really two classes of answers for this question

* STANDALONE DB SERVER
* MASTER/SLAVE REPLICATION

# **STANDALONE DB SERVER**

If you know you are going to perform a `feature-revert`, the simplest thing to do is this

## StandAlone Method #1 : Disable Binary Logs

* STEP 01) Run `SET GLOBAL SQL_LOG_BIN = 0;`
* STEP 02) Run your `feature-revert`
* STEP 03) Run `SET GLOBAL SQL_LOG_BIN = 1;`

This will disable binary logging during the feature revert and reenable afterwards

## StandAlone Method #2 : Erase All Binary Logs Except the Last One

You could crontab a job that runs this:

```
PURGE BINARY LOGS BEFORE NOW();

```

## StandAlone Method #3 : Erase All Binary Logs

You could crontab a job that runs this:

```
RESET MASTER;

```

# **MASTER/SLAVE REPLICATION**

In standard MySQL Master/Slave Replication, a Master Has Binary Logging Active and the Slave Does Not. You cannot just disable binary logging like you would for a StandAlone DB Server because you need to replicate the DB Changes of the feature-revert.

Here is what to do stem the rise of binary logs and relay logs

## **Replication Master (Manage Binary Logs)**

At the completion of a `feature-revert`, which binary logs are safe to remove so that MySQL Replication can still work and remain intact?

Here is what you do:

* STEP 01) Run `SHOW SLAVE STATUS\G` On the Slave.

For example:

```
mysql> show slave status\G
*************************** 1. row ***************************
             Slave_IO_State: Waiting for master to send event
                Master_Host: 10.64.97.249
                Master_User: replicant
                Master_Port: 3306
              Connect_Retry: 60
            Master_Log_File: mysql-bin.000658
        Read_Master_Log_Pos: 799061333
             Relay_Log_File: relay-bin.003861
              Relay_Log_Pos: 47059
      Relay_Master_Log_File: mysql-bin.000658
           Slave_IO_Running: Yes
          Slave_SQL_Running: Yes
            Replicate_Do_DB:
        Replicate_Ignore_DB:
         Replicate_Do_Table:
     Replicate_Ignore_Table:
    Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
                 Last_Errno: 0
                 Last_Error:
               Skip_Counter: 0
        Exec_Master_Log_Pos: 799061333
            Relay_Log_Space: 47059
            Until_Condition: None
             Until_Log_File:
              Until_Log_Pos: 0
         Master_SSL_Allowed: No
         Master_SSL_CA_File:
         Master_SSL_CA_Path:
            Master_SSL_Cert:
          Master_SSL_Cipher:
             Master_SSL_Key:
      Seconds_Behind_Master: 0
1 row in set (0.00 sec)

```
* STEP 02) Get binary log from `Relay_Master_Log_File`
    + Field #10 of `SHOW SLAVE STATUS\G`
    + That would be `mysql-bin.000658`
* STEP 03) On the Master, Run `PURGE BINARY LOGS TO 'mysql-bin.000658';`

## **Replication Slave (Manage Relay Logs)**

To force a Slave to Throttle the amount of Relay Logs to Just 2GB, add this to the Slave's my.cnf

```
[mysqld]
relay_log_space_limit=2G

```

and restart mysql on the Slave. When a Relay Log is fully processed it is automatically deleted and makes room for the next Relay Log.

# **EPILOGUE**

You should make sure you have this set in /etc/my.cnf on the StandAlone DB Server or Master

```
[mysqld]
expire_logs_days = 3;

```

and restart mysql. This will make sure all binary logs older that 3 days are automatically deleted.

If you are curious and want to know what runs in a `feature-revert` You could

* Look through source code of the `feature-revert` module
* take the binary logs and dump the contents in plain text SQL

Run the following:

```
mysqlbinlog mysql-bin.000138 mysql-bin.000139 mysql-bin.000140 mysql-bin.000141 > Revert.sql
less Revert.sql

```

## **UPDATE 2012-08-09 12:40 EDT**

If you are concerned with point-in-time recovery, you must decide how many days worth of binary logs you are willing to keep.

Here is a scenario: Say you want to be able to revert back up to 7 days ago. You would have to setup the following:

STEP 01) Have the Slave maintain its set of Binary Logs with an expiration of 7 days

Add this to /etc/my.cnf on the Slave

```
[mysqld]
log-bin=mysql-bin
expire_logs_days=7

```

STEP 02) service mysql restart

STEP 03) Perform a midnight Backups on the Slave as follows

* STOP SLAVE;
* FLUSH LOGS;
* mysqldump on the Slave
* START SLAVE;

STEP 04) Delete backups older than 14 days

Once you have Steps 3 and 4 automated, you must let mysql rotate the binary logs on the Slave. You should not manually delete the binary logs on the Slave. Keep in mind that point-in-time recovery is not automatic. It is rigorous manual process.

## Would you like a description of a point-in-time recovery ??? Here we go...

Let's say you have the following

* It's August 9, 2012 12:11 PM
* run mysqldumps on the Slave every night at midnight
* each backup is named by date Backup\_99999999.sql in /backups
* and you have the following list of binary logs on the Slave

_

```
-rw-rw---- 1 mysql mysql 1073742269 Aug  2 11:22 mysql-bin.001789
-rw-rw---- 1 mysql mysql 1073762807 Aug  2 16:22 mysql-bin.001790
-rw-rw---- 1 mysql mysql 1073742048 Aug  2 21:28 mysql-bin.001791
-rw-rw---- 1 mysql mysql 1073741969 Aug  3 06:34 mysql-bin.001792
-rw-rw---- 1 mysql mysql 1073741954 Aug  3 11:20 mysql-bin.001793
-rw-rw---- 1 mysql mysql 1073742182 Aug  3 16:19 mysql-bin.001794
-rw-rw---- 1 mysql mysql 1073742228 Aug  3 21:37 mysql-bin.001795
-rw-rw---- 1 mysql mysql 1073753003 Aug  4 06:32 mysql-bin.001796
-rw-rw---- 1 mysql mysql 1073742100 Aug  4 13:18 mysql-bin.001797
-rw-rw---- 1 mysql mysql 1073741891 Aug  4 18:56 mysql-bin.001798
-rw-rw---- 1 mysql mysql 1073742424 Aug  5 06:12 mysql-bin.001799
-rw-rw---- 1 mysql mysql 1073742017 Aug  5 18:35 mysql-bin.001800
-rw-rw---- 1 mysql mysql 1073741952 Aug  6 05:27 mysql-bin.001801
-rw-rw---- 1 mysql mysql 1073757571 Aug  6 13:00 mysql-bin.001802
-rw-rw---- 1 mysql mysql 1073742172 Aug  6 17:35 mysql-bin.001803
-rw-rw---- 1 mysql mysql 1073742067 Aug  7 00:35 mysql-bin.001804
-rw-rw---- 1 mysql mysql 1073777487 Aug  7 10:45 mysql-bin.001805
-rw-rw---- 1 mysql mysql 1073791986 Aug  7 15:51 mysql-bin.001806
-rw-rw---- 1 mysql mysql 1073742035 Aug  7 20:37 mysql-bin.001807
-rw-rw---- 1 mysql mysql 1073741978 Aug  8 05:28 mysql-bin.001808
-rw-rw---- 1 mysql mysql 1073742217 Aug  8 10:30 mysql-bin.001809
-rw-rw---- 1 mysql mysql 1073742422 Aug  8 14:41 mysql-bin.001810
-rw-rw---- 1 mysql mysql 1073743447 Aug  8 18:47 mysql-bin.001811
-rw-rw---- 1 mysql mysql 1073742241 Aug  9 00:36 mysql-bin.001812
-rw-rw---- 1 mysql mysql 1073741985 Aug  9 08:45 mysql-bin.001813
-rw-rw---- 1 mysql mysql  743967477 Aug  9 12:10 mysql-bin.001814

```

You want to reload the Master going back to August 5, 2012 02:30 PM

Here are you steps

STEP 01) Take all binary logs that encompass August 5, 2012 from 12:00AM to 2:30PM. This would be binlogs mysql-bin.001799 and mysql-bin.001800. These are used because

* PRINCIPLE : the first write of a binlog is also the last write of the previous binlog
    + the last write to mysql-bin.001798 is Aug 4 18:56 (6:56PM) 2012-08-04 18:56:00
    + the first write to mysql-bin.001799 is Aug 4 18:56 (6:56PM) 2012-08-04 18:56:00
    + the last write to mysql-bin.001799 is Aug 5 06:12 (6:12AM) 2012-08-05 06:12:00
    + the first write to mysql-bin.001800 is Aug 5 06:12 (6:12AM) 2012-08-05 06:12:00
    + the last write to mysql-bin.001800 is Aug 5 18:35 (6:35PM) 2012-08-05 18:35:00

The range 2012-08-04 18:56:00 to 2012-08-05 18:35:00 is the narrowest range that surround 2012-08-05 00:00:00 to 2012-08-05 14:30:00. This is why binlogs mysql-bin.001799 and mysql-bin.001800 are the correct choices

STEP 02) Generate all the SQL that ran August 5, 2012 from 12:00AM to 2:30PM

```
mysqlbinlog --start-datetime="2012-08-05 00:00:00" --stop-datetime="2012-08-05 14:30:00" mysql-bin.001799 mysql-bin.001800 > ForwardChanges.sql

```

STEP 03) Make a copy of the August 5, 2012 midnight backup to PITR.sql

```
cp /backups/Backup_20120805.sql PITR.sql

```

STEP 04) Append ForwardChanges.sql to PITR.sql

```
cat ForwardChanges.sql >> PITR.sql

```

STEP 05) Load PITR.sql into the Master

```
mysql -h IPAddressOfMaster -u ... -p... < PITR.sql

```

When the script is done, the database will be in the state it was as of August 5, 2012 2:30PM

Pretty easy, huh ???

---
Tags: 7, database, features
---


title: How Reliable is node_save?

text:
# Question
Title: How Reliable is node_save?
When using node\_save, how sure can one be that it did what it was supposed to do?

At the moment after any call to node\_save I have been checking that the required property did succesfully update. For example:

```
$node->field_some_field['und'][0] = array('tid' => $some_taxonomy);
node_save($node);

if($node->field_some_field['und'][0]['tid'] == $some_taxonomy) {
    return TRUE;
} else {
    return FALSE;
}

```

Is this necessary? Or is there a better way to perform the check?

Edit: As an example, say I want to update a node's taxonomy programatically - it would be useful to know if it worked or not. I think it's just bad in general for things to fail silently.

# Answer
I think you have to believe that `node_save()` is doing its job. But, if you don't, `node_save($node)` is declared as sending $node by reference, so, if anything changes `$node` during the `node_presave()` hook, it will be reflected in `$node` after the fact. That notwithstanding, if you wanted to be perfectly sure, you could do something like:

```
$nid=$node->nid;
node_load(NULL, NULL, TRUE);
$node=node_load($nid);

if ($node->.....

```

which would clear any node caches in your page and then reload the node from the database before your `if` check.

ADDITION:

From your example, the failure logic imho should be in your generation of the taxonomy value, not in worrying about if `node_save()` has or hasn't done its job. For example:

```
   // assuming we have $node populated

   $some_taxonomy=programmatically_created_tid($args);

   if ($some_taxonomy !== FALSE) {
     $node->field_some_field['und'][0] = array('tid' => $some_taxonomy);
   } else {
     drupal_set_message(....
     watchdog(.....
   }

```

where your function looks something like this:

```
   function programmatically_created_tid($args) {

     // do whatever logic is necessary to generate the tid

     if ($success) { // success
       return $tid;
     } else {
       return FALSE;
     }
   }

```

would alert the user to the problem you are actually concerned about.
> 1 votes

---
Tags: nodes
---


title: TreeView with checkboxes

text:
# Question
Title: TreeView with checkboxes
I need to create a Tree View Menu with checkboxes, showing values taken from the database. I want to use the Collapsible Checkbox Tree. A demo of the jQuery plugin is available here.

# Answer
> 4 votes
If this is a listing of taxonomy terms, you could giva a try to the Term Reference Tree module. At any rate you could just carefully theme a view, tossing out all markup that is unnecessary or even could mess up with jQuery plugin.

# Answer
> 0 votes
It depends on what the tree is for. I don't know of a versatile all round module that just works that turns any type of Drupal-generated `<ul>` or `<ol>` into a tree, but individual use cases for trees have their own modules. Artur's mentioned Term Reference Tree for taxonomy, and Better Exposed Filters supports javascript tree plugins like you mention for Views exposed filters (though it's not quite as simple as just working out of the box).

For other cases, like checkboxes in content body, etc, most javascript tree plugins are actually pretty easy to implement in Drupal the normal way. Usually you just need to make sure that the `<ul>` or `<ol>` has a certain class (Views etc have options to give content classes, and most Wysiwyg editors have optional dropdown menus of classes you define that can be added to inline content), and then, in custom javascript in your theme (e.g. scripts.js) select that class in jQuery and run the tree library's function on it however they say in their document.

Normally, the only difference between the javascript code in the library's documentation and the javascript code you'll use on a Drupal site is that you wrap it in `Drupal.behaviors` instead of `$(document).ready`, so that it re-applies if Drupal updates a page. I can't find the specifics of the javascript tree library you mention (links just point to a design agency site?), but in Drupal 7 it'll usually look something like this:

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

    // assuming the function is called 'tree' - check their docs!
    $('.some-class', context).tree({
      some: 'options',
      more: { 'options', 'go', 'here' }
    });

  // do other things...

  }
}

```

---
Tags: forms
---


# Question
Title: One submit button posting to multiple functions
I am displaying a form inside a block and I want it to submit to multiple functions, namely the original submit functions and in addition my own pm\_form\_submit. Yet I can't get it to work... you can submit to multiple functions right?

In the case bellow only "Test Form Submit" (the original submit function) is displayed.

Submit button of my test form:

```
function test_form_form ($form,&$form_state){
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );

  return $form;
}

```

My code for displaying the form in a block:

```
$form = drupal_get_form ('test_form_form');

//add our submit function (both are here just to test)
$form ['#submit'][] = 'pm_form_submit';
$form ['submit']['#submit'][] = 'pm_form_submit';

$output .= drupal_render ($form);
return $output;

```

My submit functions: (the pm\_form submit is in the same file where I alter the form and the test\_form\_form\_submit is in the file where the form is generated)

```
function pm_form_submit ($form, &$form_state) {
  drupal_set_message('pm_form_submit');
}

function test_form_form_submit(&$form, &$form_state) {
  drupal_set_message('Test Form Submit');
}

```

when I print\_r the $form array I can see the following:

```
[submit] => Array
    (
        [#type] => submit
        [#value] => Submit
        [#input] => 1
        [#name] => op
        [#button_type] => submit
        [#executes_submit_callback] => 1
        [#limit_validation_errors] =>
        [#process] => Array
            (
                [0] => ajax_process_form
            )

        [#theme_wrappers] => Array
            (
                [0] => button
            )

        [#defaults_loaded] => 1
        [#tree] =>
        [#parents] => Array
            (
                [0] => submit
            )

        [#weight] => 0.001
        [#processed] => 1
        [#required] =>
        [#attributes] => Array
            (
            )

        [#title_display] => before
        [#id] => edit-submit
        [#ajax_processed] =>
        [#sorted] => 1
        [#submit] => Array
            (
                [0] => pm_form_submit
            )

    )

...
[#submit] => Array
    (
        [0] => test_form_form_submit
        [1] => pm_form_submit
    )

```

# Answer
> 2 votes
You can't add submit handlers to form after drupal\_get\_form() is called, because they will not be processed.

You need to add submit handler in hook\_form\_alter(). If you want add this handler only in specific cases, you can add cutom parameter to drupal\_get\_form()

Code in block:

```
$form = drupal_get_form('test_form_form', 'add_pm');
$output .= drupal_render($form);
return $output;

```

Code in custom module:

```
function MODULE_form_alter(&$form, &$form_state, $form_id) {
   if (($form_id == 'test_form_form') && ($form_state['build_info']['args'][0] == 'add_pm')) {
     // add custom submit only if form was called with parameter.
     $form ['#submit'][] = 'pm_form_submit';
   }
}

function pm_form_submit($form, &$form_state) {
  drupal_set_message('pm_form_submit');
}

```

---
Tags: 7, forms
---


title: How do I create relative menu links?

text:
# Question
Title: How do I create relative menu links?
I am busy working on a site on my localhost that needs to link to some content that is separate from Drupal.

I have the current menu paths set up like this: `http://mylocalsite/the_folder_for_the_other_content`. If I try `<front>/the_folder_for_the_other_content` or `/the_folder_for_the_other_content` or `the_folder_for_the_other_content`, I get the error "The path 'whatever\_I\_use' is either invalid or you do not have access to it."

When I go live I obviously need all the menu items to point to `http://myrealsite/the_folder_for_the_other_content`.

How can I set it up so that I won't have to edit all the menu paths when I go live?

# Answer
> 4 votes
kiamlaluno's answer did not quite work for me. Using %menu\_tail produced a storm of errors that the menu\_tail\_load function was having problems with missing arguments:

```
Warning: Missing argument 2 for menu_tail_load(), called in  ... /includes/menu.inc on line 579 and defined in menu_tail_load() (line 827 of ... /includes/menu.inc).
Warning: Missing argument 3 for menu_tail_load(), called in ... /includes/menu.inc on line 579 and defined in menu_tail_load() (line 827 of ... /includes/menu.inc).

```

What did work for me was

```
function allow_menu_links_menu() {
  $items = array();
  $items['sites/d8/files/%'] = array(
    'title' => 'Folder Content',
    'page callback' => 'allow_menu_links_cb', /* never called */
    'access callback' => TRUE,
  );
  return $items;
}

```

Then, I could serve up files in the sites/d8/files folder (and subfolders) using menu items with paths like `sites/d8/files/Documents/MyFile.pdf`

The menu system will then generate a link like `href="/sites/d8/files/Documents/MyFile.pdf"`

If you don't use the custom menu module, the menu system will reject a path starting as above.

If you try to use a path like `http:sites/d8/files/Documents/MyFile.pdf` , it will produce a link like `href="http:sites/d8/files/Documents/MyFile.pdf"`, which will work when you are at the root of the site, but when you are on a content page, the browser will interpret the url relative to the content page, and it will not work.

If you use a path like `http:/sites/d8/files/Documents/MyFile.pdf`, the menu system will accept it, but the menu system will produce a link like `href="http:/sites/d8/files/Documents/MyFile.pdf"` , which the browser (at least Safari) will interpret as `href="http://sites/d8/files/Documents/MyFile.pdf"` , and fail trying to find the server named "sites".

(On further investigation, the reason the code using menu\_tail fails is that you need to add the 'load arguments', as noted here: http://api.drupal.org/api/drupal/includes--menu.inc/function/menu\_tail\_load/7 . If you add `'load arguments' => array('%map', '%index'),` to the definition of $items in kiamlaluno's code, it will work. The issue of whether menu\_tail\_load should require the explicit load arguments is also discussed here: http://drupal.org/node/298561)

(Don't forget to enable your new module, or the menu system will not accept the new links)

# Answer
> 5 votes
When you add a new link, the link is validated from menu\_edit\_item\_validate(), which calls drupal\_valid\_path() to check if the path is valid, or it can be accessed from the user.
`drupal_valid_path()` returns `TRUE` if

* The path is `<front>` (`<front>/directory`, or similar paths are excluded)
* The path is an external path (the function url\_is\_external() returns `TRUE`)
* The path is associated with a menu callback

Apart from using absolute URLs, the only solution is to have a custom module that defines a menu callback associated with the path you want to use.
When you use the URL that points to a file, or a directory, the web server should show that file or directory, without invoking Drupal. That is what happens with Apache, as the .htaccess file that comes with Drupal contains the following directives:

```
# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

```

In your case, the custom module should contain code similar to the following:

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

  $items['the_folder_for_the_other_content/%menu_tail'] = array(
    'title' => 'Folder content',
    'page callback' => 'mymodule_view',
    'access callback' => TRUE,
    'load arguments' => array('%map', '%index'),
  );

  return $items;
}

```

You can use any values for *title* and *page callback*, as that menu callback should never be called. The value of *access callback* says to Drupal that every user has access to that menu callback.

As an alternative you can define a menu callback associated to "alias\_for\_directory/%menu\_tail" that redirects the user to the directory you want they see (using drupal\_goto()). I would use this solution when the server does not use the content of .htaccess, and it would invoke Drupal even when the URL is pointing to an existing file or directory.

# Answer
> 3 votes
For me the following did the trick (on drupal 6).

I want to direct to another URL on the same domain, let's say Drupal is running on `http://www.example.com` and I want to have a link to `http://www.example.com/frontend`

In the menu item, please enter as path:

```
http:/frontend

```

The drupal menu will link to: `http://www.example.com/frontend`

When you use https, you should enter https:/frontend in the path field for the menu item.

# Answer
> 1 votes
I used sql to replace the link in the menu structure:

```
UPDATE menu_links SET link_path = replace(link_path, "livesite.com", "localhost.com");

```

Not sure if I needed to do this but I then flushed the menu caches.

# Answer
> 1 votes
I resolved my link issues with the following:

http://groups.drupal.org/node/210308 and http://drupal.org/node/372252

It turns out my theme was printing the menu incorrectly so that all items were relative to my current location (ie admin/logout, instead of /logout).

Hope this helps.

---
Tags: routes
---


# Question
Title: Using jQuery .ajaxstart with views exposed filter
To start with, my goal was to alter the ajax loading behavior in views exposed filter (Druapl 7 and Views 7.x-3.3) and this question pretty much sorted that one out: How do I change the ajax loading behaviour in Views?

Here comes the problem, the jQuery .ajaxStart and .ajaxSuccess doesn't seem to fire when i change the exposed filter in the view. I get my custom.js file to load correctly and this simple code works just fine:

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

      alert('message');

    }
  };
})(jQuery);

```

but replacing my alert message with this does not:

```
$('#views-exposed-form-produkter-3-kol-page', context).ajaxStart(function(){
        $('#views-exposed-form-produkter-3-kol-page,div.view-id-produkter_3_kol', context).fadeTo(300, 0.5);
      });
      $('#views-exposed-form-produkter-3-kol-page', context).ajaxSuccess(function(){
         $('#views-exposed-form-produkter-3-kol-page', context).fadeTo(300, 1.0);
         $('div.view-id-produkter_3_kol', context).css('opacity', 0.5).fadeTo(300, 1.0);
      });

```

I have also tried to use $(document).ajaxStart without success. The fading also works if i remove the ajaxStart and allow it to fade when page is loaded.

So, if i could get the ajaxStart and Success to fire, everything else should work like I wanted it.

(This is my first question here, so I hope I've managed to do it the right way)

# Answer
I found another js file that was causing the error, decided to live without it and everything works after removing it.

So, if someone encounter errors like this, change the the default theme and see if that solves the problem, then you know if the issue is within your custom theme or somewhere else.
> 0 votes

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


title: Ad-hoc content access restriction

text:
# Question
Title: Ad-hoc content access restriction
is there a way to restrict content access to a specific subset of users upon node creation without having to create a specific user role and/or organic group?

For instance having a list of users to refer to upon node creation, and allowing ONLY them to view/visit/edit the node.

# Answer
> 3 votes
As mentioned above, the Node Access User Reference module does exactly that. You specify a list of user and grant them actions upon the node. Awesome.

# Answer
> 1 votes
as far as I am concerned, you can use these modules to achieve what you want :)

Content Access module

Workbench

---
Tags: 7, users
---


# Question
Title: How to display module ouptput in a page with content
I would like to display my module otuput in one page. The only solution I found till now is to use iframes. Is there some better solution?

I created a module to display a map with branches, branches are stored in DB. But before and after this map there should be some content, like text or pictures.

I hope there is a posibility. Maybe with blocks?

# Answer
If the code for output your result is not so big than you can put the code in block and show that block on any page you want.
> 0 votes

---
Tags: google-maps
---


# Question
Title: How do I cache an object loaded through SOAP from a third party that I use in forms?
I am loading and object that I use to populate a form. Then on form submit I return some of the fields through SOAP back to the third party. On submit the form building function gets called and loads the object then the submit function gets called and loads the object again. How do I cache the object so that it is only loaded once but available to both or more function to act on it.

# Answer
Both answers so far a very good. There is an additional method which is worth noting. static caching.

there a few places in Drupal core which use static caching and there is even a small api to support it in D7. the `static` keyword in PHP is a scope which is local to a function but remains between function calls.

So if you have a method to load your SOAP object you can set it as a static variable in the loading method

```
function my_loader($id) {
  // Initialize a static variable.
  static $loaded_items = array();
  // Check to see if object with $id has been loaded
  if (!is_set($loaded_items[$id]) P
    // code to load $soap_object;
    $loaded_items[$id] = $soap_object;
  }
  // Return the item
  return $loaded_items[$id];
}

```

You can see it in action in Drupal core in \_menu\_build\_tree(). This only lasts for the duration of a request, but it can be handy with a framework where you are not sure when, or how many times a loader may be called.

**protips**

```
$trees = &drupal_static(__FUNCTION__, array());

```

The `drupal_static()` method allows for static variables to be accessible from everywhere. This stops every function which declares static variables from having a clear flag. So if you save your soap object you can clear the static cache.

The `__FUNCTION__` magic word is the name of the function currently being executed.

The `&` before the function passes the return value by reference so that changes to $trees will be changed in the static variable in the function `drupal_static()`
> 2 votes

# Answer
Would it not be possible for you to simply pass off the data you need in fields of `#type => value`? These are passed safely behind the scene through the entire form submission process, acting in a sense as the cache you are striving for. Consider the following simplistic example :

```
$form['soap_data_email'] = array('#type' => 'value', '#value' => $soap_data_email);
$form['soap_data_name'] =  array('#type' => 'value', '#value' => $soap_data_name);

```

After submission, all your soap object's values would be available in the validation and submit callbacks of your form through the usual `$form_state['values']['soap_data_email']` and `$form_state['values']['soap_data_name']` array.

If you have many variables this could all be factorised to be more efficient, but this should give you the basic idea.

This is the simplest way I can think of that lets you cache your data all across the form validation and submission process.
> 4 votes

# Answer
If you want to have cache that will be accessible not only in one form, but all over the site - you can use Drupal Cache API

Here is example for your case.

While creating form you save object in cache:

```
cache_set('my-variable_name', $object);

```

Then on submit handler you can load object from cache:

```
$object = cache_get('my-variable_name');

```
> 0 votes

---
Tags: caching
---


# Question
Title: Can jPlayer be integrated with the Video module?
With the Video module, the admin panel shows a large list of video formats with dropdowns allowing the user to select one of the supported players. The list that is included consists of:

* Divx
* Quicktime
* RealMedia
* FLV flash
* SWF flash
* Director/Shockwave
* Windows Media
* Theora

I installed the jPlayer module and put the jPlayer library into /sites/all/libraries. Is there an established way to get jPlayer to appear in this list, or to otherwise integrate Video with jPlayer?

# Answer
> 1 votes
I hope I can help you

First of all.

The jplayer you have installed

here is a tutorial that will help get up and running with that Jplayer Tutorial

Second of all, the video module you have, Is for making a new filefield with a new content type, make a view that shows the filefield. You should either choose one of the following options. and not both of them.

Hope this helps. I am currently myself working on something smiliar.

I would also like to help you by showing you this link

Its a Drupal distribution called Octopus : Octupus Drupal

Hope this helps :)

---
Tags: files
---


# Question
Title: How do I setup multiple sites with one database in Drupal 7
My hosting provider limits the number of databases. I would like to setup several small sites with their own theme, modules, etc. The scripting for setting up drupal sites from my host provider uses simplescripts.com but when I go to do an install, only Drupal 5 has the table prefix option. Drupal 6 and 7 installs do not allow the table prefix.

I found this good reference, but it wasn't explicit as to whether or not the Drupal version mattered. How do I get Drupal to use table prefixes so I can install multiple drupal installations in the same database schema?

I guess I don't see how to add the table prefixes to a particular install after the simplescripts.com has made the initial installation.

Is it even possible to setup multiple sites in Drupal 7 using one database? If so, is it a matter of using the simplescripts.com to install the files and then moving the installed files to the location I need them to be in? or must I install Drupal 7 manually for each site?

# Answer
Yes it is possible to setup a multiple sites in Drupal 7 using one database.

All though its not optimale. compared to the other option to run it in different databases.

Drupal multiple sites tutorial

Complete tutorial on setting up sites in Drupal 7

Hope it helps :)
> 5 votes

---
Tags: database, multi-sites, installation
---


# Question
Title: Node Acess User Reference and Organic Groups permissions
I am using Organic Groups to give group-specific content to users.

The groups' permissions do not allow simple group members to edit group content.

By using the Node Acess User Reference module I wanted to grant permission to specific group members to edit specific nodes on an ad-hoc basis.

The devel information that I get is that allthough that rule works, it is being overriden by OG's permissions thus still not allowing the user to edit the node.

# Answer
> 1 votes
Nevermind, http://drupal.org/node/1171834#comment-6019078 answers it.

---
Tags: 7, organic-groups, users
---


title: Export content types using features

text:
# Question
Title: Export content types using features
I am struggling with it, but I can't do it by myself. Google doesn't gave me links for tutorials other modules doesn't help me too.

I would like to export content types definition from Drupal site to another.

Could someone give me any hint how to do it?

# Answer
Sure,

Install the features module and then you go to structure -\> features

Click on "create new feature"

Give it a name and then on Edit component you can select what you want to export. Select Content-type: node and you will see a list of all your content types, check the content types you want to export,( when you click the checkbox, you will see the ajax image wait till it disappear) and then click on download feature. Version 7.x-2.x has got a better UI and it's possible to download it straight into your sites/all/modules/features folder if you give web server permission to write into that folder.

The feature you downloaded works like a module so upload the folder you downloaded into sites/all/modules/features, go to you module page and enable it.

You will find your content type with all the fields.

I suggest you to play with features module to understand all his potential.
> 23 votes

---
Tags: 7, nodes, features, importing-exporting
---


# Question
Title: Parse feed items into nodes, but also get full html from link by scraping the site
I am using feeds to create nodes from an rss feed. I also use feeds imagegrabber to grab the image from the webpage. But I can't seem to follow the links to each item and scrape it.

The feeds usually only show the teaser text, but I want to scrape the page with the full text and save it.

Can anyone explain to me how this is done?

Here is an example feed: http://feeds.washingtonpost.com/rss/homepage

# Answer
This doesn't seem possible at the moment, so I used Yahoo Pipes to create a new rss feed based on the original scraped the full page for each rss item and sustituted the description with the content of the full article.
> 0 votes

---
Tags: 7, feeds
---


# Question
Title: Displaying nodes and forms in a block for processing
I am trying to build a module that enables users to use Drupal as a front end for a BMP engine. Users will be able to use Drupal content in their Processes. For example filling out forms or approving nodes for publication. Filling out a form or approving something will be the completion of a step.

My idea is to display the Drupal content (node, form) in a block and display the step description above it and a button underneath it stating: "Complete Step".

The BMP engine tells Drupal what to display in the block through a node\_id or a form\_id. Adding a button to a form seems quite easy (even though a way that will always removing/replace the button that calles hook\_form\_submit is welcome). The Problem is displaying this same button under a node.

After trying a lot of things I am down to this (and it does not work yet but it should not be that big a problem...)

```
//get the node object
$node_object = node_load ($step['DrupalID']);

//get our node submision form
$form = drupal_get_form('pm_form_form');

$output = drupal_render($form);
$output .= drupal_render(node_view ($node_object, true));

```

Yet it feels like a hack... can anyone suggest a better idea?

# Answer
> 1 votes
The Form Block module lets you easily create "block versions" of your add node forms. These block versions are still forms like any other in Drupal so you can use hook\_form\_alter to change the Submit button text to whatever you like and/or add any submit/validation handlers as required.

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


# Question
Title: Content type - manage display based on roles?
Is there a way to define a custom display setting under Manage Display on a content type? I want to hide certain fields (when viewing, not editing) from non-authenticated users. I know I can do this with a custom .tpl file; just wondering if there's another way (without additional modules.)

# Answer
> 2 votes
As far as implementing a new view mode yourself goes it's pretty easy, without any contrib modules.

You can implement `hook_entity_info_alter()` to add a custom view mode to any entity. For example this code adds a new view mode called "Test View" to the node entity type:

```
function MYMODULE_entity_info_alter(&$info) {
  $info['node']['view modes']['test_view'] = array(
    'label' => 'Test View',
    'custom settings' => TRUE
  );
}

```

After a cache clear that view mode will appear in all the places you'd expect (manage display, views, etc.)

---
Tags: entities, nodes
---


title: Page not found return false

text:
# Question
Title: Page not found return false
Im using a custom query to display some content. This query uses url arguments as MySQL variables.

Usually when I create a link with the variables the page does not exist and it returns a 404 error.

Is there a way of creating a page on certain urls to avoid getting an "page not found"?

EDIT: To be more specific

The query is something like

```
SELECT * WHERE node.type = '.arg(0).' AND node_data_field_type.field_type = '.arg(1).'

```

The url intended would be: **example.com/exhibition/speacial\_feature** or **example.com/program/speaker\_series**

The link exhibition/speacial\_feature or program/speaker\_series are not found.

# Answer
Supposing that example.com is a site running Drupal, what Drupal does when you try to access example.com/exhibition/speacial\_feature is:

* Verify exhibition/speacial\_feature is a path alias
* Verify there is a menu that uses exhibition/speacial\_feature as path
* Verify a module define a menu callback for exhibition/speacial\_feature

If none of the conditions is verified, then Drupal returns a 404 error.

In your case, as you want to execute code when a path is entered, you need to create a module that defines a menu callback.

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

  $items['mymodule/%/%'] = array(
    'page callback' => 'mymodule_abc_view',
    'page arguments' => array(1, 2),
  );

  return $items;
}

function mymodule_page_view($first, $second) {
  // Execute the query, and show the result.
}

```

The code for `hook_menu()` I shown is the minimum required; see hook\_menu() for more information.

As also noted from Berdir, you don't concatenate input given from a user to obtain the query to execute, as that causes SQL injection. You need to use query parameters, which are supported in any Drupal version. Also, with static queries, the name of the database tables are surrounded by *{* and *}*.
> 1 votes

# Answer
When a request is made to a Drupal site, it looks up in the menu router and the url table to see if that link exists. Since you are using a custom query, it will fail to recognize your new pattern. You can either create a normal node, a URL alias as per your requirements, and change the content in the node.tpl.php file.

Otherwise, you can create a menu. Say your custom URL is foobar/X, where X is varying.

```
 $items['foobar/%'] = array(
   'page callback' => 'foo_page',
   'page arguments' => array(1, 'foo'),
 );

```

Then, in the page callback, fetch the custom content and return it.
> 0 votes

---
Tags: uri
---


# Question
Title: What's the accepted way to add different prices to commerce products?
The standard model for an e-commerce system is to have an RRP price and sale price (and when relevant a cost price).

I know there are product pricing rules to apply discounts, but this is a pretty un-intuitive solution as it requires the adding of a new rule for every single product that needs a discount.

Plus 'discount' isn't the right way to look at this particular situation conceptually in my opinion. I don't want the users to have to work out what the discount should be when all they want is to set a static 'special offer' price. It also doesn't make sense to refer to the cost price as a discount of any kind.

What I'd like to have is 2/3 (or as many as I want to be honest) different price fields on the product to represent the different prices. The system would then obviously display the correct price at the correct time based on some sort of rule.

I know I can just add new fields to the product bundle but their relationship to the overall price of the product will obviously not exist until "something" happens.

This seems like a pretty standard use case...has anyone come up with a good solution? Code and UI solutions both welcome.

# Answer
As mentioned you can add new field to your product type:
Next enable `commerce_product_pricing_ui` module or just add new Rule on event “Calculating the sell price of a product”. Rule looks like this (full size):
You can control the order of Product Pricing rules by Rules weight.

But I prefer to create field “Old price” (or “Common price”) and to add simple description:

> If you want to create special offer for this product, please, place new price in the Price field and move crossed out price to “Old price” field.

So, “Old price” is only for theming. It works for small commerce sites and I don't need any crazy Rules.
> 6 votes

---
Tags: commerce
---


# Question
Title: How to run code on every page request - after modules are loaded?
I want to write a module that redirects visitors to another page based on the geoip module.

There is hook\_boot() which runs on all page requests, but before the modules are loaded. There is also hook\_init() which isn't run on cached pages. I'd need something that runs after all modules are loaded - but before cached pages are served. Did I miss another hook in the documentation?

Note: Turning off the cache is not an option for performance reasons.

# Answer
> 7 votes
I think it's best to summarize the options in a new answer:

First off: There is no hook that's executed between `hook_boot()` and `hook_init()`. That means there is no hook that has a fully initialized drupal environment and is executed regardless of the page cache. -- thanks @kiamlaluno for clearing that up.

There are still two methods to get a similar effect:

1. It's possible to selectively load include files or modules in `hook_boot()` using module\_load\_include() or drupal\_load() respectively. This is especially useful if you only need some rather self-contained functionality which isn't spread over a lot of files.
2. The module dynamic\_cache can be used to dynamically deactivate the cache on certain page loads by setting `$GLOBALS['conf']['cache'] = FALSE` in `hook_boot()` and then do the heavy lifting in `hook_init()`. - thanks to @David Meister

The two methods can also be combined to narrow down the number of requests where caching needs to be disabled: Use a minimal-bootstrap in `hook_boot()` to determine exactly when caching needs to be disabled.

The dynamic\_cache module seems rather hackish though. So I'll stick to method 1 for now.

# Answer
> 7 votes
> I'd need something that runs after all modules are loaded - but before cached pages are served.

You cannot, as loading all the modules is the last phase of Drupal bootstrap, while cached pages are served in the second bootstrap phase.

See the code used by drupal\_bootstrap().

```
  switch ($current_phase) {
    case DRUPAL_BOOTSTRAP_CONFIGURATION:
      _drupal_bootstrap_configuration();
      break;

    case DRUPAL_BOOTSTRAP_PAGE_CACHE:
      _drupal_bootstrap_page_cache();
      break;

    case DRUPAL_BOOTSTRAP_DATABASE:
      _drupal_bootstrap_database();
      break;

    case DRUPAL_BOOTSTRAP_VARIABLES:
      _drupal_bootstrap_variables();
      break;

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

    case DRUPAL_BOOTSTRAP_PAGE_HEADER:
      _drupal_bootstrap_page_header();
      break;

    case DRUPAL_BOOTSTRAP_LANGUAGE:
      drupal_language_initialize();
      break;

    case DRUPAL_BOOTSTRAP_FULL:
      require_once DRUPAL_ROOT . '/includes/common.inc';
      _drupal_bootstrap_full();
      break;
  }

```

If you look at \_drupal\_bootstrap\_page\_cache(), you will notice that `hook_boot()` is eventually invoked before the page is served from the cached data, while `hook_exit()` is eventually invoked after the page is served from the cached data. Those hooks are invoked if the value of the Drupal variable "page\_cache\_invoke\_hooks" is `TRUE`.

```
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('boot');
  }
  drupal_serve_page_from_cache($cache);
  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_exit.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('exit');
  }

```

Notice that in Drupal 8, `hook_boot()`has been removed and so does `hook_exit()`. This means Drupal 8 will never invoke those hooks.

# Answer
> 1 votes
I know you said that turning off the cache is not an option but the Dynamic Cache module lets you turn off the cache conditionally in hook\_boot which might actually be an option as the cache will only be off for users you're about to redirect - http://drupal.org/project/dynamic\_cache

If you can get the logic you need out of GeoIP in hook\_boot() then you can turn off the cache for that page load and just do a drupal\_goto() in hook\_init().

# Answer
> 1 votes
Or you could just load the modules in `hook_boot()`, then drupal won't have to load them later and you can do whatever you want with the modules. I understand that this is a bit irregular, but programming in Drupal seems to require several irregular ways of doing things.

# Answer
> 0 votes
You can try hook\_exit which is run even on cached pages. I'm not sure if drupal\_goto works inside it but if it doesn't you could do what the boost module does and use `header('Location: mynewurl')`.

---
Tags: 7, hooks
---


# Question
Title: How do you call ubercart's shopping cart block?
I have a need to manually call and place the UC shopping cart block. I know that to call the block it would be something like this;

```
<?php
$block = module_invoke('block', 'block_view', #);
print render($block);
?>

```

I tried;

```
<?php
$block = module_invoke('block', 'block_view', 'cart');
print render($block);
?>

```

and

```
<?php
$block = module_invoke('uc_cart', 'block_view', 'cart');
print render($block);
?>

```

Neither worked. How do I properly do this call?

# Answer
I was able to render the code using the following;

```
<?php
  $block = block_load('uc_cart', 'cart');
  $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
  print $output;
?>

```
> 1 votes

---
Tags: theming, blocks, ubercart
---


# Question
Title: Formatting my Link field with multiple values
I believe I have a way to do this, but as I'm learning I want to make sure I'm not doing it horribly wrong or reinventing a wheel that already exists (the module search on the Drupal site leaves a lot to be desired).

I've got a Link field with multiple values (just URLs). When this field is being rendered, I would like to sort of preprocess each of the URLs. If it's a youtube or vimeo link, I'd like to change it so that a video embed is rendered instead. If it's a link to an audio file (with certain extensions) then I want to render an html5 audio tag. Else, I just want to render the link normally.

It looks like I could override `mytheme_field__links__mycontenttype()` (although I'm not exactly sure how to implement that method just yet, any examples are welcome).

It also looks like I could create a template in my theme named `field--links--mycontenttype.tpl.php`

Is this the right way to go?

Is one better than the other?

Do you have any links to a good example of how to implement/override these?

Thanks!

# Answer
> 1 votes
The two best ways to do this are the one you suggest by creating a tpl.php like you mention and doing your work in there directly. Another (and preferred by many, but a bit more complex) is to use template\_preprocess\_field.

A very good explanation of how to go down the second route is http://www.digett.com/blog/01/18/2012/change-output-single-field-drupal-7-node

That way you don't end up with a whole bunch of field.tpls and you can isolate your changes in that function.

---
Tags: 7, entities, theming
---


# Question
Title: Deleting the files associated with my node is VERY slow
I've got a node which has around 50 files associated with it. The files are stored on Rackspace Cloud Files. Interacting with Cloud Files was very slow, but I've fixed that now and the actual delete operations are running very quickly now. However, there is sometimes a gap of 3-5 seconds between each attempt to delete a file. I added some logging to the unlink() method so I could track how fast the requests were happening.. here is an abbreviation snippet of the log:

```
[11:55:31 2012] starting to delete rcf://videos/thumbnails/1702/thumbnail-1702_0001.png
[11:55:31 2012] deletion complete

[11:55:36 2012] starting to delete rcf://videos/thumbnails/1702/thumbnail-1702_0002.png
[11:55:36 2012] deletion complete

[11:55:40 2012] starting to delete rcf://videos/thumbnails/1702/thumbnail-1702_0003.png
[11:55:40 2012] deletion complete

```

So, each delete operation is taking essentially no time, but in between each call to unlink() there is 4-5 seconds. This continues for the remaining files, so it takes SOOO long to delete a node and I'm in danger of the php process being killed for running too long.

Why would drupal be so slow in between file deletes? What might cause this? Where can I look to determine what is taking so long?

# Answer
I edited the cloudfiles.php API from Rackspace to uncomment the following line:

```
define('RACKSPACE_SERVICENET', 1);

```

That automatically causes the API to connect over the private network which is a lot faster than accessing cloudfiles via the public network.

This is only usable if you are hosting your site on a Rackspace server though.
> 0 votes

---
Tags: 7
---


title: Setting up drupal's js and css on CDN

text:
# Question
Title: Setting up drupal's js and css on CDN
I've got my drupal site set up so that all newly uploaded files are automatically stored on my CDN (Rackspace Cloud Files).

The only thing I need moved over is drupal's core css and js (along with the css and js for all of the installed modules).

I've been reading over the CDN module and the FileConveyor daemon, but it seems like a lot of overkill. I don't need a daemon that watches for new files and transports them over to CloudFiles. I really just need a one-time deal.

Is there an easier way?

# Answer
My "easier way" was simply to copy all of the core css and js as well as the all of the modules css and js up into my CloudFiles container and then configure the CDN module to automatically rewrite the URLs of any .css or .js file.
> 1 votes

---
Tags: 7, cdn
---


# Question
Title: Add #theme_wrapper after drupal_render() is called
I have a render array:

```
$element = array(
   '#theme' => 'custom_theme_func',
);

drupal_render($element);

```

I have a preprocess function in which I'd like to add theme wrappers to this render array:

```
function my_module_custom_theme_func(&$element)
{
    $element['theme_wrappers'] = array('some_theme_func');
}

```

The problem that I'm running into is that some\_theme\_func() is not being called. If I add it to the list of theme wrappers before I call drupal\_render(), however, it works.

# Answer
> 1 votes
There are two errors in your code:

* If you use `'#theme' => 'custom_theme_func'` to reference the theme function, Drupal will look for `theme_custom_theme_func()`, not `my_module_custom_theme_func()`.
* The argument a theme function gets is always `$variables`, an array that in your case probably contains `$variables['element']`.
What exactly that array contains depends from the definition given in the implementation of hook\_theme(). For example, theme\_status\_report() is defined as:

```
'status_report' => array(
  'render element' => 'requirements',
  'file' => 'system.admin.inc',
),

```

The array it gets contains `$variables['requirements']`.

theme\_image() is defined as:

```
'image' => array(
  'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
),

```

The array it gets can contain `$variables['path']`, `$variables['width']`, `$variables['height']`, `$variables['alt']`, `$variables['title']`, and `$variables['attributes']`.

As for setting `#theme_wrappers`, setting them in the theme function doesn't have any effect, as the theme function doesn't receive the `$variables` array as reference; therefore, it cannot change its content, and pass those changes back to `drupal_render()`.

As zdecibel said, you can use the preprocess function to set the theme wrappers, even if it is probably better to define them directly in the code you shown at the beginning (the first 3 lines), as you are not dynamically changing the theme wrappers. (At least, that is what you shown in your code.)

# Answer
> 0 votes
Because of function `my_module_custom_theme_func` don't pass a reference parameter. you can try

```
function template_preprocess_custom_theme_func(&vars){
  $element = $vars['element'];
  $element['theme_wrappers'] = array('some_theme_func');
}

```

---
Tags: 7, theming
---


title: Migrating CCK fields

text:
# Question
Title: Migrating CCK fields
I'm in the process of upgrading to Drupal 7.12 from Drupal 6.25. I have been upgrading all my modules as well, and now is time to figure out how to migrate the data from CCK to D7 Fields.

I found the Migrating D6 Content Construction Kit (CCK) to D7 Fields article, which explains how to do this.

Unfortunately I after I update the CCK module, and enable the Content Migrate Module, I don't see where the Content Migrate Module under Admin -\> Structure -\> Content Migrate!

I'm stuck and I don't know what to do. Any ideas/suggestions?

# Answer
> 1 votes
Before I could run the CCK migration I needed to run the `mywebsite.com/update.php` script before I could use the Migrate Fields.

That solved my issue.

# Answer
> 1 votes
I used the Drush Site Upgrade command. It automatically converted my CCK fields to D7 fields core module.

# Answer
> 1 votes
Download and enable the contributed Migrate module (eg using Drush).

For further information about how to use this module, read its Community Documentation.

---
Tags: 7, migrations, entities, upgrading
---


# Question
Title: Drupal7 template suggestions for node is not working
I created a new content type named job. Now I want to use custom node template for this content type.

I created file name `node--job.tpl.php` and cleared the cache, but it doesn't pick that file, it is picking only `node.tpl.php` file.

Anybody have any idea about this?

# Answer
Your usage is right.Check your code in detail!
> 1 votes

# Answer
The theme developer module is very handy if it comes to find the right template names. After enabling you can just point and click on whathever you want the theme to find the right name.

After changing templates you have to clear your caches. Otherwise they are not picked up. Either go to `admin/config/development/performance` or use `drush cc all`.
> 0 votes

---
Tags: theming
---


title: edit content on content's language

text:
# Question
Title: edit content on content's language
I have a couple of nodes (using node translation) shown on `/en/admin/content`. All the `edit` links point to `/en/node/*/edit` which always has the English language on the URL. This is problematic because for French items the `entityreference` fields show English nodes and not French. In order to solve this I have to manually edit the URL to `/fr/node/*/edit`.

The same applies when initially translating a node. The "add translation" link at `/en/node/*/translate` always starts with `/en/...`. If it'd start with the target language (e.g `/fr/...`) then this problem with the `entityreference` fields would not exist.

Is this a problem of `entityreference` or Drupal? Can it be fixed or configured from somewhere?

# Answer
The edit links where fixed in `i18n 7.x-1.6`. When I crated this issue I was using `7.x-1.5`.

http://drupal.org/node/1649596
> 0 votes

---
Tags: 7, i18n-l10n, entities
---


# Question
Title: Drupal 7 block api, is this custom module correct?
This is my first time attempting at writing a custom module i had a quick look over the api but forgive me if its wrong

We have been having some small issues regarding the drupal core blocks, the main page content block completely disregards the weigh assigned to it, and we are stumped for clues, no help or ideas have been found from posting on drupal or extensively searching google.

The final option we have is to manually overwrite the weight, i threw this together quickly

```
 <?php
 funtion hook_block_info_alter() {
$blocks['Main page content'] = array(
    'weight' => ('-9999'),
    );
 }
 ?>

```

Would that successfully overwrite the weight of the main page content block?

# Answer
> 1 votes
Very nearly, but not quite.

1. You're missing the function arguments in your hook implementation, so there's nothing there to actually alter.
2. The blocks array is keyed by module, then block delta, so you would need to access the block using those instead of the title as you currently are.
3. You're trying to overwrite the system main block in it's entirety rather than changing a property on it.
4. You've spelt `function` wrong ;)

Try:

```
function MYMODULE_block_info_alter(&$blocks, $theme, $code_blocks) {
  $blocks['system']['main']['weight'] = -9999;
}

```

---
Tags: 7, hooks, blocks
---


# Question
Title: Returning alternate HTTP codes for unpublished content
Sometimes when nodes are unpublished, they are not meant to be taken live again.

Under those circumstances, I would like to return a `410 Gone` status, instead of the default `403 Forbidden`.

Implementing the 410 itself is a 1 line patch to Page manager, but I soon realize that there is no easy way to get the response to the client, as the router system itself checks the node status, and denies access.

How can I force the menu router to process my request for an unpublished node as usual?

# Answer
I haven't tried this myself, but I think the main problem is that in your cases, the "unpublished status" means two things.

I think your best bet is to use something like Workbench Moderation, and defined a "retired" state. Then, in a hoot\_init(), check the status, and generate the 410.

Something like:

```
function mymodule_init ()
{
   $node = menu_get_object();
   if (isset($node->nid) && this_is_a_retired_node($node)) {
     drupal_add_http_header('Status', '410 Gone');
     drupal_exit(); // may want exit instead; not sure of other hook_inits()s should run
   }
}

```

I think you have to take the sledgehammer approach so that you don't get too far into the request where you may have a race condition with other modules.
> 3 votes

# Answer
Ultimately, the current 403 is coming from node\_access, hook\_menu\_alter'ing a wrapper around that function may be able to solve this problem.
> 2 votes

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


title: Primary & secondary links

text:
# Question
Title: Primary & secondary links
I tried really hard but couldn't figure out what are they (subj). Can anybody explain? I see mentions of them here and there but there just no definitions anywhere available.

Thank you.

# Answer
Primary & Secondary links are the definition of the hyperlinks often found in the main menu in Drupal 7

Menu System Documentation
> 0 votes

---
Tags: navigation
---


title: Issue with views and php

text:
# Question
Title: Issue with views and php
i'm using a view thats pulls data from a certain node via refference and i show non logged in users a error that they need to login, but i need to show a special node/add link with the nid in it. i'v got the code and it works without the if statement, in the if statement, my code is not working..

```
<?php global $user;if (!$user->uid){print '<div class="messages error"><h4 class="alert-heading logged_out">Oops!</h4><p>tekst hier</p></div>';}else{
 (arg(0) == 'node' && is_numeric(arg(1))) {  $nid = arg(1);print '<a class="btn" href='/node/add/album&field_band[]=$nid'>Voeg een album toe!<a/>';} ?>

<?php  if (arg(0) == 'node' && is_numeric(arg(1))) {  $nid = arg(1);print '<a class="btn"  href='/node/add/album&field_band[]=$nid'>Voeg een album toe!<a/>';} ?>

```

the code above works, but not when its in the if/else block...

Please note that i don't have great knowledge about php.

Thanks!

# Answer
You should write the if-else structure like:

````
<?php
global $user;
if (!$user->uid) {
   print '<div class="messages error"><h4 class="alert-heading logged_out">Oops!</h4><p>tekst hier</p></div>';
}
else if(arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    print '<a class="btn" href='/node/add/album&field_band[]=$nid'>Voeg een album toe!<a/>';
}

```

?>`

Note that after 'else' you want to test some conditions so you need to put an 'if' statement in front of your test.
> 1 votes

# Answer
You're missing an `if` before the beginning of your second line of code; you should be getting a fatal error for invalid syntax, unless it's being suppressed somehow.

Try changing the first two lines to:

```
<?php
global $user;
if (!$user->uid) {
  print '<div class="messages error"><h4 class="alert-heading logged_out">Oops!</h4><p>tekst hier</p></div>';
} else {
  if (arg(0) == 'node' && is_numeric(arg(1))) {
    $nid = arg(1);
    print '<a class="btn" href='/node/add/album&field_band[]=$nid'>Voeg een album toe!<a/>';
  }
}
?>

```

Or go with Gabriel's solution to use an `else if`, it's more efficient anyway.
> 0 votes

---
Tags: views
---


# Question
Title: Is it possible to create an iCal stream from Open Atrium's calendar feature? If so, how?
I'm getting mixed signals around whether or not its possible to create an iCal feed from the Open Atrium Calendar Feature.

When I try creating a new view or adding a feed to an existing view, I don't see the option for an iCal feed...just RSS :(

Can someone point me in the right direction?

Some background: http://drupal.org/node/348871

# Answer
> 2 votes
I ended up making the feed in a custom module using the iCalCreator library. I did like this approach because I was able to be very selective with the events to include in the feed which was a requirement and the iCalCreator library was VERY easy to work with :D

# Answer
> 0 votes
I think that the Calendar module provides this feature, and that it is part of Open Atrium, I think. Here is an excerpt about it from the module's project page:

> ... will display any Views date field in calendar formats, including CCK date fields, node created or updated dates, etc. Switch between year, month, and day views. Back and next navigation is provided for all views. Lots of the Calendar functionality comes from the Date module, so any time you update the Calendar module you should be sure you also update to the latest version of the Date module at the same time.
>
> See also Date iCal, a project that contains code and features needed to either import or export dates using iCal feeds. The functionality that used to be in the Calendar iCal module has been moved into that module.

---
Tags: 6, distributions
---