Referenced node display references - drupal

I have a node "Bug/Requests" which references one "Project".
On the project "node" page, I would like to display a list of bugs/requests which link to that project. Is this possible?
here is how I ended up doing it:
Is this good or bad? Is there a better way? (in template.php)
<?php
function digital_preprocess_node(&$vars)
{
$node = $vars['node'];
if ($node->type == 'project' )
{
$bugs_requests_nids = array();
$query = 'SELECT entity_id FROM field_data_field_project WHERE field_project_nid = :project_nid';
$result = db_query($query, array(':project_nid' =>$node->nid));
foreach($result as $row)
{
$bugs_requests_nids[] = $row->entity_id;
}
$vars['tasks'] = node_load_multiple($bugs_requests_nids);
}
}

I think you want the References Module (provides node and user reference fields for Drupal 7)
Apologies I didn't read properly, you also want the Corresponding node reference module which makes the node reference bi-directional (D7 versions of the modules given in another answer).
EDIT to address your new code:
I'm guessing you're pretty new to Drupal from your recent questions but either way you've hit on (in my opinion) the best method to do this. If you're comfortable writing PHP code (which a lot of Drupal users aren't) then grabbing the data directly will always be more efficient than using a contributed module that might have a lot of overhead.
A few minor points:
I'd consider moving your code out of the template file and into a custom module, inside a hook_node_load function instead so this data is available throughout the life of the nodes (that way you can re-use it in many different contexts). However if you don't need to reuse this data anywhere except in the template file then it's fine where it is.
If you're going to go directly into the field tables you should probably use the field_revision_field_x tables instead of field_data_field_x so you can take advantage of the revision system and always grab the most recent data.
As fields can be attached to multiple entity types you should make sure you're getting the right field data for the right entity (you may not plan to attach this field to any other nodes/entities but it's good practice in case you do).
This is a slightly edited version of your code taking into account the proper field types (untested but should work):
function digital_preprocess_node(&$vars) {
$node = $vars['node'];
if ($node->type == 'project' ) {
$bugs_requests_nids = db_select('field_revision_field_project', 'p')
->fields('p', array('entity_id'))
->condition('entity_type', 'node')
->condition('bundle', 'project')
->condition('entity_id', $node->nid)
->condition('revision_id', $node->vid)
->execute()
->fetchCol();
$vars['tasks'] = node_load_multiple($bugs_requests_nids);
}
}

Related

Drupal user permissions & odd content types

I have a permissions problem in Drupal. I want users to be able to create a certain node type, but there are two different paths I need to give them permissions for to let them do this. The type is content created by a module called isbn2node, and there are two ways to make content through it, each with different paths:
?=node/add/isbn2node-book
?=node/add/isbn2node_book/isbn2node
One has an underscore and the other one has a hyphen. The first path leads to a form that lets users enter information on a book manually; the second path lets them enter an ISBN, searches for it, and populates the form for them based on the results.
I've changed permissions in the People menu so they can add isbn2node-book content manually using the first path, but there isn't an option to let them use the second method. Aliasing the url so it didn't have node/add in the path didn't work either.
Creating a duplicate content type seems like an ugly solution to this; is there a more elegant way to let users access that second path?
A little code in a custom module using hook_node_access should do it.
$node is either a node object or the machine name of the content type on which to perform the access check (if the node is being created then the $node object is not available so it will be a string instead).
So this should do it:
function MY_MODULE_node_access($node, $op, $account) {
if ($op == 'create') {
$type = $node;
if($type == 'book' && $account->uid) return NODE_ACCESS_ALLOW;
}
}
I figured this out, and the issues I was having were specific to this content type. The ISBN2Node module requires users to have the Administer Nodes permission to use its lookup and bulk import features.
There is some extra code for the module's hook_permission and hook_menu sections submitted as a fix in the module's issues thread.

Drupal Taxonomy Block, Vocabulary Listing

I looking for the best way to implement a block that lists all terms of a certain vocabulary. Each term should link to page that lists all nodes associated with that term. Any help would be greatly appreciated. Thanks!
See here for a great tutorial to achieve exactly what you want
http://chrisshattuck.com/blog/how-add-block-menu-tags-or-other-taxonomy-terms-drupal-site
The easiest way to approach this would probably be to use Views, and simply create a new view of the type "term". Here's a quick example which assumes that you have some basic familiarity with the Views UI:
Visit Views > Add (build/views/add), give your new view a name, and select Term from the "View type" radio buttons.
On the next page, start by adding a Taxonomy: Vocabulary filter and selecting your vocabulary in the filter settings.
Add a Taxonomy: Term field and enable the Link this field to its taxonomy term page option in the field settings. You might also want to remove the field's label, since this is just a simple listing.
You probably want your display to display all terms in your vocabulary, so change the "Items to display" 0 (unlimited). By default, new views only display 10 items at a time.
Check out the Live preview below to see if it's outputting what you need.
Add a new Block display using the dropdown on the left side of the Views UI.
Give your new block a name in the "Block settings" area. This is the description that will appear on Drupal's block admin page.
Save your view and visit admin/build/block to place and configure your block.
It's worth noting that Views does indeed have some overhead, but in my experience, its flexibility and ease-of-use far outweigh the relatively minor performance hit.
If you'd like to avoid using Views, you could write a pretty simple custom module using hook_block() and adapting http://drupal.org/node/247472. If you'd like, I can edit this answer with an example module based on that.
(Posting this as another answer, since this is a different approach than my first answer.)
As I mentioned above, here's another approach involving a custom module based on the code at http://drupal.org/node/247472. You could also just drop that code into a custom block with the "PHP" input format selected, but that's generally considered to be bad practice.
Add a new folder in sites/all/modules called vocabulary_block. Customize and add the following two files:
vocabulary_block.module
<?php
/**
* #file
* Exposes a block with a simple list of terms from [vocabulary].
* Each term is linked to its respective term page.
*/
/**
* Lists terms for a specific vocabulary without descriptions.
* Each term links to the corresponding /taxonomy/term/tid listing page.
*/
function vocabulary_block_get_terms($vid) {
$items = array();
$terms = taxonomy_get_tree($vid, 0, -1, 1);
foreach($terms as $term) {
$items[]= l($term->name, "taxonomy/term/$term->tid");
}
if(count($items)) {
return theme('item_list', $items);
}
}
/**
* Implementation of hook_block().
*/
function vocabulary_block_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
$blocks[0]['info'] = t('List of [vocabulary] terms');
return $blocks;
case 'view':
if ($delta == 0) {
$vid = 43;
$block['subject'] = t('[Vocabulary]');
$block['content'] = vocabulary_block_get_terms($vid);
}
return $block;
}
}
vocabulary_block.info
name = Vocabulary Block
description = Exposes a block with a simple list of terms from [vocabulary]. Each term is linked to its respective term page.
; Core version (required)
core = 6.x
; Package name (see http://drupal.org/node/101009 for a list of names)
package = Taxonomy
; Module dependencies
dependencies[] = taxonomy
Notes
Be sure to change $vid = 43; to
reflect the ID of the vocabulary that
you'd like to load. You can find the
VID by visiting
admin/content/taxonomy and looking at
the destination of the edit
vocabulary link for your
vocabulary. The VID will be the last
fragment of that URL:
admin/content/taxonomy/edit/vocabulary/[vid].
I wouldn't normally hard-code the
$vid into the module itself. However,
setting up the necessary Drupal
variable and administration form (to
allow users to select a vocabulary
from the Drupal interface) would be
overkill for this answer.
For your own documentation purposes,
don't forget to search/replace
[vocabulary] in those two files and
use your own vocabulary's name
instead.
This method may not necessarily be more performant
than the Views method I described
earlier, especially once you start considering caching,
optimization, etc.
Since performance is a priority,
I recommend thoroughly testing a
variety of different methods on this page and
choosing whichever one is fastest for you.

Drupal - Getting node id from view to customise link in block

How can I build a block in Drupal which is able to show the node ID of the view page the block is currently sitting on?
I'm using views to build a large chunk of my site, but I need to be able to make "intelligent" blocks in PHP mode which will have dynamic content depending on what the view is displaying.
How can I find the $nid which a view is currently displaying?
Here is a more-robust way of getting the node ID:
<?php
// Check that the current URL is for a specific node:
if(arg(0) == 'node' && is_numeric(arg(1))) {
return arg(1); // Return the NID
}
else { // Whatever it is we're looking at, it's not a node
return NULL; // Return an invalid NID
}
?>
This method works even if you have a custom path for your node with the path and/or pathauto modules.
Just for reference, if you don't turn on the path module, the default URLs that Drupal generates are called "system paths" in the documentation. If you do turn on the path module, you are able to set custom paths which are called "aliases" in the documentation.
Since I always have the path module turned on, one thing that confused me at first was whether it was ever possible for the arg function to return part of an alias rather than part of system path.
As it turns out, the arg function will always return a system path because the arg function is based on $_GET['q']... After a bit of research it seems that $_GET['q'] will always return a system path.
If you want to get the path from the actual page request, you need to use $_REQUEST['q']. If the path module is enabled, $_REQUEST['q'] may return either an alias or a system path.
For a solution, especially one that involves a view argument in the midst of a path like department/%/list, see the blog post Node ID as View Argument from SEO-friendly URL Path.
In the end this snippet did the job - it just stripped the clean URL and reported back the very last argument.
<?php
$refer= $_SERVER ['REQUEST_URI'];
$nid = explode("/", $refer);
$nid = $nid[3];
?>
Given the comment reply, the above was probably reduced to this, using the Drupal arg() function to get a part of the request path:
<?php
$nid = arg(3);
?>
You should considder the panels module. It is a very big module and requires some work before you really can tap into it's potential. So take that into considderation.
You can use it to setup a page containing several views/blocks that can be placed in different regions. It uses a concept called context which can be anything related to what you are viewing. You can use that context to determine which node is being viewed and not only change blocks but also layout. It is also a bit more clean since you can move the PHP code away from admin interface.
On a side note, it's also written by the views author.
There are a couple of ways to go about this:
You can make your blocks with Views and pass the nid in through an argument.
You can manually pass in the nid by accessing the $view object using the code below. It's an array at $view->result. Each row in the view is an object in that array, and the nid is in that object for each one. So you could run a foreach on that and get all of the nid of all rows in the view pretty easily.
The first option is a lot easier, so if that suits your needs I would go with that.
New about Drupal 7: The correct way to get the node id is using the function menu_get_object();
Example:
$node = menu_get_object();
$contentType = node_type_get_name($node);
Drupal 8 has another method. Check this out:
arg() is deprecated

Saving nodes with a filefield

I'm in the progress of creating a bulk upload function for a Drupal site. Using flash I'm able to upload the files to a specific url that then handles the files. What I want to do, is not just to upload the files, but create a node of a specific type with the file saved to a filefield that has been setup with CCK. Since these are audio files, it's important that filefield handles the files, so addition meta data can be provided with the getid3 module.
Now I've looked through some of the code as I wasn't able to find an API documentation, but it's not clear at all how I should handle this. Ideally I could just pass the file to a function and just use the data returned when saving the node, but I haven't been able to find that function.
If any one has experience with this I would apreciate some pointers on how to approach this matter.
I had to do something similar some weeks ago and ended up adapting some functionality from the Remote File module, especially the remote_file_cck_attach_file() function. It uses the field_file_save_file() function from the filefield module, which might be the function you're looking for.
In my case, the files are fetched from several remote locations and stored temporarily using file_save_data(). Attaching them to a CCK filefield happens on hook_nodeapi() presave, using the following:
public static function attachAsCCKField(&$node, $filepath, $fieldname, $index=0) {
// Grab the filefield definition
$field = content_fields($fieldname, $node->type);
$validators = array_merge(filefield_widget_upload_validators($field), imagefield_widget_upload_validators($field));
$fieldFileDirectory = filefield_widget_file_path($field);
// This path does not necessarily exist already, so make sure it is available
self::verifyPath($fieldFileDirectory);
$file = field_file_save_file($filepath, $validators, $fieldFileDirectory);
// Is the CCK field array already available in the node object?
if (!is_array($node->$fieldname)) {
// No, add a stub
$node->$fieldname=array();
}
$node->{$fieldname}[$index] = $file;
}
$filepath is the path to the file that should be attached, $fieldname is the internal name of the filefield instance to use within the node and $index would be the 0 based index of the attached file in case of multiple field entries.
The function ended up within a utility class, hence the class syntax for the verifyPath() call. The call just ensures that the target directory is available:
public static function verifyPath($path) {
if (!file_check_directory($path, FILE_CREATE_DIRECTORY)) {
throw new RuntimeException('The path "' . $path . '" is not valid (not creatable, not writeable?).');
}
}
That did it for me - everything else happens on node saving automatically.
I have not used the getid3 module yet, so I have no idea if it would play along with this way of doing it. Also, I had no need to add additional information/attributes to the filefield, so maybe you'd have to put some more information into the field array than just the file returned by field_file_save_file(). Anyways, hope this helps and good luck.
I have done something whith imagefield which worked, I think the structure has to be right otherwise it won't work. It took a lot of trial and error. This is is what I populated the imagefield with.
$image['data'] =array(
'title' => $media_reference_attributes->getNamedItem("source")->value,
'description' => $description,
'alt' => "",);
$image['width'] = $width;
$image['height'] = $height;
$image['mimetype'] = $mime_type
$image['uid'] = 1;
$image['status'] = 1;
$image['fid'] = $fid;
$image['filesize'] = $file->filesize;
$image['nid'] = $id;
$image['filename'] = $url;
$image['timestamp'] = $file->timestamp;
$image['filepath'] = $file_path;
Hope this is of some help.
You might want to look at Image FUpload if you need a look at integrating the flash upload.
To push the files on to another server while still handling them through Drupal sounds a little like the CDN space, maybe look at the behavior in the CDN or CDN2 projects?
If you find a clear solution please come back and post it!

Drupal: retrieve data from multiple node types in views 2?

...or, in other words, how to create a simple join as I would do in SQL?
Suppose I want the following information:
Just as an example:
a person's full name
a person's hobbies.
His full name is in a (content profile) node type 'name_and_address' and his hobbies are in 'hobbies'.
In SQL, I would link them together by node.uid.
I've seen a bit about using relationships, but that goes with user-node-refs.
I just want the same user from one content-type and the other.
Now how could I get his name and his hobbies in 1 view?
There is a how to here does this do the job?
If not...
Views can be extended with custom joins, filters etc. If you are lucky there will be a module for this already. Some modules even provide their own views plugins.
You can write your own views plugins, although the documentation is a little fragmented.
The other thing that should be noted is that views isn't always the answer. Sometimes writing a custom query and display handler will do what you want with much less hassle.
Look at the relationships section of the view. This allows you to relate (ie join) different types of content (ie tables). It's not especially intuitive to someone used to SQL, but this video explains much of it. http://www.drupalove.com/drupal-video/demonstration-how-use-views-2s-relationships
You could use views_embed_view() in your template files to manually specify where they appear (and by extension render one view right below another).
You could override this function in a custom module (modulename_embed_view($name, $display_id)) in order to selectively edit what data is allowed out to the page.
Ex):
function modulename_embed_view($name, $display_id) {
if (strcmp($_GET['q'], 'node/123') === 0) {
$view = views_get_view($name);
$view2 = views_get_view('second view');
$output = $view['some element'] . $view2['element'];
}
return $output;
}
I know that this is very much a hack - I just wanted to show how one might use php to manually render and modify views in your template files.

Resources