Monday 11 July 2016

Drupal 7 : How to Create and Save data to Entities ( in a formAPI )

Here’s a code sample of how I’ve saved to an Entity using EntityMetaDataWrapper . I’ve included on how you’d save a Taxonomy as well as a text field.
All of this code I’ve put in the ‘_submit’ function of the Form . You could create the entity in the hook_form and then pass this through the $form_state although I’ve decided not to here.

Let's create the Entity . Where you see 'marquee' this is the Entity name and the 'type' is the bundle.

 
$pricing = entity_create('marquee', array('type' =>'pricing'));

We then use this entity to create our MetaDataWrapper - The documentation for entity_metadata_wrapper gives the first argument to be passed in as $type. Which is slightly confusing as above 'type' is the bundle, here its the Entity type for example 'node', 'user', 'file' or a custom type .

$wrapper = entity_metadata_wrapper('marquee', $pricing);

You can then prepare the Entity's data like this
$wrapper->title->set('My title);

To get a list of all the fields that you have in the entity to set you can use the Field Map function .

$a_look_at_the_field_map = field_info_field_map();

No need to leave this line in though as it's just so you can add a breakpoint and check other all your entity maps.

From here you'll be able to check what you can set in your entity. To set a field with a taxonomy it's a easy as
$wrapper->field_type_size->set($sizes_tid);

With text fields that hold more than one piece of data then you'll need to fill each cell . For example we have a carpet price that also needs a currency code set with it. So here I needed to add both bits of data .

$wrapper->field_base_price->amount->set($base_price);
$wrapper->field_base_price->currency_code->set('USD');
If you're wondering how I worked out that I needed to user 'field_base_price->amount->set' and 'field_base_price->currency_code→set' . Well I got those from the database . I checked the database table 'field_data_field_base_price' and in here we have the columns 'field_base_price_amount' and 'field_base_price_currency_code' - if you ignore the 'field_base_price_' part of the name that will give you the directions for where to make these value changes.

All that's left is to Save and leave a success message .

$wrapper->save();
 
drupal_set_message(t('Success'));

No comments: