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.

Creating New Fields<br />

}<br />

}<br />

}<br />

}<br />

}<br />

);<br />

),<br />

'%max' => $instance['settings'][$max_key],<br />

''x)<br />

Just as all fields can be validated individually, so can all form elements. However,<br />

recall that fields can be saved from anywhere in code. We may not be using a<br />

form at all. We therefore must validate the field data itself, before we save it to the<br />

database. In this case, we're checking to make sure that if the dimension has a value,<br />

and if a maximum was set for it, it is within that maximum limit. If it's not, then<br />

we set an error in the $errors array, which is passed in by reference. That error<br />

consists of, naturally, an array of possible errors. It is up to the calling code to decide<br />

how to handle that error condition. It could show a message on screen if the error<br />

happens from a user form, or could send an invalid message object back over an<br />

SOAP connection if the field (and the entity it's attached to) is being saved by code<br />

triggered by a remote server.<br />

For more extensive information on each of the parameters to the<br />

Field API callback functions, see the examples in the field.api.<br />

php file in the field module.<br />

Another important point to note here is that field is passed an array of items, not an<br />

individual item. From a code perspective, fields in <strong>Drupal</strong> are always multi-value.<br />

Even if there is only one value, even if the field is configured to only allow one value,<br />

it is still multi-value as far as our code is concerned. "One" is simply a special case of<br />

"many". That actually greatly simplifies most of our logic, as we don't need to handle<br />

two different possible cases. We can simply iterate with a foreach() loop over our<br />

data, and we will handle one or a hundred values equally well.<br />

Remember that fields in <strong>Drupal</strong> are always a multi-value array<br />

in code. That array may have only one entry, but it can still be<br />

treated as an arbitrarily large number of values.<br />

Again, notice that nowhere in the field type definition or supporting code do we<br />

actually save data. In fact, there's not a single SQL query. We are simply describing<br />

the data. Saving the data itself, and deciding where to save it, is the responsibility<br />

of the core system. That allows a great deal of flexibility, as our dimension field can<br />

now be used to store data in a local SQL database or a remote SOAP server without<br />

any code changes on our part.<br />

[ 190 ]

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

Saved successfully!

Ooh no, something went wrong!