/**
  * {@inheritdoc}
  */
 public function preprocess($value)
 {
     // Text field. Check if field has an input format.
     $field_info = field_info_field($this->getProperty());
     // If there was no bundle that had the field instance, then return NULL.
     if (!($instance = field_info_instance($this->getEntityType(), $this->getProperty(), $this->getBundle()))) {
         return NULL;
     }
     $return = NULL;
     if ($field_info['cardinality'] == 1) {
         // Single value.
         if (!$instance['settings']['text_processing']) {
             return $value;
         }
         return array('value' => $value, 'format' => 'filtered_html');
     }
     // Multiple values.
     foreach ($value as $delta => $single_value) {
         if (!$instance['settings']['text_processing']) {
             $return[$delta] = $single_value;
         } else {
             $return[$delta] = array('value' => $single_value, 'format' => 'filtered_html');
         }
     }
     return $return;
 }
Esempio n. 2
0
/**
 * Provides a method to update date fields that use a time increment value.
 *
 * @param int $time_increment
 *   The new time increment value.
 */
function hook_studyroom_time_increment_update($time_increment)
{
    foreach (studyroom_reservation_types() as $bundle) {
        $instance = field_info_instance('studyroom_reservation', 'field_reservation_datetime', $bundle->type);
        $instance['widget']['settings']['increment'] = $time_increment;
        field_update_instance($instance);
    }
}
function bunsen_form_alter(&$form, &$form_state, $form_id)
{
    $form_type = !empty($form['type']['#value']) ? $form['type']['#value'] : '';
    $form['#attributes']['class'][] = 'form-horizontal';
    // Add icons to action buttons
    $form['actions']['submit']['#value'] .= '&nbsp;&nbsp;<i class="fa fa-save"></i>';
    if (!empty($form['actions']['delete'])) {
        $form['actions']['delete']['#value'] .= '&nbsp;&nbsp;<i class="fa fa-ban"></i>';
    }
    // Remove node settings at the bottom of form
    unset($form['additional_settings']);
    foreach ($form as $key => $element) {
        if (is_array($form[$key]) && isset($form[$key]['#group'])) {
            unset($form[$key]);
        }
        // Wrap certain form element types with Bootstrap column classes
        if (strrpos($key, 'field_', -strlen($key)) !== FALSE || $key == 'title') {
            $field_info = field_info_instance('node', $key, $form_type);
            $field_type = !empty($field_info['widget']['type']) ? $field_info['widget']['type'] : '';
            $column_prefix = '<span class="col-md-8">';
            $column_suffix = '</span>';
            $adjust_col = FALSE;
            if ($key == 'title') {
                $form_elem =& $form[$key];
                $adjust_col = TRUE;
            } else {
                switch ($field_type) {
                    case "text_textarea":
                        break;
                    case "file_generic":
                        $form_elem =& $form[$key][LANGUAGE_NONE][0];
                        $adjust_col = TRUE;
                        break;
                    case "number":
                        $form_elem =& $form[$key][LANGUAGE_NONE][0]['value'];
                        $column_prefix = '<span class="col-md-2 input-type-number">';
                        $adjust_col = TRUE;
                        break;
                    case "text_textfield":
                        $form_elem =& $form[$key][LANGUAGE_NONE][0]['value'];
                        $adjust_col = TRUE;
                        break;
                    default:
                        $form_elem =& $form[$key][LANGUAGE_NONE];
                        $adjust_col = TRUE;
                        break;
                }
            }
            if ($adjust_col) {
                $prefix = !empty($form_elem['#field_prefix']) ? $form_elem['#field_prefix'] : '';
                $suffix = !empty($form_elem['#field_suffix']) ? $form_elem['#field_suffix'] : '';
                $form_elem['#field_prefix'] = $column_prefix . $prefix;
                $form_elem['#field_suffix'] = $suffix . $column_suffix;
            }
        }
    }
}
 /**
  * Overrides \RestfulEntityBaseNode::publicFieldsInfo().
  */
 public function publicFieldsInfo()
 {
     $public_fields = parent::publicFieldsInfo();
     unset($public_fields['self']);
     $public_fields['created'] = array('property' => 'created');
     $public_fields['updated'] = array('property' => 'changed');
     if (field_info_instance($this->getEntityType(), OG_AUDIENCE_FIELD, $this->getBundle())) {
         $public_fields['company'] = array('property' => OG_AUDIENCE_FIELD, 'resource' => array('company' => array('name' => 'companies', 'full_view' => FALSE)));
     }
     return $public_fields;
 }
Esempio n. 5
0
 public function publicFieldsInfo()
 {
     $public_fields = parent::publicFieldsInfo();
     if ($this->getBundle()) {
         $public_fields['vsite'] = array('property' => OG_AUDIENCE_FIELD, 'process_callbacks' => array(array($this, 'vsiteFieldDisplay')));
     }
     $public_fields['body'] = array('property' => 'body', 'sub_property' => 'value');
     if (field_info_instance($this->getEntityType(), 'field_upload', $this->getBundle())) {
         $public_fields['files'] = array('property' => 'field_upload', 'process_callbacks' => array(array($this, 'fileFieldDisplay')));
     }
     return $public_fields;
 }
Esempio n. 6
0
 /**
  * @todo.
  */
 public function dateForm($field_name, $field_type, $widget_type, $todate = TRUE)
 {
     // Tests that date field functions properly.
     $edit = array();
     $edit['title'] = $this->randomName(8);
     if ($widget_type == 'date_select') {
         $edit[$field_name . '[und][0][value][year]'] = '2010';
         $edit[$field_name . '[und][0][value][month]'] = '10';
         $edit[$field_name . '[und][0][value][day]'] = '7';
         $edit[$field_name . '[und][0][value][hour]'] = '10';
         $edit[$field_name . '[und][0][value][minute]'] = '30';
         if ($todate) {
             $edit[$field_name . '[und][0][show_todate]'] = '1';
             $edit[$field_name . '[und][0][value2][year]'] = '2010';
             $edit[$field_name . '[und][0][value2][month]'] = '10';
             $edit[$field_name . '[und][0][value2][day]'] = '7';
             $edit[$field_name . '[und][0][value2][hour]'] = '11';
             $edit[$field_name . '[und][0][value2][minute]'] = '30';
         }
     } elseif ($widget_type == 'date_popup') {
         $edit[$field_name . '[und][0][value][date]'] = '10/07/2010';
         $edit[$field_name . '[und][0][value][time]'] = '10:30';
         if ($todate) {
             $edit[$field_name . '[und][0][show_todate]'] = '1';
             $edit[$field_name . '[und][0][value2][date]'] = '10/07/2010';
             $edit[$field_name . '[und][0][value2][time]'] = '11:30';
         }
     }
     // Test that the date is displayed correctly using both the 'short' and
     // 'long' date types.
     //
     // For the short type, save an explicit format and assert that is the one
     // which is displayed.
     variable_set('date_format_short', 'l, m/d/Y - H:i:s');
     $instance = field_info_instance('node', $field_name, 'story');
     $instance['display']['default']['settings']['format_type'] = 'short';
     field_update_instance($instance);
     $this->drupalPost('node/add/story', $edit, t('Save'));
     $this->assertText($edit['title'], "Node has been created");
     $should_be = $todate ? 'Thursday, 10/07/2010 - 10:30 to 11:30' : 'Thursday, 10/07/2010 - 10:30';
     $this->assertText($should_be, "Found the correct date for a {$field_type} field using the {$widget_type} widget displayed using the short date format.");
     // For the long format, do not save anything, and assert that the displayed
     // date uses the expected default value of this format provided by Drupal
     // core ('l, F j, Y - H:i').
     $instance = field_info_instance('node', $field_name, 'story');
     $instance['display']['default']['settings']['format_type'] = 'long';
     field_update_instance($instance);
     $this->drupalPost('node/add/story', $edit, t('Save'));
     $this->assertText($edit['title'], "Node has been created");
     $should_be = $todate ? 'Thursday, October 7, 2010 - 10:30 to 11:30' : 'Thursday, October 7, 2010 - 10:30';
     $this->assertText($should_be, "Found the correct date for a {$field_type} field using the {$widget_type} widget displayed using the long date format.");
 }
/**
 * Notification to modules that a goal is completed.
 *
 * @param int $goal_id
 *   Goal being completed.
 * @param int $uid
 *   UserID of user completing the goal.
 */
function hook_goals_completed_goal($goal_id, $uid)
{
    if (field_info_instance('goal', 'goal_userpoints', 'goal_bundle') && function_exists('userpoints_userpointsapi')) {
        $goals = entity_load('goal', array($goal_id));
        $goal = $goals[$goal_id];
        $point_array = field_get_items('goal', $goal, 'goal_userpoints');
        $points = $point_array[0]['value'];
        if ($points) {
            $params = array('uid' => $uid, 'points' => $points, 'description' => t('Goal @goal completed.', array('@goal' => $goal->title)));
            userpoints_userpointsapi($params);
        }
    }
}
Esempio n. 8
0
/**
 * Implements template_preprocess_node, replacing selected static 
 * field values with form elements that allow them to be edited.
 */
function sand_theme_preprocess_node(&$variables)
{
    // Only applies to specific node type 'request'
    if ($variables['type'] == 'request') {
        //We don't need to show comments or links with this form
        if (isset($variables['content']['comments'])) {
            unset($variables['content']['comments']);
        }
        if (isset($variables['content']['links'])) {
            unset($variables['content']['links']);
        }
        // Call the form builder function for 'request_updater'
        // with current node->nid as an extra parameter
        $status_form = drupal_get_form('request_updater', $variables['nid']);
        $weight_max = -999;
        // Check whether there is a returned form that can be displayed
        if ($status_form['#access']) {
            foreach ($status_form['fields_replaced']['#value'] as $field) {
                // For each field in the form with a corresponding static field that has
                // been populated, copy the weight of the static field to the form
                // element and delete the static element.
                if (isset($variables['content'][$field])) {
                    $status_form[$field]['#weight'] = $variables['content'][$field]['#weight'];
                    $weight_max = max($weight_max, $status_form[$field]['#weight']);
                    unset($variables['content'][$field]);
                } else {
                    $inst = field_info_instance('node', $field, 'request');
                    $status_form[$field]['#weight'] = $inst['display']['default']['weight'];
                    $weight_max = max($weight_max, $status_form[$field]['#weight']);
                }
            }
            // Node fields that have been populated and not matched to a form element just stay
            // as they are
            foreach ($variables['content'] as $field => $status) {
                if (isset($variables['content'][$field]['#weight'])) {
                    $weight_max = max($weight_max, $variables['content'][$field]['#weight']);
                }
            }
            // Merge the elements of the form with the remaining content elements into
            // the content array.
            $variables['content'] = array_merge($status_form, $variables['content']);
            // $weight_max should now equal to the largest weight of any content element
            // so add 1 to make sure that the 'Save' button appears at the bottom
            $variables['content']['submit_button']['#weight'] = $weight_max + 1;
        } else {
            // If there's no form to be displayed, no change is made to the content array
            // and we still have the regular static display for the node
        }
    }
}
Esempio n. 9
0
 /**
  * Load a field's configuration and instance configuration by an
  * entity_type.bundle.field_name identifier.
  */
 protected function field_load($identifier)
 {
     list($entity_type, $field_name, $bundle) = explode('.', $identifier);
     $field_info = field_info_field($field_name);
     $instance_info = field_info_instance($entity_type, $field_name, $bundle);
     if ($field_info && $instance_info) {
         unset($field_info['id']);
         unset($field_info['bundles']);
         unset($instance_info['id']);
         unset($instance_info['field_id']);
         return array('field_config' => $field_info, 'field_instance' => $instance_info);
     }
     return FALSE;
 }
 /**
  * Test instance field creation.
  *
  * @dataProvider fieldDataProvider
  */
 public function testFieldInstanceCreation($field_name, $type, $label, $widget, $default_formatter, $teaser_formatter)
 {
     $base_handler = new DefaultBaseFieldHandler($field_name, $type);
     $base_handler->save();
     $handler = new DefaultInstanceFieldHandler($field_name, 'node', self::CONTENT_TYPE_WITHOUT_FIELDS);
     $handler->label($label)->widget($widget)->display('default', $default_formatter, 'inline')->display('teaser', $teaser_formatter);
     $instance = $handler->getField();
     $handler->save();
     $saved_instance = field_info_instance('node', $field_name, self::CONTENT_TYPE_WITHOUT_FIELDS);
     $this->assertEquals($label, $saved_instance['label']);
     $this->assertEquals($widget, $saved_instance['widget']['type']);
     $this->assertEquals($default_formatter, $saved_instance['display']['default']['type']);
     $this->assertEquals($teaser_formatter, $saved_instance['display']['teaser']['type']);
     field_delete_field($field_name);
 }
 /**
  * Constructor for the Add to cart form. Provide $nid as the id of the
  * product display node. Other optional arguments are product reference field
  * name, view mode of the product display node and language of the product
  * display node. If optional arguments are not provided, their default values
  * are assumed, which are "field_product", "default" and "en" respectively.
  *
  * @param int $nid
  *   Product display node id.
  */
 public function __construct($nid)
 {
     $args = func_get_args();
     array_shift($args);
     $field_name = array_shift($args);
     $view_mode = array_shift($args);
     $language = array_shift($args);
     if (is_null($field_name)) {
         $field_name = 'field_product';
     }
     if (is_null($view_mode)) {
         $view_mode = 'default';
     }
     if (is_null($language)) {
         $language = 'en';
     }
     $node = node_load($nid);
     $instance = field_info_instance('node', $field_name, $node->type);
     $display = field_get_display($instance, $view_mode, $node);
     $settings = array_merge(field_info_formatter_settings($display['type']), $display['settings']);
     $field_product = field_get_items('node', $node, $field_name);
     $product_id = $field_product[0]['product_id'];
     $products = commerce_product_load_multiple(array($product_id));
     $type = !empty($settings['line_item_type']) ? $settings['line_item_type'] : 'product';
     $line_item = commerce_product_line_item_new(commerce_product_reference_default_product($products), $settings['default_quantity'], 0, array(), $type);
     $line_item->data['context']['product_ids'] = array_keys($products);
     $line_item->data['context']['add_to_cart_combine'] = !empty($settings['combine']);
     $line_item->data['context']['show_single_product_attributes'] = !empty($settings['show_single_product_attributes']);
     $cart_context = array('entity_type' => 'node', 'entity_id' => $nid, 'display' => 'default', 'language' => $language);
     $cart_context['class_prefix'] = $cart_context['entity_type'] . '-' . $nid;
     $cart_context['view_mode'] = $cart_context['entity_type'] . '_' . $view_mode;
     $entity_uri = entity_uri($cart_context['entity_type'], $node);
     $arguments = array('form_id' => commerce_cart_add_to_cart_form_id(array($product_id)), 'line_item' => $line_item, 'show_quantity' => $settings['show_quantity']);
     // Add the display path and referencing entity data to the line item.
     if (!empty($entity_uri['path'])) {
         $arguments['line_item']->data['context']['display_path'] = $entity_uri['path'];
     }
     $arguments['line_item']->data['context']['entity'] = array('entity_type' => $cart_context['entity_type'], 'entity_id' => $cart_context['entity_id'], 'product_reference_field_name' => $field_name);
     // Update the product_ids variable to point to the entity data if we're
     // referencing multiple products.
     if (count($arguments['line_item']->data['context']['product_ids']) > 1) {
         $arguments['line_item']->data['context']['product_ids'] = 'entity';
     }
     parent::__construct($arguments['form_id'], $arguments['line_item'], $arguments['show_quantity'], $cart_context);
     $this->cart_context = $cart_context;
     $this->arguments = $arguments;
 }
