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.

Submit callback<br />

The submit callback is a little more interesting but not by much:<br />

Chapter 6<br />

function artwork_form_submit($form, &$form_state) {<br />

global $user;<br />

$artwork = &$form_state['artwork'];<br />

// Set the artwork's uid if it's being created at this time.<br />

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

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

}<br />

$artwork->title = $form_state['values']['title'];<br />

$artwork->revision = $form_state['values']['revision'];<br />

// Notify field widgets.<br />

field_attach_submit('artwork', $artwork, $form, $form_state);<br />

// Save the artwork.<br />

artwork_save($artwork);<br />

// Notify the user.<br />

drupal_set_message(t('Artwork saved.'));<br />

}<br />

$form_state['redirect'] = 'artwork/' . $artwork->aid;<br />

First we pull the old artwork object out of the $form_state variable. Next we set<br />

its user, if it's a new artwork, and populate it with the few values we have from the<br />

form. We've already confirmed that those values are valid in the validation hook.<br />

field_attach_submit(), much like its sibling functions, lets the Field system<br />

respond to the fact that a form was just submitted and do whatever it wants to<br />

do. Then we simply save the artwork.<br />

It is important to note here that the submit callback is doing extremely little. It's just<br />

glue code between the form and the artwork_save() function, really. That's a good<br />

thing. It means that artwork operations, such as saving, are not dependent on the<br />

form system.<br />

Never do serious processing in a form submit callback. The<br />

actual work of saving an entity and its data should happen in the<br />

entity's save routines. The form submit callback is just glue code.<br />

[ 171 ]

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

Saved successfully!

Ooh no, something went wrong!