Snippets

Gravitywell Drush script for printing valid php field export code

Created by Lucian Buzzo last modified
#!/usr/bin/env drush

<?php

/**
 * This script will echo valid php for programatically creating a field.
 * The field must already exist for this to work, so it's value is in deploying 
 * changes from a development environment onto a live site.
 * 
 * Call the script with "drush fieldexport.drush.php" specifying a field name using
 * the --field option. 
 * e.g.
 * drush fieldexport.drush --field=field_text_field
 */

// Use the drush API to get the --field option.
$fieldName = drush_get_option('field');

// If the --field option hasn't been provided, print a helpful message and exit the script.
if (is_null($fieldName)) {
  echo "\nPlease specify a field name using the --field option\n";
  echo "e.g. drush fieldexport.drush --field=field_base_site";
  exit;
}

// Load the field definition array.
$fieldInfo = field_info_field($fieldName);
// Save the fields defined bundles to a variable.
$instances = $fieldInfo["bundles"];
// Generate a prettified array that can be used by field_create_field
$fieldInfoPretty = var_export(array(
  "field_name" => $fieldName,
  "type" => $fieldInfo["type"],
  "settings" => $fieldInfo["settings"]
  ), true);

// Remove line breaks after fat arrows, so that the output fits the Gravitywell code style
$fieldInfoPretty = preg_replace( '/=> \r\s*|=> \n\s*/', '=> ', $fieldInfoPretty );

// Output beautified code for creating a field
echo <<<EOT

// Clear the field cache so we've got a clean slate to start on
field_cache_clear();

// Check if our field is not already created.
if (!field_info_field("$fieldName")) {
  \$field = $fieldInfoPretty;

  field_create_field(\$field);

EOT;

// A field may be attached to multiple entity types and bundles, so we need to create an instance definition for each one.
$prettyInstances = [];

foreach ($instances as $entity_type => $bundles) {
  foreach ($bundles as $bundle) {
    // Load the field instance definition array and save it as a valid php string
    $prettyInstance = var_export(field_info_instance( $entity_type, $fieldName, $bundle), true);
    
    // Remove line breaks after fat arrows, so that the output fits the Gravitywell code style
    $prettyInstance = preg_replace( '/=> \r\s*|=> \n\s*/', '=> ', $prettyInstance );
    
    // Push the instance definition string into an array
    $prettyInstances[] = $prettyInstance;
  }
}

// Loop through the the generated instance definition strings and output php code 
foreach($prettyInstances as $prettyInstance) {
echo <<<EOT

  // Create the instances on the bundle.
  \$instance = {$prettyInstance};

  field_create_instance(\$instance);
EOT;
}

echo "\n}\n";


Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.