Friday, April 22, 2011

Drupal 7 Field API tutorial-Create a new content type

With Drupal 7, most modules will use field API for the tasks outlined above. One example of this is Organic Groups which relies on field API instead of using custom tables. Drupal 7 coding is becoming more “precision surgery” as most of the work is done by the field API, you just need a few well placed alter statements to get the customization you need.
However, field API introduces many new concepts and because it is a new API, there are a number of “gotchas”. This writeup is a quick introduction to the new concepts and points out things that may make learning the API more challenging.

Field

A field is a data structure holding some settings. Fields must have a name and a field type.
Fields can have a cardinality; that is 'how many values will this field have?' Fields can have as cardinality: one (default), a pre-specified number or any number. This is where SQL does not shine and NoSql databases like MongoDB do. As we mentioned above, you can store arrays in MongoDB and when you query them it will use indexes (if indexes are defined). You can define storage per field but there is a default, too. Core ships with an SQL storage module, but the default is just a variable, so it's easy to change.
Note that these all are configurations that are hard to upgrade because they can change database schema, semantics, and other database specifics. This is why updating the field type is explicitly forbidden.

Instance

Attaching a Field to a Bundle results in an Instance. The instance, much like the field is an array containing various settings. The most important settings are the field name and the bundle. The instance also stores widget and formatter settings. We will get back to these settings; but for now realize that these instance settings are trivial to update. When we were developing field API and we needed to decide whether something gets into fields or instances, the important question was: Can this be updated easily?

Field attach API

The field attach API lets you deal with entities containing fields. The operations are again the usual: hook_field_attach_load, hook_field_attach_validate. The entity modules call the field attach functions directly, for example field_attach_presave('node', $node); If you are writing an entity module, this is how you interact with the field API. There is no super hook-set that the field API implements, it gets explicit calls. In turn, the field attach functions call same named hooks, for example module_invoke_all('field_attach_presave', $entity_type, $entity); The arguments are the entity type and the entity. These are real hooks, so every module can implement them.

Visit this from original site: http://drupal.org/node/707832

No comments:

Post a Comment