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

There are a couple of moving parts here. First is the create method of the controller.<br />

The entity_get_controller() function creates a new instance of the controller<br />

class for artwork entities, which is the ArtworkController class we defined earlier.<br />

The create method is not part of the normal controller interface but is a really nice<br />

addition. It's quite simple:<br />

public function create($type = '') {<br />

return (object) array(<br />

'aid' => '',<br />

'type' => $type,<br />

'title' => '',<br />

);<br />

}<br />

It's easier to define large data structures in PHP as arrays, so we'll do that and<br />

cast it back to an object to return it. We can now create a new artwork object<br />

from anywhere.<br />

Next is the PASS_THROUGH constant we're passing as the second parameter to<br />

drupal_set_title(). Normally drupal_set_title will strip out HTML from the<br />

title to avoid security issues. Passing PASS_THROUGH as the second parameter tells the<br />

function to allow HTML in the string we're giving it because we've already checked<br />

to make sure it's safe.<br />

Use the PASS_THROUGH flag with drupal_set_title() to allow<br />

HTML in the page title. Remember that means it's up to us to sanity<br />

check and filter the title to avoid cross-site-scripting attacks.<br />

Finally there's the form. We're giving the form a dynamic name so that form_alter<br />

implementations may uniquely target a specific artwork type. How then do we<br />

match that form name with the form builder function that defines it? <strong>Drupal</strong><br />

provides another optional hook for us called hook_forms() that lets us<br />

dynamically define forms and how they should behave.<br />

function artwork_forms() {<br />

$forms = array();<br />

if ($types = artwork_types()) {<br />

foreach (array_keys($types) as $type) {<br />

$forms[$type . '_artwork_form']['callback'] = 'artwork_form';<br />

}<br />

}<br />

return $forms;<br />

}<br />

[ 168 ]

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

Saved successfully!

Ooh no, something went wrong!