Esempio n. 12
0
 /**
  * {@inheritdoc}
  */
 function describe($api, $entity_type, $keys)
 {
     if (!empty($this->bundlesByType[$entity_type])) {
         if ('user' === $entity_type) {
             $instance = field_info_instance('user', $this->fieldKey, 'user');
             foreach ($keys as $key => $title) {
                 $api->addRule($key, $title);
             }
             $api->descWithLabel($instance['label'], t('Field'));
         }
         foreach ($this->bundlesByType[$entity_type] as $bundle_name) {
             if (isset($keys[$bundle_name])) {
                 $instance = field_info_instance($entity_type, $this->fieldKey, $bundle_name);
                 $api->addRule($bundle_name, $keys[$bundle_name]);
                 $api->descWithLabel($instance['label'], t('Field'), $bundle_name);
             }
         }
         // $api->addDescription('(' . $this->fieldKey . ')');
     }
 }
Esempio n. 13
0
 /**
  * Given a relationship, gets the stub entity for the source.
  *
  * @param array $relationship The relationship array.
  *
  * @return bool|mixed Either the stub entity or false on error.
  */
 protected function getSourceStubEntity(array $relationship)
 {
     $field_name = $relationship['field_name'];
     $source_entity_ids = entity_get_id_by_uuid($relationship['source_type'], array($relationship['source_uuid']));
     $source_entity_id = count($source_entity_ids) > 0 ? reset($source_entity_ids) : null;
     $source_entity_vids = entity_get_id_by_uuid($relationship['source_type'], array($relationship['source_vuuid']), true);
     $source_entity_vid = count($source_entity_vids) > 0 ? reset($source_entity_vids) : false;
     if (!$source_entity_id) {
         return false;
     }
     // Get the bundle for the source entity.
     $source_entity_bundle = Entity::getBundleFromID($relationship['source_type'], $source_entity_id);
     if (!$source_entity_bundle) {
         return false;
     }
     // Get the stub entity for the source.
     $source_stub = Entity::getStub($relationship['source_type'], $source_entity_id, $source_entity_bundle, $source_entity_vid);
     // Load the existing field onto the entity.
     $field_instance_info = field_info_instance($relationship['source_type'], $field_name, $source_entity_bundle);
     if ($field_instance_info === false) {
         return false;
     }
     try {
         // First, load the revisions.
         field_attach_load_revision($relationship['source_type'], array($source_entity_id => $source_stub), array('field_id' => $field_instance_info['field_id']));
         // Second, get the original deltas for the revision.
         $deltas = db_select('field_revision_' . $field_name, 'fr')->fields('fr', array('language', 'delta'))->condition($source_entity_vid ? 'revision_id' : 'entity_id', $source_entity_vid ? $source_entity_vid : $source_entity_id)->condition('language', field_available_languages($relationship['source_type'], $field_instance_info), 'IN')->orderBy('delta')->execute();
         // Assign the deltas to their languages.
         $deltas_languages = array();
         foreach ($deltas as $delta) {
             if (!array_key_exists($delta->language, $deltas_languages)) {
                 $deltas_languages[$delta->language] = array();
             }
             $deltas_languages[$delta->language][] = $delta->delta;
         }
         // Reset the deltas to their correct orders.
         $field_value =& $source_stub->{$field_name};
         foreach ($deltas_languages as $language => $deltas) {
             $new_value = array();
             for ($i = 0; $i < count($field_value[$language]); $i++) {
                 $new_value[$deltas[$i]] = $field_value[$language][$i];
             }
             $field_value[$language] = $new_value;
         }
     } catch (\Exception $ex) {
         // If an exception was thrown, that probably means the field doesn't
         // exist, so we should return false.
         return false;
     }
     return $source_stub;
 }
Esempio n. 14
0
 /**
  * Delete field instance given label, base field name, entity type and bundle.
  *
  * @param string $field_name
  *    Machine name of an existing base field.
  * @param string $entity_type
  *    Entity type machine name.
  * @param string $bundle
  *    Bundle machine name.
  */
 public function deleteInstanceField($field_name, $entity_type, $bundle)
 {
     if ($instance = field_info_instance($entity_type, $field_name, $bundle)) {
         field_delete_instance($instance);
     }
 }
Esempio n. 15
0
 /**
  * Returns field instance from field name for the given entity.
  *
  * @param string $field_name
  *   Field name.
  *
  * @return mixed $instance
  *   An instance array if one exists, FALSE otherwise.
  *
  * @throws \EntityMalformedException
  */
 public function getFieldInstance($field_name)
 {
     list(, , $bundle) = entity_extract_ids($this->entity_type, $this->entity);
     return field_info_instance($this->entity_type, $field_name, $bundle);
 }
