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 Content<br />

}<br />

'#submit' => array('artwork_form_delete_submit'),<br />

);<br />

$form['#validate'][] = 'artwork_form_validate';<br />

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

}<br />

return $form;<br />

Once again, a fair number of lines but all fairly simple. First we set a fake property<br />

on the form so that form_alter implementations may detect all artwork forms of<br />

any type and stick the artwork object itself into the form in case we need it later in<br />

validate or submit routines. We then add a form field for the title and a checkbox<br />

to indicate whether we should save a new revision or overwrite the existing revision.<br />

We then add not one but two buttons, one that is always available for the save<br />

operation and another for deleting an artwork if we're editing an existing artwork.<br />

More on that later.<br />

The last line is very important. The field_attach_form() call is what passes our<br />

form off to the Field system so that any fields we've added to this artwork type can<br />

be added to the form. Think of it as a Field-specific form_alter operation. The form<br />

properties that the Field system adds are quite complex, but we don't have to worry<br />

about them. They just work.<br />

Validation callback<br />

Similar to the form, the validation callback passes most of its logic off to the<br />

Field system.<br />

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

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

}<br />

// Field validation.<br />

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

If we had any validation of our own we would include it here, but in this case any<br />

validation we'd do (checking for required fields) the Form API already does for us.<br />

All we need do is tell the Field system to do its own validation.<br />

[ 170 ]

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

Saved successfully!

Ooh no, something went wrong!