18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Working with Content<br />

Saving your artwork<br />

What does artwork_save() look like, though? Like artwork_load() it's really just a<br />

thin wrapper:<br />

function artwork_save($artwork) {<br />

return entity_get_controller('artwork')->save($artwork);<br />

}<br />

Once again, we let the controller class do the hard work. The save() method itself is<br />

actually broken into two parts, one for normal saving and one for revisions.<br />

public function save($artwork) {<br />

$transaction = db_transaction();<br />

try {<br />

global $user;<br />

// Determine if we will be inserting a new artwork.<br />

$artwork->is_new = empty($artwork->aid);<br />

// Set the timestamp fields.<br />

if (empty($artwork->created)) {<br />

$artwork->created = REQUEST_TIME;<br />

}<br />

$artwork->changed = REQUEST_TIME;<br />

$artwork->revision_timestamp = REQUEST_TIME;<br />

$update_artwork = TRUE;<br />

// Give modules the opportunity to prepare field data for<br />

// saving.<br />

field_attach_presave('artwork', $artwork);<br />

if (!$artwork->is_new && !empty($artwork->revision) &&<br />

$artwork->vid) {<br />

$artwork->old_vid = $artwork->vid;<br />

unset($artwork->vid);<br />

}<br />

// If this is a new artwork...<br />

if ($artwork->is_new) {<br />

// Save the new artwork.<br />

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

[ 172 ]

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

Saved successfully!

Ooh no, something went wrong!