function BraftonArticleImporter()
{
    $errors = new BraftonErrorReport(variable_get('brafton_api_key'), variable_get('brafton_api_root'), (bool) variable_get('brafton_debug_mode'));
    //Gathers feed type, Api and Video Keys, and archive file information from the Brafton module settings page.
    $import_list = array();
    $feed_type = variable_get('brafton_feed_type');
    $is_api = variable_get('brafton_api_key');
    $is_archive = variable_get('brafton_archive_file');
    $overwrite = variable_get('brafton_overwrite');
    $is_published = variable_get('brafton_published');
    $counter = 0;
    //Define default fields for b_news type_url_form_media
    if ($is_api || $is_archive) {
        //Loads the date and overwrite settings.
        $date = get_date_setting();
        //Loads the article objects from the feed into an array.
        $article_array = load_article_array($is_archive);
        //Loops through the article array
        foreach ($article_array as $value) {
            //Checks to see if the article already exists.  If it does not, a new node is created of type b_news.  If it does, then depending upon the overwrite settings the existing node is either loaded, or we iterate to the next article in the feed
            $id = $value->getId();
            $check = check_if_article_exists($id);
            if (!empty($check) && $overwrite == 1) {
                $nid = key($check['node']);
                $node = node_load($nid);
            } elseif (empty($check)) {
                $node = new stdClass();
            } else {
                continue;
            }
            //Gets an array of image information from the feed.
            $image = get_image_attributes($value);
            //Gets the article categories as an array of valid and unique term ids.
            $categories = set_article_categories($value, 'b_news');
            //Instantiation of each article component as a field in the node object.
            $node->status = $is_published == 1 ? 0 : 1;
            $types = array('body' => 'body', 'image' => 'field_brafton_image', 'tax' => 'field_brafton_term');
            if (variable_get('brafton_existing_type') != 'b_news') {
                $types['body'] = variable_get('brafton_custom_body');
                $types['image'] = variable_get('brafton_custom_image');
                $types['tax'] = variable_get('brafton_custom_taxonomy');
            }
            $node->type = variable_get('brafton_existing_type');
            $node->language = LANGUAGE_NONE;
            $node->title = $value->getHeadline();
            $import_list['title'][] = $node->title;
            $node->uid = checkAuthor(variable_get('brafton_author'), $value->getByLine());
            //$nodestatus = 1;
            $node->created = strtotime($value->{$date}());
            $node->updated = $node->created;
            $node->promote = 0;
            $node->sticky = 0;
            $node->comment = variable_get('brafton_comments');
            $node->{$types['body']}[$node->language][0] = array('value' => $value->getText(), 'summary' => $value->getExtract(), 'format' => 'full_html');
            if ($image) {
                $node->{$types['image']}[$node->language][0] = (array) system_retrieve_file($image['url'], NULL, TRUE, FILE_EXISTS_REPLACE);
                $node->{$types['image']}[$node->language][0]['alt'] = $image['alt'];
                $node->{$types['image']}[$node->language][0]['title'] = $image['title'];
            }
            if (field_info_instance('node', 'field_brafton_id', $node->type) == NULL) {
                $brafton_id_field = array('field_name' => 'field_brafton_id', 'entity_type' => 'node', 'bundle' => $node->type, 'display' => array('default' => array('label' => 'hidden', 'type' => 'hidden')));
                field_create_instance($brafton_id_field);
            }
            $node->field_brafton_id[$node->language][0]['value'] = $id;
            //Setting the article pause cta text
            //ensure categories don't get added twice
            $cats = false;
            $oldcats;
            if ($overwrite && isset($node->{$types['tax']}[$node->language])) {
                $oldcats = $node->{$types['tax']}[$node->language];
                $cats = true;
            }
            foreach ($categories as $category) {
                if ($cats) {
                    foreach ($oldcats as $oldcat) {
                        if ($oldcat['tid'] != $category) {
                            $node->{$types['tax']}[$node->language][]['tid'] = $category;
                        }
                    }
                } else {
                    $node->{$types['tax']}[$node->language][]['tid'] = $category;
                }
            }
            //end category code
            node_save($node);
            var_dump($node);
            taxonomy_node_insert($node);
            $nid = $node->nid;
            $alias = drupal_get_path_alias("node/" . $nid);
            $counter++;
            ++$errors->level;
        }
    }
    $import_list['counter'] = $counter;
    return $import_list;
}
Esempio n. 17
0
 /**
  * Returns information about field instance.
  *
  * @param Entity $entityObject
  *   Entity for which the field instance is to be returned.
  * @param string $field_name
  *   Field name.
  *
  * @return array|null
  *   An array of field instance information if the instance exists. NULL if
  *   the field instance does not exist.
  */
 public static function getFieldInstance(Entity $entityObject, $field_name)
 {
     list(, , $bundle) = entity_extract_ids($entityObject->getEntityType(), $entityObject->getEntity());
     $instance = field_info_instance($entityObject->getEntityType(), $field_name, $bundle);
     return $instance;
 }
 /**
  * Grab the information about a field instance attached to a bundle.
  *
  * This is simple a wrapper around field_info_instance.
  *
  * @param string $entityType
  *   The entity type the bundle is attached to.
  * @param string $fieldName
  *   The field name (i.e. field_image)
  * @param string $bundleName
  *   The bundle name you are looking on.
  * @return array|null
  *   An array containing the output of field_info_instance or null if the field instance doesn't exist.
  */
 public function grabFieldInstance($entityType, $fieldName, $bundleName)
 {
     return field_info_instance($entityType, $fieldName, $bundleName);
 }
Esempio n. 19
0
 public function build($entityType, $bundleName)
 {
     if (!($info = field_info_instance($entityType, $this->field_name, $bundleName))) {
         field_create_instance(array('entity_type' => $entityType, 'bundle' => $bundleName, 'field_name' => $this->field_name, 'label' => $this->label, 'description' => $this->description, 'required' => $this->required, 'settings' => array(), 'widget' => $this->widget->getDefinition(), 'display' => array()));
     }
 }
Esempio n. 20
0
function _get_field_instance($bundle_name, $field_name)
{
    return field_info_instance('node', $field_name, $bundle_name);
}
 /**
  * Populate public info field with Property API information.
  */
 protected function populatePublicInfoField()
 {
     $field_definition = $this->getDefinition();
     $discovery_info = empty($field_definition['discovery']) ? array() : $field_definition['discovery'];
     $public_field_info = new PublicFieldInfoEntity($this->getPublicName(), $this->getProperty(), $this->getEntityType(), $this->getBundle(), $discovery_info);
     $this->setPublicFieldInfo($public_field_info);
     if ($field_instance = field_info_instance($this->getEntityType(), $this->getProperty(), $this->getBundle())) {
         $public_field_info->addSectionDefaults('info', array('label' => $field_instance['label'], 'description' => $field_instance['description']));
         $field_info = $this::fieldInfoField($this->getProperty());
         $section_info = array();
         $section_info['label'] = empty($field_info['label']) ? NULL : $field_info['label'];
         $section_info['description'] = empty($field_info['description']) ? NULL : $field_info['description'];
         $public_field_info->addSectionDefaults('info', $section_info);
         $type = $public_field_info instanceof PublicFieldInfoEntityInterface ? $public_field_info->getFormSchemaAllowedType() : NULL;
         $public_field_info->addSectionDefaults('form_element', array('default_value' => isset($field_instance['default_value']) ? $field_instance['default_value'] : NULL, 'type' => $type));
         // Loading allowed values can be a performance issue, load them only if
         // they are not provided in the field definition.
         $form_element_info = $public_field_info->getSection('form_element');
         if (!isset($form_element_info['allowed_values'])) {
             $allowed_values = $public_field_info instanceof PublicFieldInfoEntityInterface ? $public_field_info->getFormSchemaAllowedValues() : NULL;
             $public_field_info->addSectionDefaults('form_element', array('allowed_values' => $allowed_values));
         }
     } else {
         // Extract the discovery information from the property info.
         try {
             $property_info = $this->entityTypeWrapper()->getPropertyInfo($this->getProperty());
         } catch (\EntityMetadataWrapperException $e) {
             return;
         }
         if (empty($property_info)) {
             return;
         }
         $public_field_info->addSectionDefaults('data', array('type' => $property_info['type'], 'required' => empty($property_info['required']) ? FALSE : $property_info['required']));
         $public_field_info->addSectionDefaults('info', array('label' => $property_info['label'], 'description' => $property_info['description']));
     }
 }
Esempio n. 22
0
function cubert_attach_form($field_name, $entity_type, $bundle, $entity, &$form, &$form_state, $langcode = NULL)
{
    // Set #parents to 'top-level' if it doesn't exist.
    $form += array('#parents' => array());
    // If no language is provided use the default site language.
    $options = array('language' => field_valid_language($langcode), 'default' => TRUE);
    // Append to the form
    ctools_include('fields');
    $field_instance = field_info_instance($entity_type, $field_name, $bundle);
    $form += (array) ctools_field_invoke_field($field_instance, 'form', $entity_type, $entity, $form, $form_state, $options);
}
Esempio n. 23
0
<?php

