Skip to content

Instantly share code, notes, and snippets.

@petebarnett
Created September 27, 2016 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petebarnett/723890ed7d7754eca9ad5f89943d4e4c to your computer and use it in GitHub Desktop.
Save petebarnett/723890ed7d7754eca9ad5f89943d4e4c to your computer and use it in GitHub Desktop.
DrupalCon Dumb Storage of Typed Data
<?php
namespace Drupal\yourmodule\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\zuora\Plugin\DataType\Account;
use Drupal\zuora\TypedData\Definition\AccountDefinition;
/**
* Defines the 'zuora_account' entity field type.
*
* @FieldType(
* id = "zuora_account",
* label = @Translation("Zuora Account"),
* description = @Translation("A field for storing zuora account data."),
* no_ui = TRUE
* )
*/
class ZuoraAccountItem extends FieldItemBase {
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties = array();
// Funnily, FieldItemBase class actually extends Map - and so is itself typed data!
// We have the method "propertyDefinitions". Here we say that the 'value' property
// is a 'zuora_account', which is the data type I defined elsewhere.
$properties['value'] = AccountDefinition::create('zuora_account')
->setLabel(t('Zuora Account'));
return $properties;
}
public function setValue($values, $notify = TRUE) {
// Here we check if the value being passed in is Typed Data,
// and if so, call the "toArray" method to get raw data out.
// It'll be serialized, based on the schema settings (@see schema())
if (isset($values) && $values instanceof Account) {
$this->set('value', $values->toArray(), $notify);
}
else {
parent::setValue($values, $notify);
}
}
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
'columns' => array(
'value' => array(
// The schema here is actually different to my description
// during the DrupalCon session... whoops.
// The key is the 'serialize'.
'type' => 'blob',
'size' => 'big',
'serialize' => TRUE,
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment