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.

Chapter 6<br />

Master/slave database configurations are an advanced topic that we<br />

won't cover in detail. However, <strong>Drupal</strong> transparently falls back to<br />

single-database behavior if no slave is defined so it's always good to<br />

plan ahead for supporting a master/slave configuration.<br />

Once again there are multiple points where we call the Fields system to let it<br />

do its part with our entity, which again should be self-explanatory. We also call<br />

module_invoke_all() in order to allow other modules to interact with any entity<br />

when they are created or updated.<br />

Handling revisions<br />

The only other complex part of the process involves revision handling, which can be a<br />

bit hard to wrap our head around. Looking at the saveRevision() method may help:<br />

function saveRevision($artwork, $uid, $update = FALSE) {<br />

// Hold on to the artwork's original creator_uid but swap<br />

// in the revision's creator_uid for the momentary write.<br />

$temp_uid = $artwork->uid;<br />

$artwork->uid = $uid;<br />

}<br />

if ($update) {<br />

drupal_write_record('artwork_revision', $artwork, 'vid');<br />

}<br />

else {<br />

drupal_write_record('artwork_revision', $artwork);<br />

}<br />

// Reset the order's creator_uid to the original value.<br />

$artwork->uid = $temp_uid;<br />

After we've saved the artwork to the artwork table, we also save it to the<br />

artwork_revision table. If we're creating a new revision, we'll save a new record to<br />

the table and drupal_write_record() will populate the vid property for us with<br />

the new version ID. Then, back in save(), we update the record in the artwork table<br />

to point to the new revision record. If we just overwrote the old revision record then<br />

that step is not necessary.<br />

That's it! We can now create new artwork objects straight from the UI with a simple<br />

form, including whatever Fields we've decided to attach to our artworks. Not only<br />

that, but since we put the saving logic in the controller rather than in the form submit<br />

callback we can easily create new artworks programmatically; we need only create a<br />

new artwork object with the properties we want and call artwork_save().<br />

[ 175 ]

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

Saved successfully!

Ooh no, something went wrong!