$field_instances = field_info_instance('node', $settings['fieldName'], $settings['nodeType']);
$display = field_get_display($field_instances, 'full', $node);
$field_render = field_view_field('node', $node, $settings['fieldName'], $display);
print render($field_render);
 public function setValue($wrapper, $fieldLabel, $rawValue)
 {
     $subField = FALSE;
     if (strpos($fieldLabel, ':') !== FALSE) {
         $fieldStrings = explode(':', $fieldLabel);
         $fieldLabel = $fieldStrings[0];
         $subField = $fieldStrings[1];
     }
     foreach ($wrapper->getPropertyInfo() as $key => $wrapper_property) {
         if ($fieldLabel == $wrapper_property['label']) {
             $fieldMachineName = $key;
             $fieldInfo = isset($wrapper_property['field']) && $wrapper_property['field'] ? field_info_field($fieldMachineName) : array();
             if (empty($fieldInfo)) {
                 switch ($wrapper_property['type']) {
                     case 'boolean':
                         $value = filter_var($rawValue, FILTER_VALIDATE_BOOLEAN);
                         break;
                     case 'date':
                         if (!is_numeric($rawValue)) {
                             $rawValue = strtotime($rawValue);
                         }
                     default:
                         $value = $rawValue;
                 }
             } elseif ($fieldInfo = field_info_field($fieldMachineName)) {
                 // @todo add condition for each field type.
                 switch ($fieldInfo['type']) {
                     case 'entityreference':
                         $relatedEntityType = $fieldInfo['settings']['target_type'];
                         $targetBundles = $fieldInfo['settings']['handler_settings']['target_bundles'];
                         $query = new \EntityFieldQuery();
                         $query->entityCondition('entity_type', $relatedEntityType);
                         // Adding special conditions.
                         if (count($targetBundles) > 1) {
                             $relatedBundles = array_keys($targetBundles);
                             $query->entityCondition('bundle', $relatedBundles, 'IN');
                         } else {
                             $relatedBundles = reset($targetBundles);
                             $query->entityCondition('bundle', $relatedBundles);
                         }
                         if ($relatedEntityType == 'node') {
                             $query->propertyCondition('title', $rawValue);
                         }
                         if ($relatedEntityType == 'taxonomy_term' || $relatedEntityType == 'user') {
                             $query->propertyCondition('name', $rawValue);
                         }
                         $results = $query->execute();
                         if (empty($results)) {
                             throw new \Exception("Entity that you want relate doesn't exist.");
                         }
                         $value = array_keys($results[$relatedEntityType]);
                         if (count($value) == 1) {
                             $value = array_pop($value);
                         }
                         break;
                     case 'image':
                         try {
                             $fieldInstance = field_info_instance($wrapper->type(), $fieldMachineName, $wrapper->getBundle());
                             $fieldDirectory = 'public://' . $fieldInstance['settings']['file_directory'];
                             $image = file_get_contents($rawValue);
                             $pathinfo = pathinfo($rawValue);
                             $filename = $pathinfo['basename'];
                             file_prepare_directory($fieldDirectory, FILE_CREATE_DIRECTORY);
                             $value = (array) file_save_data($image, $fieldDirectory . '/' . $filename, FILE_EXISTS_RENAME);
                             if ($fieldInfo['cardinality'] > 1 || $fieldInfo['cardinality'] == FIELD_CARDINALITY_UNLIMITED) {
                                 $value = array($value);
                             }
                         } catch (Exception $e) {
                             throw new \Exception("File {$rawValue} coundn't be saved.");
                         }
                         break;
                     default:
                         $value = $rawValue;
                         break;
                 }
             }
         }
     }
     if (empty($fieldMachineName)) {
         throw new \Exception("Entity property {$fieldLabel} doesn't exist.");
     }
     if ($subField) {
         $wrapper->{$fieldMachineName}->{$subField} = $value;
     } else {
         $wrapper->{$fieldMachineName} = $value;
     }
     $wrapper->save();
 }
Esempio n. 25
0
function _generate_specifics_string($node)
{
    $string = '';
    $included_fields = array('field_practice_pit', 'field_pit_dug_in_a_ski_area', 'field_pit_is_representative_of_backcountry', 'field_adjacent_to_avy', 'field_near_avalanche', 'field_collapsing_widespread', 'field_collapsing_localized', 'field_cracking', 'field_recent_activity_on_similar', 'field_recent_activity_on_differe', 'field_instability_rapidly_rising', 'field_ski_tracks_on_slope', 'field_we_skiied_slope', 'field_snowmobile_tracks_on_slope', 'field_we_snowmobiled_slope', 'field_poor_pit_location');
    // etc
    $specifics = array();
    // then we loop through the array and add them each to the string.
    foreach ($included_fields as $key => $field) {
        if (isset($node->{$field})) {
            // Anything beyond the specific field here ,  will require accessing via the $node  object
            $field_item = $node->{$field};
            if (isset($field_item['und'][0]) && $field_item['und'][0]['value'] != '0') {
                $item_full = field_info_instance('node', $field, 'snowpit_profile');
                switch ($field) {
                    case 'field_adjacent_to_avy':
                        $specifics[] = $item_full['label'] . ": " . $node->field_near_avalanche['und'][0]['value'];
                        break;
                    case 'field_near_avalanche':
                        break;
                    case 'field_stability_on_similar_slope':
                        $specifics[] = $item_full['label'] . ": " . $node->field_stability_on_similar_slope['und'][0]['value'];
                        break;
                    default:
                        $specifics[] = $item_full['label'];
                        break;
                }
            }
        }
    }
    return implode('; ', $specifics);
}
Esempio n. 26
0
/**
 * Specify token replacement values for combinations.
 *
 * Combination-providing modules should implement this hook.
 *
 * commerce_bpc handles token management for combinations, to ensure
 * a minimally consistent set of tokens. In particular, commerce_bpc
 * will create a FIELD_NAME-value and a FIELD_NAME-label token for
 * each combination-creating field. The -value token should be fit
 * for inclusion in SKUs, while the -label token should be a human readable
 * value.
 *
 * @param string $product_type
 *   The product type to provide tokens for.
 * @param array $combination
 *   An array with field names as keys and their respective
 *   values as values.
 * @param array $options
 *   Options array passed unmodified from hook_tokens(). Make sure
 *   you honor the 'sanitize' property.
 *
 * @return array
 *   An array with two keys 'values' and 'labels', each of which should
 *   have an array keyed by field names with replacements as values.
 *
 * @see hook_commerce_bpc_get_combinations()
 */
