Tuesday 8 March 2011

Using Views custom text

So here's the thing: for the current project I had to produce an administrative list of node types, meetings in this case, and alongside have a bunch of links to edit, delete and one for other management stuff.

Views is your friend. Creating a table output of a list of nodes ordered by meeting date is easy-peasy but the challenge here is adding links.

It crossed my mind that I could intercept Views output in half a dozen places, programmatically or by creating replacement templates but that sounds far too much like hard work. I was sure that I'd seen an option to add custom text to a View somewhere, and I knew from a project last year sometime that Views very kindly allows you to use tokens built from fields being displayed in the row it's building.

And so it turns out ... with some caveats:

I had configured the view to output three columns - Name, Date/Time and Location - now I needed a column with the links.

So I added a field, selected "Global" and chose Custom text.

Then added the text: <a href="node/[nid]/edit">Edit</a>

I'll keep it simple and just use one link.

Now this doesn't work, why? Because the tokens can only be for fields that have been used and appear <em>before</em> the field you need them. So I had to add a "Node: Nid" field and put it at the top of the list - remembering to check the "Exclude from display" box because I don't want a column of nids in the table.

And now - I get garbage in the link. The nid numbers are going in okay, but the HTML is all screwed up.

This is the caveat: I was pretty sure, with Drupal 6, that you get the raw output of the field. So if I ask for the nid all I get is the nid (could be wrong on that, I'm not going to check). But it turns out that with Drupal 7 Views what you get in the token is the processed output of the Node: Nid field.

I recommend unchecking every option, but especially uncheck the "Link this field to its node" box, because that's what I was getting, where I have [nid] in the URL it was embedding a complete link.

Having said that, once you take out all the extra options you just get the raw nid. And the link now works.

No comments: