18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Working with Files and Images<br />

$node->title = 'The World of Crell';<br />

$node->language = LANGUAGE_NONE;<br />

$node->body[LANGUAGE_NONE]['0']['value'] = 'GAHHHH!';<br />

$node->field_image[LANGUAGE_NONE]['0']['fid'] = $file->fid;<br />

node_save($node);<br />

As discussed in Chapter 6, Working with Content, a node is an object and fields<br />

are properties of the object, indexed by language. In terms of this example, the<br />

highlighted line is the most important one. All we need to do, is to associate our file<br />

with the image field, is add the fid of our returned file object to a fid property of<br />

the field's instance. When the node is saved, <strong>Drupal</strong> will extract all the appropriate<br />

information from the files table and add it to the image field.<br />

That's it! After running this code, you can visit your site's front page and you should<br />

see something like the following:<br />

This simple example shows how easy it is to manage files in <strong>Drupal</strong>, and should<br />

provide a good jumping off point for further exploration.<br />

As mentioned earlier in the chapter, <strong>Drupal</strong> 7's File API uses PHP stream wrappers.<br />

It also introduces the ability for developers to create their own PHP stream wrappers<br />

and integrate them with <strong>Drupal</strong> file handling. Let's take a look at what stream<br />

wrappers are and how developers can use them.<br />

[ 318 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!