function hook_commerce_bpc_tokens($product_type, $combination, $options)
{
    $replacements = array();
    $sanitize = !empty($options['sanitize']);
    foreach ($combination as $field_name => $values) {
        $field = field_info_field($field_name);
        $instance = field_info_instance('commerce_product', $field_name, $product_type);
        if ($field['module'] == 'list' && !_commerce_bpc_get_value($instance, array('commerce_bpc', 'is_static'), FALSE)) {
            // TODO: Treat languages properly.
            $items = reset($values);
            // We only allow a single value per combination, so we can treat
            // this like a single value field.
            $value = $items[0]['value'];
            $replacements['values'][$field_name] = $value;
            $labels = list_allowed_values($field);
            $replacements['labels'][$field_name] = $sanitize ? check_plain($labels[$value]) : $labels[$value];
        }
    }
    return $replacements;
}
Esempio n. 27
0
function snowpilot_user_unit_prefs_check($uid, $redirect_to_user_edit = TRUE)
{
    $account = user_load($uid);
    $drupal_keys_required = array('field_depth_0_from', 'field_depth_units', 'field_temp_units', 'field_coordinate_type', 'field_elevation_units', 'field_longitude_type', 'field_latitude_type', 'field_density_units', 'field_fracture_category', 'field_hardness_scale', 'field_first_name', 'field_last_name', 'name', 'mail');
    $missing_keys = array();
    foreach ($drupal_keys_required as $key) {
        if (count($account->{$key}) == 0) {
            $field = field_info_field($key);
            $field_instance = field_info_instance('node', $key, 'snowpit_profile');
            $missing_keys[] = $field_instance['label'];
        }
    }
    if (count($missing_keys)) {
        drupal_set_message("<h3>Missing User Unit Preferences</h3>You need to set your <a href = '/user/" . $uid . "/edit#edit-field-first-name'>User Unit Preferences</a> before you can create a new Snowpit Profile.<br/>\n\t\t\tThe following preferences have not been set yet: <li>" . implode($missing_keys, '<li>'), 'warning');
        if ($redirect_to_user_edit == TRUE) {
            drupal_goto("snowpilot/user/edit", array('query' => array('destination' => drupal_get_destination())));
        }
        return FALSE;
    }
    return TRUE;
}
Esempio n. 28
0
 /**
  * Returns field instance information.
  *
  * @param string $field_name
  *   Field name.
  *
  * @return array
  *   Field instance array.
  */
 protected function getFieldInstance($field_name)
 {
     list(, , $bundle) = entity_extract_ids($this->entityObject->getEntityType(), $this->entityObject->getEntity());
     $instance = field_info_instance($this->entityObject->getEntityType(), $field_name, $bundle);
     return $instance;
 }
Esempio n. 29
0
 public static function changeInstanceField(array $instance, $new_field_name)
 {
     $old_field = field_info_field($instance['field_name']);
     $new_field = field_info_field($new_field_name);
     if ($old_field['type'] != $new_field['type']) {
         throw new FieldException("Cannot change field instance because they are not the same field type.");
     }
     if ($old_field['storage']['type'] !== 'field_sql_storage') {
         throw new FieldException("Unable to change field type for field {$old_field['field_name']} using storage {$old_field['storage']['type']}.");
     }
     if ($new_field['storage']['type'] !== 'field_sql_storage') {
         throw new FieldException("Unable to change field type for field {$new_field['field_name']} using storage {$new_field['storage']['type']}.");
     }
     if (!field_info_instance($instance['entity_type'], $new_field_name, $instance['bundle'])) {
         $new_instance = $instance;
         $new_instance['field_name'] = $new_field_name;
         field_create_instance($new_instance);
         watchdog('helper', "Created new field instance: {$instance['entity_type']}.{$instance['bundle']}.{$new_field_name}");
     }
     // Copy data from old field tables to the new field tables.
     $old_data_table = _field_sql_storage_tablename($old_field);
     $new_data_table = _field_sql_storage_tablename($new_field);
     $query = db_select($old_data_table, 'old');
     $query->fields('old');
     $query->condition('entity_type', $instance['entity_type']);
     $query->condition('bundle', $instance['bundle']);
     db_insert($new_data_table)->from($query)->execute();
     $old_revision_table = _field_sql_storage_revision_tablename($old_field);
     if (db_table_exists($old_revision_table)) {
         $new_revision_table = _field_sql_storage_revision_tablename($new_field);
         $query = db_select($old_revision_table, 'old');
         $query->fields('old');
         $query->condition('entity_type', $instance['entity_type']);
         $query->condition('bundle', $instance['bundle']);
         db_insert($new_revision_table)->from($query)->execute();
     }
     FieldHelper::deleteInstance($instance);
 }
Esempio n. 30
0
    field_delete_instance($instance);
}
// From roles nodes.
if ($instance = field_info_instance('node', 'field_diaet', 'roles')) {
    field_delete_instance($instance);
}
if ($instance = field_info_instance('node', 'field_invitation', 'roles')) {
    field_delete_instance($instance);
}
if ($instance = field_info_instance('node', 'field_reminder', 'roles')) {
    field_delete_instance($instance);
}
if ($instance = field_info_instance('node', 'field_rsvp_yes', 'roles')) {
    field_delete_instance($instance);
}
if ($instance = field_info_instance('node', 'field_rsvp_no', 'roles')) {
    field_delete_instance($instance);
}
if ($instance = field_info_instance('node', 'field_rsvp_never', 'roles')) {
    field_delete_instance($instance);
}
// From volutneer nodes.
if ($instance = field_info_instance('node', 'field_token', 'volunteers')) {
    field_delete_instance($instance);
}
if ($instance = field_info_instance('node', 'field_rsvp', 'volunteers')) {
    field_delete_instance($instance);
}
if ($instance = field_info_instance('node', 'field_rsvp_comment', 'volunteers')) {
    field_delete_instance($instance);
}