source: sipes/0.3-modules/cck_plan_fields/cck_plan_fields_combine_term.module @ 1e031fe

stable
Last change on this file since 1e031fe was 1e031fe, checked in by Sipes Apn <root@…>, 7 años ago

se realizo la correción en lo referente al nombre del campo

  • Propiedad mode establecida a 100755
File size: 19.1 KB
Línea 
1<?php
2  /**
3  * Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana
4  * @file cck_plan_fields_combine_term.module
5  * Drupal part Module to code ente planificador module
6  * Copyright 2017 Sistema Automatizado para la Planificación Estratégico-Situacional en la Administración Pública Venezolana (CENDITEL)
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  * @author Cenditel Merida - Phd. Juan Vizcarrondo
23  * @date 2017-03-24 // (a&#241;o-mes-dia)
24  * @version 0.2 // (0.2)
25  *
26  */
27
28/**
29* Implementation of hook_field_info().
30*/
31function cck_plan_fields_combine_term_field_info() {
32  return array(
33    'cck_plan_fields_combine_term' => array(
34      'label' => t('Combine term and num line field'),
35      'description' => t('Store items operative combine term data in the database.'),
36    ),
37  );
38}
39
40/**
41* Implementation of hook_field_settings().
42*/
43function cck_plan_fields_combine_term_field_settings($op, $field) {
44  switch ($op) {
45    case 'form':
46      $form = array();
47      $vocabularies = taxonomy_get_vocabularies();
48      $vocabulary_options = array();
49      foreach($vocabularies as $vocabulary) {
50        $vocabulary_options[$vocabulary->vid] = $vocabulary->name;
51      }
52      $form['vid'] = array(
53        '#type' => 'select',
54        '#title' => t('Taxonomy'),
55        '#default_value' => !empty($field['vid']) ? $field['vid'] : '',
56        '#options' => $vocabulary_options,
57      );
58      if (!empty($field['vid'])) {
59        $vid = $field['vid'];
60        //$terms = taxonomy_get_tree($vid);
61        $tree = taxonomy_get_tree($vid);
62        $options = array();
63        if ($tree) {
64          foreach ($tree as $term) {
65              $choice = new stdClass();
66              $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
67              $options[] = $choice;
68          }
69        }
70        $form['vtid'] = array(
71          '#type' => 'select',
72          '#default_value' => isset($field['vtid']) ? $field['vtid'] : array(),
73          '#options' => $options,
74          '#multiple' => TRUE,
75          );
76      }
77      $types = array(
78        'int' => t('Integer'),
79        'float' => t('Float'),
80      );
81      $form['cck_plan_fields_simple_type'] = array(
82        '#type' => 'select',
83        '#title' => t('Type'),
84        '#default_value' => !empty($field['cck_plan_fields_simple_type']) ? $field['cck_plan_fields_simple_type'] : 'int',
85        '#options' => $types,
86      );
87      $form['cck_plan_fields_simple_titulo_term'] = array(
88        '#type' => 'textfield',
89        '#title' => t('Titulo del Termino de la taxonomia'),
90        //'#required' => TRUE,
91        '#weight' => -9,
92        '#default_value' => !empty($field['cck_plan_fields_simple_titulo_term']) ? $field['cck_plan_fields_simple_titulo_term'] : t('Term'),
93      );
94
95      $form['cck_plan_fields_simple_titulo'] = array(
96        '#type' => 'textfield',
97        '#title' => t('Titulo del monto'),
98        //'#required' => TRUE,
99        '#weight' => -9,
100        '#default_value' => !empty($field['cck_plan_fields_simple_titulo']) ? $field['cck_plan_fields_simple_titulo'] : t('Monto'),
101      );
102      return $form;
103    case 'save':
104      $save_settings = array(
105        'vid',
106        'vtid',
107        'cck_plan_fields_simple_type',
108        'cck_plan_fields_simple_titulo_term',
109        'cck_plan_fields_simple_titulo',
110      );
111      return $save_settings;
112    case 'database columns':
113      $columns['tid'] = array(
114        'type' => 'int',
115        'not null' => FALSE,
116        'sortable' => TRUE,
117        'views' => TRUE,
118      );
119      $columns['value'] = array(
120        'type' => 'numeric',
121        'size' => 'normal',
122        'not null' => TRUE,
123        'default' => 0,
124        'precision' => 32,
125        'scale' => 0,
126      );
127      return $columns;
128    case 'views data':
129      $data = content_views_field_views_data($field);
130      $db_info = content_database_info($field);
131      $table_alias = content_views_tablename($field);
132      $titulo_term = !empty($field['cck_plan_fields_simple_titulo_term']) ? $field['cck_plan_fields_simple_titulo_term'] : t('Term');
133      $titulo_monto = !empty($field['cck_plan_fields_simple_titulo']) ? $field['cck_plan_fields_simple_titulo'] : t('Monto');
134      $ftypes = array(
135        'tid' => $titulo_term,
136        'value' => $titulo_monto,
137      );
138      foreach ($ftypes as $ftype => $label) {
139        $copy = $data[$table_alias][$field['field_name'] . $ftype];
140        $copy['title'] = t($label);
141        $copy['filter']['handler'] = 'content_handler_filter_many_to_one';
142        $copy['filter']['numeric'] = TRUE;
143        unset($copy['field'], $copy['argument'], $copy['sort']);
144        $data[$table_alias][$field['field_name'] . $ftype . '_many_to_one'] = $copy;
145        $data[$table_alias][$field['field_name'] . $ftype]['argument']['handler'] = 'content_handler_argument_many_to_one';
146        if ($ftype != 'description') {
147          $data[$table_alias][$field['field_name'] . $ftype]['argument']['numeric'] = TRUE;
148        }
149      }
150      return $data;
151  }
152}
153
154/**
155 * Implementation of hook_content_is_empty().
156 */
157function cck_plan_fields_combine_term_content_is_empty($item, $field) {
158  $flat = TRUE;
159  foreach (array_keys($field['columns']) as $ftype) {
160    if ($ftype != 'tid' && !empty($item[$ftype])) {
161      $flat = FALSE;
162    }
163  }
164  return $flat;
165}
166
167/**
168 * Implementation of hook_field_formatter_info().
169 */
170function cck_plan_fields_combine_term_field_formatter_info() {
171  $formatters = array(
172    'default' => array(
173      'label'  => t('Default'),
174      'multiple values' => CONTENT_HANDLE_CORE,
175      'field types'  => array('cck_plan_fields_combine_term'),
176    ),
177  );
178  return $formatters;
179}
180
181/**
182 * Implementation of hook_theme().
183 */
184function cck_plan_fields_combine_term_theme() {
185  return array(
186    // Shows address in the default view: Multilines
187    'cck_plan_fields_combine_term_formatter_default' => array(
188      'arguments' => array('element'),
189    ),
190    'cck_plan_fields_combine_term_table' => array(
191      'arguments' => array('form' => NULL),
192    ),
193  );
194}
195
196/**
197 * Proxy theme function for cck_plan_fields formatters.
198 */
199function theme_cck_plan_fields_combine_term_formatter_generic($element) {
200  $output = '';
201  $flag = explode('single_line_', $element['#formatter']);
202  $field_name = $element['#field_name'];
203  $type_name = $element['#type_name'];
204  $field = content_fields($field_name, $type_name);
205  $ftypes = array(
206    'tid' => $field['cck_plan_fields_simple_titulo_term'],
207    'value' => $field['cck_plan_fields_simple_titulo'],
208  );
209  if ($flag[1] == 'tid') {
210    $term = taxonomy_get_term($element['#item'][$flag[1]]);
211    // If this term's vocabulary supports localization.
212    if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
213      $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
214    }
215    $output = '<strong>'. $ftypes[$flag[1]] .': </strong>'. check_plain($term->name);
216  }
217  else {
218    $output = '<strong>'. $ftypes[$flag[1]] .': </strong>'. number_format($element['#item'][$flag[1]], 2, '.', ',');
219  }
220  return $output;
221}
222
223/**
224 * theme_cck_plan_fields_formatter_default().
225 * default formatter theme
226 */
227function theme_cck_plan_fields_combine_term_formatter_default($element) {
228  $field_name = $element['#field_name'];
229  $type_name = $element['#type_name'];
230  $field = content_fields($field_name, $type_name);
231  $output = '';
232  // If all fields are hidden, return ''
233  if (empty($element['#item']['tid'])) {
234    return $output;
235  }
236  $format_number = array(
237    'decimals' => variable_get('proyectos_operativos_number_decimals', 0),
238    'dec_point' => variable_get('proyectos_operativos_number_dec_point', ','),
239    'thousands_sep' => variable_get('proyectos_operativos_number_thousands_sep', '.'),
240  );
241
242  $headers = array();
243  $rows = array();
244  $row = array();
245  $total = 0;
246  // If this term's vocabulary supports localization.
247  $term = taxonomy_get_term($element['#item']['tid']);
248  if (module_exists('i18ntaxonomy') && i18ntaxonomy_vocabulary($term->vid) == I18N_TAXONOMY_LOCALIZE) {
249    $term->name = tt("taxonomy:term:$term->tid:name", $term->name);
250  }
251  $numero = number_format($element['#item']['value'], $format_number['decimals'], $format_number['dec_point'], $format_number['thousands_sep']);
252  return $numero . ' ' . $term->name;
253}
254
255/**
256 * Implementation of hook_widget_info().
257 */
258function cck_plan_fields_combine_term_widget_info() {
259  return array(
260    'cck_plan_fields_combine_term' => array(
261      'label'           => t('Items combine term Field'),
262      'field types'     => array('cck_plan_fields_combine_term'),
263      'multiple values' => CONTENT_HANDLE_CORE,
264      'callbacks'       => array('default value' => CONTENT_CALLBACK_DEFAULT),
265    ),
266  );
267}
268
269/**
270* Implementation of hook_widget_settings().
271*/
272function cck_plan_fields_combine_term_widget_settings($op, $widget) {
273  switch ($op) {
274    case 'form':
275      $form = array();
276      $form['min'] = array(
277        '#type' => 'textfield',
278        '#title' => t('Minimum'),
279        '#element_validate' => array('_element_validate_number'),
280        '#default_value' => is_numeric($widget['min']) ? $widget['min'] : '',
281      );
282      $form['max'] = array(
283        '#type' => 'textfield',
284        '#title' => t('Maximum'),
285        '#element_validate' => array('_element_validate_number'),
286        '#default_value' => is_numeric($widget['max']) ? $widget['max'] : '',
287      );
288      return $form;
289    break;
290    case 'save':
291      return array(
292        'min',
293        'max',
294      );
295    break;
296  }
297}
298
299/**
300* Implementation of theme_cck_plan_fields_combine_term_table().
301*/
302function theme_cck_plan_fields_combine_term_table($form = array()) {
303  $headers = array();
304  $rows = array();
305  $row = array();
306  $ftypes = array(
307    'value' => t('Cantidad'),
308    'tid' => t('Term'),
309  );
310  $backgrounds = array(
311    'tid' => 'blue',
312    'value' => 'black',
313  );
314  if (isset($form['#title']) && $form['#title']) {
315    $field = str_replace('_', '-', $form['#field_name']);
316    $output .= '<div id="edit-' . $field . '-0-value-wrapper" class="form-item"><label for="edit-' . $field . '-0-value">' . $form['#title'] . '</label>';
317  }
318  $output = '<div">';
319  foreach ($ftypes as $ftype => $label) {
320    if($ftype != 'tid') {
321      $output .= '<div style="float:left;margin-left:5px">' . drupal_render($form[$ftype]) . '</div>';
322    }
323    else {
324      $output .= '<div style="float:left;margin-left:5px">' . drupal_render($form[$ftype]) . '</div>';
325    }
326  }
327  $output .= drupal_render($form);
328  $output .= '</div>';
329  if (isset($form['#title']) && $form['#title']) {
330    $output .= '</div>';
331  }
332  return $output;
333}
334
335/**
336 * Implementation of hook_widget().
337 */
338function cck_plan_fields_combine_term_widget(&$form, &$form_state, $field, $items, $delta = 0) {
339  $field_name = $field['field_name'];
340  $element = array();
341  $ftypes = array(
342    'tid' => !empty($field['cck_plan_fields_simple_titulo_term']) ? $field['cck_plan_fields_simple_titulo_term'] : t('Term'),
343    'value' => !empty($field['cck_plan_fields_simple_titulo']) ? $field['cck_plan_fields_simple_titulo'] : t('Monto'),
344  );
345  $ftypes['total'] = !empty($field['cck_plan_fields_simple_titulo']) ? $field['cck_plan_fields_simple_titulo'] : t('Total');
346  $class = $field_name . '_' . $delta . '_field';
347  $vid = $field['vid'];
348  $tree = taxonomy_get_tree($vid);
349  $options = array();
350  if ($tree) {
351    foreach ($tree as $term) {
352      if (isset($field['vtid'][$term->tid])) {
353        $choice = new stdClass();
354        $choice->option = array($term->tid => str_repeat('-', $term->depth) . $term->name);
355        $options[] = $choice;
356      }
357    }
358  }
359  $element['tid'] = array(
360    '#type' => 'select',
361    '#default_value' => isset($items[$delta]['tid']) ? $items[$delta]['tid'] : NULL,
362    '#options' => $options,
363  );
364  if ($delta == 0) {
365    $element['tid']['#title'] = $ftypes['tid'];
366  }
367  for ($i = 0; $i < 1; $i++) {
368    $class1 = ' ' . $field_name . '_m' . $i . '_field' . ' ' . $field_name . '_dato_field';
369    $field_id = $i ? 'value_' . $i : 'value';
370    $field_id_form = $i ? 'value-' . $i : 'value';
371    $element[$field_id] = array(
372      '#type' => 'textfield',
373      '#default_value' => isset($items[$delta][$field_id]) && $items[$delta][$field_id] ? $items[$delta][$field_id] : 0,
374      '#size' => 15,
375      '#attributes' => array('class' => $class . $class1 . ' number', 'onchange' => "suma('$class');sumatexto('" . $field_name . '_dato_field' . "');sumatexto('" . $field_name . '_m' . $i . '_field' . "');"),
376    );
377    if ($delta == 0) {
378      $element[$field_id]['#title'] = $ftypes[$field_id];
379    }
380  }
381  $element['#theme'] = 'cck_plan_fields_combine_term_table';
382  if (empty($element['#element_validate'])) {
383    $element['#element_validate'] = array();
384  }
385  array_unshift($element['#element_validate'], 'cck_plan_fields_combine_term_validate');
386  $form_state['#field_info'][$element['#field_name']] = $form['#field_info'][$field_name];
387  // Used so that hook_field('validate') knows where to
388  // flag an error in deeply nested forms.
389  if (empty($form['#parents'])) {
390    $form['#parents'] = array();
391  }
392  $element['_error_element'] = array(
393    '#type' => 'value',
394    '#value' => implode('][', array_merge($form['#parents'], array('value'))),
395  );
396  return $element;
397}
398
399/**
400 * FAPI validation of an individual element.
401 */
402function cck_plan_fields_combine_term_validate($element, &$form_state) {
403  $field_name = $element['#field_name'];
404  $type_name = $element['#type_name'];
405  $field = content_fields($field_name, $type_name);
406  $min = is_numeric($field['widget']['min']);
407  $max = is_numeric($field['widget']['max']);
408  $cck_plan_fields_path = drupal_get_path('module', 'cck_plan_fields');
409  drupal_add_js($cck_plan_fields_path . '/js/cck_plan_fields.js');
410  $flag = FALSE;
411  foreach ($element['#columns'] as $ftype) {
412    if ($ftype != 'tid' && !empty($element[$ftype]['#value'])) {
413      $error_field = implode('][', $element['#parents']) .'][' . $ftype;
414      if (!is_numeric($element[$ftype]['#value'])) {
415        form_set_error($error_field, t('Amount should be a number in %field.', array('%field' => t($field['widget']['label']))));
416      }
417      elseif ($field['cck_plan_fields_simple_type'] == 'int') {
418        $start = $element[$ftype]['#value'];
419        $value = preg_replace('@[^-0-9]@', '', $start);
420        if ($start != $value) {
421          form_set_error($error_field, t('Only numbers are allowed in %field.', array('%number' => $field['widget']['min'], '%field' => t($field['widget']['label']))));
422        }
423      }
424      elseif ($min && $field['widget']['min'] > $element[$ftype]['#value']) {
425        form_set_error($error_field, t('Amount should be greater %number in %field.', array('%number' => $field['widget']['min'], '%field' => t($field['widget']['label']))));
426      }
427      elseif ($max && $field['widget']['max'] < $element[$ftype]['#value']) {
428        form_set_error($error_field, t('Amount should be litter %number in %field.', array('%number' => $field['widget']['max'], '%field' => t($field['widget']['label']))));
429      }
430      $flag = TRUE;
431    }
432  }
433  if (!$flag) {
434    return;
435  }
436  if ($element['#delta']) {
437    $current_taxonomy = $element['tid']['#value'];
438    for($i = 0; $i < $element['#delta']; $i++) {
439      if ($current_taxonomy == $form_state['values'][$field_name][$i]['tid']) {
440        $error_field = implode('][', $element['#parents']) .'][tid';
441        form_set_error($error_field, t('@type_term can not be repeat in %field.', array('%field' => t($field['widget']['label']), '@type_term' => $field['cck_plan_fields_simple_titulo_term'])));
442      }
443    }
444  }
445  $type_name = $element['#type_name'];
446  $field = content_fields($field_name, $type_name);
447  $field_key = $element['#columns'][0];
448}
449
450/**
451 * Implementation of hook_feeds_node_processor_targets_alter().
452 *
453 * @see FeedsNodeProcessor::getMappingTargets()
454 */
455function cck_plan_fields_combine_term_feeds_node_processor_targets_alter(&$targets, $content_type) {
456  $info = content_types($content_type);
457  $fields = array();
458  if (isset($info['fields']) && count($info['fields'])) {
459    foreach ($info['fields'] as $field_name => $field) {
460      if (in_array($field['type'], array('cck_plan_fields_field'))) {
461        $fields[$field_name] = isset($field['widget']['label']) ? $field['widget']['label'] : $field_name;
462      }
463    }
464  }
465  $ftypes = array(
466    'tid' => t('Term'),
467    'value' => t('Cantidad'),
468  );
469  foreach ($fields as $k => $name) {
470    foreach($ftypes as $id => $month) {
471      $targets[$k . ':' . $id] = array(
472        'name' => check_plain($name) . '(' . $month . ')',
473        'callback' => 'cck_plan_fields_combine_term_feeds_set_target',
474        'description' => t('The part @month_name of @name field of the node.', array('@name' => $name, '@month_name' => $month)),
475      );
476    }
477  }
478}
479
480/**
481 * Implementation of cck_plan_fields_combine_term_feeds_set_target().
482 * Target callback function in Feeds
483 */
484function cck_plan_fields_combine_term_feeds_set_target($node, $target, $value) {
485  $ftypes = array(
486    'tid' => t('Term'),
487    'value' => t('Cantidad'),
488  );
489  $field_default = array();
490  foreach($ftypes as $id => $month) {
491    $field_default[$id] = 0;
492  }
493  list($field_name, $sub_field) = explode(':', $target);
494  $field = isset($node->$field_name) ? $node->$field_name : $field_default;
495  // Handle multiple value fields.
496  $field = content_fields($field_name, $node->type);
497  if (is_array($value)) {
498    $i = 0;
499    foreach ($value as $v) {
500      if (!is_array($v) && !is_object($v)) {
501        if ($sub_field == 'tid') {
502          $terms_found = content_taxonomy_get_term_by_name_vid($v, $field['vid']);
503          if ($terms_found->tid) {
504            $field[$i][$sub_field] = $terms_found->tid;
505          }
506        }
507        elseif(isset($field[$i]['tid']) && $field[$i]['tid']) {
508          $field[$i][$sub_field] = $v;
509        }
510      }
511      $i++;
512    }
513  }
514  else {
515    if ($sub_field == 'tid') {
516      $terms_found = cck_plan_fields_combine_term_get_term_by_name_vid($value, $field['vid']);
517      if ($terms_found->tid) {
518        $field[$i][$sub_field] = $terms_found->tid;
519      }
520    }
521    elseif(isset($field[0]['tid']) && $field[0]['tid']) {
522      $field[$i][$sub_field] = $value;
523    }
524    $field[0][$sub_field] = $value;
525  }
526  $node->$field_name = $field;
527}
528
529/**
530 * Implementation of cck_plan_fields_combine_term_get_term_by_name_vid().
531 * Get term from name and vocabulary
532 */
533function cck_plan_fields_combine_term_get_term_by_name_vid($name, $vid) {
534  $db_result = db_query(db_rewrite_sql("SELECT t.tid, t.name FROM {term_data} t WHERE LOWER(t.name) = LOWER('%s') AND vid=%d", 't', 'tid'), trim($name), $vid);
535  $result = array();
536  $term = db_fetch_object($db_result);
537  if($term) {
538    return $term->tid;
539  }
540  return FALSE;
541}
Nota: Vea TracBrowser para ayuda de uso del navegador del repositorio.