/** * Overrides CommerceLicenseBase::formValidate(). */ public function formValidate($form, &$form_state) { parent::formValidate($form, $form_state); $parents_path = implode('][', $form['#parents']); $form_values = drupal_array_get_nested_value($form_state['values'], $form['#parents']); // Validate the cle_name field value. if ($form_values['cle_name'][LANGUAGE_NONE][0]['value'] == 'John Smith') { form_set_error($parents_path . '][cle_name][und][0][value', t('John Smith is not allowed to have licenses.')); } }
/** * Overrides EntityInlineEntityFormController::entityFormSubmit(). * * Fixes some of the custom entity values, similar to * fieldable_panels_panes_entity_edit_form_submit(). */ public function entityFormSubmit(&$entity_form, &$form_state) { $info = entity_get_info($this->entityType); list(, , $bundle) = entity_extract_ids($this->entityType, $entity_form['#entity']); $entity = $entity_form['#entity']; $entity_values = drupal_array_get_nested_value($form_state['values'], $entity_form['#parents']); // Some additional adjustments necessary for FPP to save correctly. if (!empty($entity_values['link']['path'])) { $entity_values['path'] = $entity_values['link']['path']; } if (isset($entity_values['link']['link'])) { $entity_values['link'] = $entity_values['link']['link']; } else { $entity_values['link'] = 0; } // The 'reusable' option contains several sub fields. if (isset($entity_values['reusable']['reusable'])) { $reusable = $entity_values['reusable']; $entity_values['reusable'] = FALSE; $entity_values['category'] = ''; $entity_values['admin_title'] = ''; $entity_values['admin_description'] = ''; foreach (array('reusable', 'category', 'admin_title', 'admin_description') as $field) { if (isset($reusable[$field])) { $entity_values[$field] = $reusable[$field]; } } } // Only fix the revision log if a revision is being saved. $entity_values['log'] = ''; if (isset($entity_values['revision']['revision'])) { if (isset($entity_values['revision']['log'])) { $entity_values['log'] = $entity_values['revision']['log']; } $entity_values['revision'] = $entity_values['revision']['revision']; } else { $entity_values['revision'] = 0; } // Copy top-level form values that are not for fields to entity properties, // without changing existing entity properties that are not being edited by // this form. Copying field values must be done using field_attach_submit(). $values_excluding_fields = $info['fieldable'] ? array_diff_key($entity_values, field_info_instances($this->entityType, $bundle)) : $entity_values; foreach ($values_excluding_fields as $key => $value) { $entity->{$key} = $value; } if ($info['fieldable']) { field_attach_submit($this->entityType, $entity, $entity_form, $form_state); } }
/** * Fill textfield in the form with random text values. * * @param Form $formObject * Form object. * @param string|array $field_name * Field name if it is present at top-level form element. If it is not at * the top-level form element, then provide an array. * @param array $options * Options array. * * @return array * An array with 3 values: * (1) $success: Whether the field could be filled with provided values. * (2) $values: Values that were filled. * (3) $msg: Error message if $success is FALSE and empty otherwise. */ public static function fillRandomValues(Form $formObject, $field_name, $options = array()) { $num = 1; $text_processing = FALSE; $max_length = 100; $is_cck_field = FALSE; if (method_exists($formObject, 'getEntityObject')) { // This is an entity form. list($field, $instance, $field_num) = $formObject->getFieldDetails($field_name); if (!is_null($field) && !is_null($instance)) { $text_processing = $instance['settings']['text_processing']; $max_length = $field['settings']['max_length']; $is_cck_field = TRUE; $num = $field_num; } } if (!$is_cck_field) { $array = is_array($field_name) ? $field_name : array($field_name); $key_exists = NULL; $form = $formObject->getForm(); $value = drupal_array_get_nested_value($form, $array, $key_exists); $max_length = $value['#maxlength']; } $field_class = get_called_class(); $values = $field_class::generateValues($num, $text_processing, FALSE, $max_length, FALSE); $function = "fill" . Utils::makeTitleCase($field_name) . "Values"; if (!$is_cck_field) { if (is_array($field_name)) { return $formObject->fillFieldValues($field_name, $values['value']); } else { return $formObject->{$function}($values['value']); } } elseif (is_array($field_name)) { return $formObject->fillFieldValues($field_name, $values); } else { return $formObject->{$function}($values); } }
function translateOneNode($currentNodeID, $to_languages, $content_type) { global $db, $XMLarray, $error_log; $separator = "7543545165934149"; // Fetch a node from Drupal if a copy does not already exist in sources dir. // $xml_MASTER is the original English-language version // $xml is the copy that will be translated $fn = getcwd() . "/sources/SOURCE_" . $currentNodeID . ".XML"; if (file_exists($fn)) { $xml_MASTER = file_get_contents($fn); if ($content_type == "page") { // Remove <teaser> from "page". The "teaser" is created by truncating the <body>, resulting in invalid XML $xml_MASTER = preg_replace("|<teaser>.*?</teaser>|us", "<teaser></teaser>", $xml_MASTER); } } else { $xml_MASTER = fetchOneNode($currentNodeID); if ($content_type == "page") { $xml_MASTER = preg_replace("|<teaser>.*?</teaser>|us", "<teaser></teaser>", $xml_MASTER); } $fh = fopen($fn, "w"); fwrite($fh, $xml_MASTER); fclose($fh); } foreach ($to_languages as $to_language) { $query = "select drupal_code from sovee.languages where sovee_code = '" . $to_language . "'"; $result = mysql_query($query, $db); while ($row = mysql_fetch_assoc($result)) { $drupalLanguageCode = $row['drupal_code']; } mysql_free_result($result); echo "\n=====================================================================================\n========== ==========\n. . . Translating node {$currentNodeID} ({$content_type}) into {$to_language} . . . \n"; $error_IncompleteNodeFlag = 0; $xml = $xml_MASTER; // Create a copy of the master, to be translated // Convert XML to array $XMLarray = XML2Array::createArray($xml); // Get info about the node // Requested info is placed in the $requestedTags array // and returned in the assoc. array info() $requestedTags = array("type", "tnid"); $info = getXMLinfo($xml, $requestedTags); $derivedContentType = $info['type']; // Build list of containers to parse for the given content_type. $query = "select DISTINCT sovee.node_fields.name from sovee.content_type \nLEFT JOIN sovee.field_map ON sovee.content_type.id = sovee.field_map.content_id\nLEFT JOIN sovee.node_fields ON sovee.node_fields.id = sovee.field_map.field_id\nWHERE sovee.content_type.name = '" . $derivedContentType . "'"; $result = mysql_query($query, $db); while ($row = mysql_fetch_assoc($result)) { $containerArrayTemplate[] = $row['name']; } mysql_free_result($result); // Walk throught the array, extract the specified containers, translate // and replace in the array // All array elements are assumed to be in the [node_export][node] array // $containerArrayTemplate = array("body", "title", "teaser", "field_product_subtitle|n*|value", "field_warranty|n*|value", "field_product_education|n*|value", // "field_prod_man_docs_link|n*|title", // "field_did_you_know|n*|value", "field_product_benefits|n*|value", "nodewords|copyright|value", "nodewords|dcterms.contributor|value", // "nodewords|dcterms.title|value", "nodewords|description|value", "nodewords|keywords|value" ); $containerArray = expandTemplate($containerArrayTemplate); $allContainers = "<div>{$separator}"; foreach ($containerArray as $oneContainer) { echo "\nProcessing container {$oneContainer}\n"; $parents = explode("|", $oneContainer); array_unshift($parents, "node_export", "node"); #echo "Parents: "; #print_r($parents); $XMLfragment = drupal_array_get_nested_value($XMLarray, $parents); if (is_array($XMLfragment)) { $XMLfragment = ""; } $translatedFragment = ""; $patterns = array("|^<div>|us", "|</div>\$|us"); // The "|u" flag enables multibyte support $replacements = array("", ""); if (strlen(trim($XMLfragment)) > 0 and !is_array($XMLfragment)) { $XMLfragment = "<div>" . $XMLfragment . "</div>"; // Encapsulate in dummy <div> to satisfy Sovee translator // echo "ORIGINAL Fragment = |$XMLfragment|\n"; } else { echo "Original Fragment |{$XMLfragment}| is empty -- skipping.\n"; } $allContainers .= $XMLfragment . $separator; // Add at the end of each container to faciliate preg_split } // ------- End of foreach($containerArray as $oneContainer) $allContainers .= "</div>"; // Translate the entire node if target language is not English echo "TO_LANGUAGE = {$to_language}\n"; $xxx = substr($to_language, 0, 2); echo "SUBSTR = |{$xxx}|\n"; $sovee_to_language = $to_language; if (substr($to_language, 0, 2) != "en") { if ($to_language == "es-419") { $sovee_to_language = "es-es"; } // Use standard Spanish for Latin America echo "Sending strings to Sovee . . . \n"; $translatedFragmentAry = translateFrag($allContainers, $currentNodeID, "FULL NODE", $to_language); // Perform the translation $translatedFragment = $translatedFragmentAry['content']; $translatedFragmentError = $translatedFragmentAry['error_count']; // Count of translation errors. 0 = success $error_IncompleteNodeFlag += $translatedFragmentError; } else { echo "English-to-English: No translation needed.\n"; $translatedFragment = $allContainers; $translatedFragmentError = 0; } // print_r($translatedFragmentAry); $separatorPattern = "/{$separator}/u"; $translatedNodeAry = preg_split($separatorPattern, $translatedFragment); // print_r($translatedNodeAry); $translatedContentPointer = 1; reset($containerArray); foreach ($containerArray as $oneContainer) { $parents = explode("|", $oneContainer); array_unshift($parents, "node_export", "node"); $stripped = trim(preg_replace($patterns, $replacements, $translatedNodeAry[$translatedContentPointer])); // Remove the leading and trailing <div>s from the node fragments // Special handling for page_title, which can be a string or an array if ($oneContainer == "page_title" and $stripped == "Array") { $pageTitleParents1 = array('node_export', 'node', 'page_title', 'value'); $pageTitleParents2 = array('node_export', 'node', 'page_title', 'attributes', 'type'); drupal_array_set_nested_value($XMLarray, $pageTitleParents1, "FALSE"); drupal_array_set_nested_value($XMLarray, $pageTitleParents2, "boolean"); } else { if (strlen($stripped) > 0) { drupal_array_set_nested_value($XMLarray, $parents, $stripped); } } $translatedContentPointer++; } // HTML-Encode any info in the <data> container // $dataParents = array('node_export', 'node', 'data'); // $dataFragment = htmlentities(drupal_array_get_nested_value($XMLarray, $dataParents)); // drupal_array_set_nested_value($XMLarray, $dataParents, $dataFragment); #echo "TRANSLATED XML ARRAY:"; #print_r($XMLarray); // Does an older version of this translated node exist? // If yes, return the node# and alias in an array // otherwise, $oldNodeID_ary['number'] == '' $oldNodeID_ary = findOldTranslation($currentNodeID, $to_language); $oldNodeID = $oldNodeID_ary['number']; $oldNodeIDalias = $oldNodeID_ary['url_alias']; if ($oldNodeID != "") { echo "\nFound old node number -- old={$oldNodeID}\n"; } if ($oldNodeIDalias != "") { echo "\nFound old node number alias -- old={$oldNodeIDalias}\n"; } // Update the nid and tnid fields // For new nodes, nid='' // and tnid = the current nid value $XMLarray['node_export']['node']['tnid'] = $currentNodeID; $XMLarray['node_export']['node']['nid'] = $oldNodeID; // $XMLarray['node_export']['node']['language'] = $oldNodeID['drupal_lang_code']; $XMLarray['node_export']['node']['language'] = $drupalLanguageCode; // // // $XMLarray['node_export']['node']['path'] = $oldNodeID['url_alias']; if (isset($XMLarray['node_export']['node']['xmlsitemap']['language'])) { // $XMLarray['node_export']['node']['xmlsitemap']['language'] = $oldNodeID['drupal_lang_code']; $XMLarray['node_export']['node']['xmlsitemap']['language'] = $drupalLanguageCode; } //echo "XMLARRAY = \n"; //print_r($XMLarray); $FOO = $XMLarray['node_export']['node']['nodewords']['location']['latitude']; $BAR = $XMLarray['node_export']['node']['nodewords']['location']['longitude']; echo "FOO = {$FOO}\nBAR = {$BAR}\n"; // If lat or long > 8 chars, set to zero, otherwise node will not import if (isset($XMLarray['node_export']['node']['nodewords']['location']['latitude'])) { if (strlen($XMLarray['node_export']['node']['nodewords']['location']['latitude']) > 8) { $XMLarray['node_export']['node']['nodewords']['location']['latitude'] = 0; } } if (isset($XMLarray['node_export']['node']['nodewords']['location']['longitude'])) { if (strlen($XMLarray['node_export']['node']['nodewords']['location']['longitude']) > 8) { $XMLarray['node_export']['node']['nodewords']['location']['longitude'] = 0; } } // Adjust the menu references $this_plid = $XMLarray['node_export']['node']['menu']['plid']; $this_menu_name = $XMLarray['node_export']['node']['menu']['menu_name']; if ($this_menu_name == "primary-links") { $mquery = "SELECT t_menuid from sovee.menus LEFT JOIN sovee.languages on sovee.menus.language_code = sovee.languages.id WHERE drupal_code = \"" . $drupalLanguageCode . "\" and Eng_menuid = \"" . $this_plid . "\""; echo "MQ = {$mquery}\n"; $rmquery = mysql_query($mquery, $db); $err_msg = trim(mysql_error($db)); if (strlen($err_msg) > 0) { echo "{$mquery}\n{$err_msg}\n\n\n"; } while ($m1 = mysql_fetch_assoc($rmquery)) { $newPlid = $m1['t_menuid']; $XMLarray['node_export']['node']['menu']['plid'] = $newPlid; } mysql_free_result($rmquery); } // Convert array back to XML $encoding = "UTF-8"; $xmlVersion = "1.0"; Array2XML::init($xmlVersion, $encoding); $xmlobj = Array2XML::createXML('DELETE_ME', $XMLarray); // Convert a PHP array to XML, using 'DELETE_ME' as the root_node_name $translated_xml = $xmlobj->saveXML(); // Returned object is of type DOMDocument $translated_xml = preg_replace("/<[\\/]?DELETE_ME>[\n]/u", "", $translated_xml); $fn = getcwd() . "/TRANSLATED_" . $drupalLanguageCode . "_" . $currentNodeID . ".XML"; echo "WRITING {$fn}\n"; $fh = fopen($fn, "w"); fwrite($fh, $translated_xml); fclose($fh); // If node translation was successful, // import the translated node back into Drupal if ($error_IncompleteNodeFlag == 0) { $cmd = "/usr/bin/drush --root=/var/www/pressflow node-export-import --file={$fn}"; echo "COMMAND = {$cmd}\n"; $success = `{$cmd}`; $error = "DRUSH IMPORT RESULTS: {$success}\n"; echo $error; fwrite($error_log, $error); $cmd = "/bin/rm {$fn}"; #$success = `$cmd`; $q1 = "INSERT INTO sovee.progress (node, status, type, language) VALUES(\"" . $currentNodeID . "\", \"1\", \"" . $derivedContentType . "\", \"" . $to_language . "\") ON DUPLICATE KEY UPDATE status=VALUES(status)"; echo "Q1={$q1}\n"; $r1 = mysql_query($q1, $db); } else { $error = "Node {$currentNodeID} ({$content_type}) not completely translated. Not importing into Drupal.\n"; echo $error; $q1 = "INSERT INTO sovee.progress (node, status, type, language) VALUES(\"" . $currentNodeID . "\", \"0\", \"" . $derivedContentType . "\", \"" . $to_language . "\") ON DUPLICATE KEY UPDATE status=VALUES(status)"; $r1 = mysql_query($q1, $db); $err_msg = trim(mysql_error($db)); if (strlen($err_msg) > 0) { echo "{$q1}\n{$err_msg}\n\n\n"; } fwrite($error_log, $error); } echo "========== ==========\n=====================================================================================\n"; } $translated_xml_array = array('status' => $error_IncompleteNodeFlag, 'translated_xml' => $translated_xml); return $translated_xml_array; }
/** * Helper function for retaining settings of an extension. */ function _omega_retain_extension_settings($form, &$form_state, $extension, $theme, $parents = array()) { $current = array_merge(array('omega', $extension, 'settings'), $parents); if ($items = drupal_array_get_nested_value($form, $current)) { foreach (element_children($items) as $key) { if (array_key_exists($key, $form_state['values'])) { $form_state['values'][$key] = omega_theme_get_setting($key, NULL, $theme); } $next = array_merge($parents, array($key)); _omega_retain_extension_settings($form, $form_state, $extension, $theme, $next); } } }
/** * Act on field_attach_submit(). * * This hook is invoked after the field module has performed the operation. * * @param $entity_type * The type of $entity; for example, 'node' or 'user'. * @param $entity * The entity for which an edit form is being submitted. The incoming form * values have been extracted as field values of the $entity object. * @param $form * The form structure where field elements are attached to. This might be a * full form structure, or a sub-part of a larger form. The $form['#parents'] * property can be used to identify the corresponding part of * $form_state['values']. * @param $form_state * An associative array containing the current state of the form. */ function hook_field_attach_submit($entity_type, $entity, $form, &$form_state) { // Sample case of an 'Empty the field' checkbox added on the form, allowing // a given field to be emptied. $values = drupal_array_get_nested_value($form_state['values'], $form['#parents']); if (!empty($values['empty_field_foo'])) { unset($entity->field_foo); } }
/** * Implements hook_field_attach_submit(). */ public function hook_field_attach_submit($entity, &$form, &$form_state) { // Call parent. parent::hook_field_attach_submit($entity, $form, $form_state); // Save paragraph item panelizer settings. if (!empty($form_state['panelizer has choice'])) { list($entity_id, $revision_id, $bundle) = entity_extract_ids($this->entity_type, $entity); foreach ($this->plugin['view modes'] as $view_mode => $view_mode_info) { if (isset($form['#parents']) && drupal_array_nested_key_exists($form_state['values'], $form['#parents'])) { $values = drupal_array_get_nested_value($form_state['values'], $form['#parents']); if (isset($values['panelizer'][$view_mode]['name'])) { $entity->panelizer[$view_mode] = clone $this->get_default_panelizer_object($bundle . '.' . $view_mode, $values['panelizer'][$view_mode]['name']); if (!empty($entity->panelizer[$view_mode])) { $entity->panelizer[$view_mode]->did = NULL; // Ensure original values are maintained, if they exist. if (isset($form['panelizer'][$view_mode]['name'])) { $entity->panelizer[$view_mode]->entity_id = $form['panelizer'][$view_mode]['name']['#entity_id']; $entity->panelizer[$view_mode]->revision_id = $form['panelizer'][$view_mode]['name']['#revision_id']; } } } } } } }
/** * Modify the entity render array in the context of a view. * * @param array $content * By reference. An entity view render array. * @param array $context * By reference. An associative array containing: * - row: The current active row object being rendered. * - view: By reference. The current view object. * - view_mode: The view mode which is set in the Views' options. * - load_comments: The same param passed to each row function. * * @see ds_views_row_render_entity() */ function hook_ds_views_row_render_entity_alter(&$content, &$context) { if ($context['view_mode'] == 'my_mode') { // Modify the view, or the content render array in the context of a view. $view =& $context['view']; $element =& drupal_array_get_nested_value($content, array('field_example', 0)); } }
/** * Submit callback for the bundle edit form. */ public function add_bundle_setting_form_submit($form, &$form_state, $bundle, $type_location) { // Some types do not support changing bundles, so we don't check if it's // not possible to change. if ($type_location) { $new_bundle = drupal_array_get_nested_value($form_state['values'], $type_location); } else { $new_bundle = $bundle; } // Check to see if the bundle has changed. If so, we need to move stuff // around. if ($bundle && $new_bundle != $bundle) { // Remove old settings. variable_del('panelizer_defaults_' . $this->entity_type . '_' . $bundle); $allowed_layouts = variable_get('panelizer_' . $this->entity_type . ':' . $bundle . '_allowed_layouts', NULL); if ($allowed_layouts) { variable_del('panelizer_' . $this->entity_type . ':' . $bundle . '_allowed_layouts'); variable_set('panelizer_' . $this->entity_type . ':' . $new_bundle . '_allowed_layouts', $allowed_layouts); } $default = variable_get('panelizer_' . $this->entity_type . ':' . $bundle . '_default', NULL); if ($default) { variable_del('panelizer_' . $this->entity_type . ':' . $bundle . '_default'); variable_set('panelizer_' . $this->entity_type . ':' . $new_bundle . '_default', $default); } // Load up all panelizer defaults for the old bundle and resave them // for the new bundle. $panelizer_defaults = $this->get_default_panelizer_objects($bundle); if (!empty($panelizer_defaults)) { foreach ($panelizer_defaults as $panelizer) { list($entity_type, $old_bundle, $name) = explode(':', $panelizer->name); $panelizer->name = implode(':', array($entity_type, $new_bundle, $name)); if ($panelizer->view_mode != 'page_manager') { $panelizer->name .= ':' . $panelizer->view_mode; } // The default display selection. $old_variable_name = 'panelizer_' . $this->entity_type . ':' . $bundle . ':' . $panelizer->view_mode . '_selection'; $new_variable_name = 'panelizer_' . $this->entity_type . ':' . $new_bundle . ':' . $panelizer->view_mode . '_selection'; $default_layout = variable_get($old_variable_name, NULL); if (!is_null($default_layout)) { variable_set($new_variable_name, $default_layout); variable_del($old_variable_name); } $panelizer->panelizer_key = $new_bundle; // If there's a pnid this should change the name and retain the pnid. // If there is no pnid this will create a new one in the database // because exported panelizer defaults attached to a bundle will have // to be moved to the database in order to follow along and then be // re-exported. // @todo Should we warn the user about this? ctools_export_crud_save('panelizer_defaults', $panelizer); } } } // Fix the configuration. // If the main configuration is disabled then everything gets disabled. if (empty($form_state['values']['panelizer']['status'])) { $form_state['values']['panelizer']['view modes'] = array(); } elseif (!empty($form_state['values']['panelizer']['view modes'])) { // Make sure each setting is disabled if the view mode is disabled. foreach ($form_state['values']['panelizer']['view modes'] as $view_mode => &$config) { if (empty($config['status'])) { foreach ($config as $key => $val) { $config[$key] = 0; } } } } // Save the default display for this bundle to a variable so that it may be // controlled separately. foreach ($this->get_default_panelizer_objects($new_bundle) as $panelizer) { if (!empty($form_state['values']['panelizer']['view modes'][$panelizer->view_mode]['default display'])) { $new_value = $form_state['values']['panelizer']['view modes'][$panelizer->view_mode]['default display']; $variable_name = 'panelizer_' . $this->entity_type . ':' . $new_bundle . ':' . $panelizer->view_mode . '_selection'; variable_set($variable_name, $new_value); // Don't save the setting with the rest of the settings bundle. unset($form_state['values']['panelizer']['view modes'][$panelizer->view_mode]['default display']); } } variable_set('panelizer_defaults_' . $this->entity_type . '_' . $new_bundle, $form_state['values']['panelizer']); // Unset this so that the type save forms don't try to save it to variables. unset($form_state['values']['panelizer']); }
/** * Returns class and widget type of a field. * * @param Form $formObject * Form object. * @param string|array $field_name * Field name if the field is at top level of the form, otherwise an array * with parents and field name. * * @return array * An array with two values: * (a) Field class * (b) Widget type in Title Case. */ public static function getFieldClass(Form $formObject, $field_name) { $field_class = ''; $widget_type = ''; if (is_string($field_name) && method_exists($formObject, 'getEntityObject')) { // This is an entity form. list($field, $instance, $num) = $formObject->getFieldDetails($field_name); if (!is_null($field) && !is_null($instance)) { $short_field_class = Utils::makeTitleCase($field['type']); $field_class = "RedTest\\core\\fields\\" . $short_field_class; $widget_type = Utils::makeTitleCase($instance['widget']['type']); return array($field_class, $widget_type); } } // Code execution came here that means that either the form is not an // EntityForm or the field name is a property and is not really a field. $array = is_array($field_name) ? $field_name : array($field_name); $key_exists = NULL; $form = $formObject->getForm(); $value = drupal_array_get_nested_value($form, $array, $key_exists); if ($key_exists) { $type = $value['#type']; switch ($type) { case 'textfield': $field_class = 'Text'; break; } if (!empty($field_class)) { $field_class = "RedTest\\core\\fields\\" . $field_class; } return array($field_class, $widget_type); } }
/** * Returns whether a field is required. * * @param string|array $parents * Field name or an array of parents along with the field name. * @param bool check_children * Check whether any of the children is required. This usually is needed * for CCK fields. For CCK fields, the field itself may not be required by * its child such as [LANGUAGE_NONE] may be required. In that case, the * fields itself should be considered as required. * * @return boolean * TRUE if the field is required and FALSE otherwise. */ public function isRequired($parents, $check_children = FALSE) { if (is_string($parents) || is_numeric($parents)) { $parents = array($parents); } $key_exists = NULL; $value = drupal_array_get_nested_value($this->form, $parents, $key_exists); if ($key_exists) { if (!$check_children) { return isset($value['#required']) && $value['#required']; } // Go through the children and see if any of them is required. foreach (element_children($value) as $index) { if (isset($value[$index]['#required']) && $value[$index]['#required']) { return TRUE; } } } return FALSE; }
/** * Perform alterations on the field form elements provide by a field module. * * Modules can implement hook_commerce_bpc_MODULE_NAME_form_element_alter() * to act only on the form elements provided by field types defined by a * specific module, rather than implementing * hook_commerce_bpc_form_element_alter() and checking the field type, or * using long switch statements to alter form elements of multiple field * types. * * This hook is particularly useful in case the field-defining module * defines several similar field type which essentially are to be * treated identically during bulk creation (such as core's list.module), * which would require multiple identical implementations of * hook_commerce_bpc_FIELD_TYPE_form_element_alter(). * * @param array $form * Nested array of form elements that comprise the bulk creation form. * @param array $form_state * A keyed array containing the current state of the form. * @param array $path * An array of keys specifying where in the form the current element * is to be found. This should be reset if the element is moved. * * @see hook_commerce_bpc_form_element_alter() * @see hook_commerce_bpc_FIELD_TYPE_form_element_alter() */ function hook_commerce_bpc_MODULE_NAME_form_element_alter(&$form, &$form_state, $path) { // Modification for form elements related to field types defined by a // specific module go here. For example, MODULE_NAME is "list" this code will // run only on fields of type "list_text", "list_integer", "list_float" and // "list_boolean". $element = drupal_array_get_nested_value($form, $path); $lang = $element['#language']; $field_name = $element[$lang]['#field_name']; $instance = field_info_instance('commerce_product', $field_name, $form['product_type']['#value']); if (commerce_bpc_commerce_bpc_is_combination_field($instance)) { $element[$lang]['#type'] = 'checkboxes'; // Get rid of 'none' option---user can just not pick any. unset($element[$lang]['#options']['_none']); // Move to comibinations-fieldset. $form['combinations'][$field_name] = $element; drupal_array_set_nested_value($form, $path, NULL); // Change path to allow subsequent hooks operate on the form element. $path = array('combinations', $field_name); if (empty($form_state['commerce_bpc']['list']['combination_fields']) || !in_array($field_name, $form_state['commerce_bpc']['list']['combination_fields'])) { // Record what we have done. As this hook may be run multiple times // due to form rebuilds, we need to make sure that we record each field // only once. $form_state['commerce_bpc']['list']['combination_fields'][] = $field_name; } } }
/** * AJAX Callback for the path table. * * @param $form * @param $form_state * @param $offset_to_root * @param $clear * * @throws \Exception * @return array */ public static function ajaxCallbackBase($form, $form_state, $offset_to_root, $clear = false) { if (!array_key_exists('triggering_element', $form_state)) { throw new \Exception('The trigger could not be found.'); } $trigger = $form_state['triggering_element']; $parents = array_slice($trigger['#array_parents'], 0, count($trigger['#array_parents']) - $offset_to_root); $parents[] = 'paths'; $parents_form = drupal_array_get_nested_value($form, $parents); $commands = array(); $commands[] = ajax_command_replace(null, theme('publisher_purge_configure_content_type_table', array('paths_form' => $parents_form))); $commands[] = ajax_command_prepend(null, theme('status_messages')); if ($clear) { // Get the "Add Path" textbox. $add_path_parents = array_slice($parents, 0, count($parents) - 1); $add_path_parents[] = 'add_path'; $add_path_parents[] = 'path'; $add_path = drupal_array_get_nested_value($form, $add_path_parents); // TODO: Actually find out why the form API is adding numbers to the IDs. $add_path_id = str_replace('--2', '', $add_path['#id']); $commands[] = ajax_command_invoke('#' . $add_path_id, 'val', array('')); } return array('#type' => 'ajax', '#commands' => $commands); }
/** * Submit callback for the bundle edit form. */ public function add_bundle_setting_form_submit($form, &$form_state, $bundle, $type_location) { // Some types do not support changing bundles, so we don't check if it's // not possible to change. if ($type_location) { $new_bundle = drupal_array_get_nested_value($form_state['values'], $type_location); } else { $new_bundle = $bundle; } // Check to see if the bundle has changed. If so, we need to move stuff // around. if ($bundle && $new_bundle != $bundle) { // Remove old settings. variable_del('panelizer_defaults_' . $this->entity_type . '_' . $bundle); $allowed_layouts = variable_get('panelizer_' . $this->entity_type . ':' . $bundle . '_allowed_layouts', NULL); if ($allowed_layouts) { variable_del('panelizer_' . $this->entity_type . ':' . $bundle . '_allowed_layouts'); variable_set('panelizer_' . $this->entity_type . ':' . $new_bundle . '_allowed_layouts', $allowed_layouts); } $default = variable_get('panelizer_' . $this->entity_type . ':' . $bundle . '_default', NULL); if ($default) { variable_del('panelizer_' . $this->entity_type . ':' . $bundle . '_default'); variable_set('panelizer_' . $this->entity_type . ':' . $new_bundle . '_default', $default); } // Load up all panelizer defaults for the old bundle and resave them // for the new bundle. $panelizer_defaults = $this->get_default_panelizer_objects($bundle); if (!empty($panelizer_defaults)) { foreach ($panelizer_defaults as $panelizer) { list($entity_type, $old_bundle, $name) = explode(':', $panelizer->name); $panelizer->name = implode(':', array($entity_type, $new_bundle, $name)); if ($panelizer->view_mode != 'page_manager') { $panelizer->name .= ':' . $panelizer->view_mode; } // The default display selection. $old_variable_name = 'panelizer_' . $this->entity_type . ':' . $bundle . ':' . $panelizer->view_mode . '_selection'; $new_variable_name = 'panelizer_' . $this->entity_type . ':' . $new_bundle . ':' . $panelizer->view_mode . '_selection'; $default_layout = variable_get($old_variable_name, NULL); if (!is_null($default_layout)) { variable_set($new_variable_name, $default_layout); variable_del($old_variable_name); } $panelizer->panelizer_key = $new_bundle; // If there's a pnid this should change the name and retain the pnid. // If there is no pnid this will create a new one in the database // because exported panelizer defaults attached to a bundle will have // to be moved to the database in order to follow along and then be // re-exported. // @todo Should we warn the user about this? ctools_export_crud_save('panelizer_defaults', $panelizer); } } } // Fix the configuration. // If the main configuration is disabled then everything gets disabled. if (empty($form_state['values']['panelizer']['status'])) { $form_state['values']['panelizer']['view modes'] = array(); } elseif (!empty($form_state['values']['panelizer']['view modes'])) { // Make sure each setting is disabled if the view mode is disabled. foreach ($form_state['values']['panelizer']['view modes'] as $view_mode => &$config) { if (empty($config['status'])) { foreach ($config as $key => $val) { $config[$key] = 0; } } } } // Save the default display for this bundle to a variable so that it may be // controlled separately. foreach ($this->get_default_panelizer_objects($new_bundle) as $panelizer) { if (isset($form_state['values']['panelizer']['view modes'][$panelizer->view_mode]['selection'])) { $variable_name = 'panelizer_' . $this->entity_type . ':' . $new_bundle . ':' . $panelizer->view_mode . '_selection'; $old_value = variable_get($variable_name, NULL); $new_value = $form_state['values']['panelizer']['view modes'][$panelizer->view_mode]['selection']; // Save the variable. variable_set($variable_name, $new_value); // Cleanup. // Additional cleanup if the default display was changed. if (!is_null($old_value) && $old_value != $new_value) { // The user specifically requested that existing entities are to be // updated to the new display. if (!empty($form_state['values']['panelizer']['view modes'][$panelizer->view_mode]['default revert'])) { $updated_count = db_update('panelizer_entity')->fields(array('name' => $new_value))->condition('name', $old_value)->execute(); drupal_set_message(t('@count @entity records were updated to the new Panelizer display for the @mode view mode.', array('@count' => $updated_count, '@entity' => $this->entity_type, '@mode' => $panelizer->view_mode))); // If EntityCache is enabled, clear all records of this type. This // is a little heavy-handed, but I don't believe there's an easy way // to clear only entities of certain types without querying for them // first, which could trigger an execution timeout. if (module_exists('entitycache')) { cache_clear_all('*', 'cache_entity_' . $this->entity_type, TRUE); } } } } } // Remove some settings that shouldn't be saved with the others. if (!empty($form_state['values']['panelizer']['view modes'])) { foreach ($form_state['values']['panelizer']['view modes'] as $view_mode => $settings) { unset($form_state['values']['panelizer']['view modes'][$view_mode]['selection']); unset($form_state['values']['panelizer']['view modes'][$view_mode]['default revert']); } } variable_set('panelizer_defaults_' . $this->entity_type . '_' . $new_bundle, $form_state['values']['panelizer']); // Verify the necessary Page Manager prerequisites are ready. if (!empty($form_state['values']['panelizer']['status']) && !empty($form_state['values']['panelizer']['view modes']['page_manager']['status']) && $this->is_page_manager_enabled()) { $this->check_page_manager_status(); } // Unset this so that the type save forms don't try to save it to variables. unset($form_state['values']['panelizer']); }
/** * Submit callback for the bundle edit form. */ public function add_bundle_setting_form_submit($form, &$form_state, $bundle, $type_location) { // Some types do not support changing bundles, so we don't check if it's // not possible to change. if ($type_location) { $new_bundle = drupal_array_get_nested_value($form_state['values'], $type_location); } else { $new_bundle = $bundle; } // Check to see if the bundle has changed. If so we need to move stuff around. if ($bundle && $new_bundle != $bundle) { // Remove old settings. variable_del('panelizer_defaults_' . $this->entity_type . '_' . $bundle); $allowed_layouts = variable_get('panelizer_' . $this->entity_type . ':' . $bundle . '_allowed_layouts', NULL); if ($allowed_layouts) { variable_del('panelizer_' . $this->entity_type . ':' . $bundle . '_allowed_layouts'); variable_set('panelizer_' . $this->entity_type . ':' . $new_bundle . '_allowed_layouts', $allowed_layouts); } $default = variable_get('panelizer_' . $this->entity_type . ':' . $bundle . '_default', NULL); if ($default) { variable_del('panelizer_' . $this->entity_type . ':' . $bundle . '_default'); variable_set('panelizer_' . $this->entity_type . ':' . $new_bundle . '_default', $default); } // Load up all panelizer defaults for the old bundle and resave them // for the new bundle. $panelizer_defaults = $this->get_default_panelizer_objects($bundle); foreach ($panelizer_defaults as $panelizer) { list($entity_type, $old_bundle, $name) = explode(':', $panelizer->name); $panelizer->name = implode(':', array($entity_type, $new_bundle, $name)); if ($panelizer->view_mode != 'page_manager') { $panelizer->name .= ':' . $panelizer->view_mode; } $panelizer->panelizer_key = $new_bundle; // If there's a pnid this should change the name and retain the pnid. // If there is no pnid this will create a new one in the database // because exported panelizer defaults attached to a bundle will have // to be moved to the database in order to follow along and // then be re-exported. // @todo -- should we warn the user about this? ctools_export_crud_save('panelizer_defaults', $panelizer); } } variable_set('panelizer_defaults_' . $this->entity_type . '_' . $new_bundle, $form_state['values']['panelizer']); // Unset this so that the type save forms don't try to save it to variables. unset($form_state['values']['panelizer']); }
/** * Alter target id to fetch referenced values from. * * @param int &$target_id * Current target id as determined by * entityreference_autofill_field_attach_form(). * @param array &$form_state * The current $form_state array. * @param array $context * An associative array containing the following key-value pairs: * - field_name: The name of the reference field. * - field: Triggering field (The entity reference field) info array. * - field: Field info. * - instance: Instance info. * - form: Current form array. * - langcode: The current langcode. */ function hook_entityreference_autofill_target_id_alter(&$target_id, &$form_state, $context) { // Fetch value from form input array instead of values. if (og_is_group_audience_field($context['field_name'])) { $reference_field_parents = $form_state['triggering_element']['#parents']; $referenced_target_id = drupal_array_get_nested_value($form_state['input'], $reference_field_parents); } }
public static function entityTypeHasProperty($entity_type, array $parents) { if ($info = entity_get_info($entity_type)) { return drupal_array_get_nested_value($info, $parents); } }