summaryrefslogtreecommitdiff
path: root/modules/simpletest/tests/field_test.module
blob: 54ae3d405487482f428ed8bae2f5813245715fc9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
<?php
// $Id$

define('FIELD_TEST_ELEMENT_ID', 1);
define('FIELD_TEST_BUNDLE', 'test_bundle');

/**
 * Implement hook_permission().
 */
function field_test_permission() {
  $perms = array(
    'access field_test content' => array(
      'title' => t('Access field_test content'),
      'description' => t('View published field_test content.'),
    ),
    'administer field_test content' => array(
      'title' => t('Administer field_test content'),
      'description' => t('Manage field_test content'),
    ),
  );
  return $perms;
}

/**
 * Implement hook_menu().
 */
function field_test_menu() {
  $items = array();
  $bundles = field_info_bundles('test_entity');

  foreach ($bundles as $bundle_name => $bundle_info) {
    $bundle_url_str = str_replace('_', '-', $bundle_name);
    $items['test-entity/add/' . $bundle_url_str] = array(
      'title' => t('Add %bundle test_entity', array('%bundle' => $bundle_info['label'])),
      'page callback' => 'field_test_entity_add',
      'page arguments' => array(2),
      'access arguments' => array('administer field_test content'),
      'type' => MENU_NORMAL_ITEM,
    );
  }
  $items['test-entity/%field_test_entity/edit'] = array(
    'title' => 'Edit test entity',
    'page callback' => 'field_test_entity_edit',
    'page arguments' => array(1),
    'access arguments' => array('administer field_test content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}


/**
 *
 * 'Field attach' API.
 *
 */


/**
 * Define a test fieldable entity.
 */
function field_test_fieldable_info() {
  $bundles = variable_get('field_test_bundles', array('test_bundle' => array('label' => 'Test Bundle')));
  return array(
    'test_entity' => array(
      'name' => t('Test Entity'),
      'object keys' => array(
        'id' => 'ftid',
        'revision' => 'ftvid',
        'bundle' => 'fttype',
      ),
      'cacheable' => FALSE,
      'bundles' => $bundles,
    ),
    // This entity type doesn't get form handling for now...
    'test_cacheable_entity' => array(
      'name' => t('Test Entity, cacheable'),
      'object keys' => array(
        'id' => 'ftid',
        'revision' => 'ftvid',
        'bundle' => 'fttype',
      ),
      'cacheable' => TRUE,
      'bundles' => $bundles,
    ),
  );
}

/**
 * Implement hook_fieldable_info_alter().
 */
function field_test_fieldable_info_alter(&$info) {
  foreach (field_test_fieldable_info_translatable() as $obj_type => $translatable) {
    $info[$obj_type]['translation_handlers']['field_test'] = TRUE;
  }
}

/**
 * Create a new bundle for test_entity objects.
 *
 * @param $bundle_name
 *   The machine-readable name of the bundle.
 * @param $text
 *   The human-readable name of the bundle. If none is provided, the machine
 *   name will be used.
 */
function field_test_create_bundle($bundle_name, $text = NULL) {
  $bundles = variable_get('field_test_bundles', array('test_bundle' => array('label' => 'Test Bundle')));
  $bundles += array($bundle_name => array('label' => $text ? $text : $bundle_name));
  variable_set('field_test_bundles', $bundles);

  field_attach_create_bundle($bundle_name);
}

/**
 * Rename a bundle for test_entity objects.
 *
 * @param $bundle_old
 *   The machine-readable name of the bundle to rename.
 * @param $bundle_new
 *   The new machine-readable name of the bundle.
 */
function field_test_rename_bundle($bundle_old, $bundle_new) {
  $bundles = variable_get('field_test_bundles', array('test_bundle' => array('label' => 'Test Bundle')));
  $bundles[$bundle_new] = $bundles[$bundle_old];
  unset($bundles[$bundle_old]);
  variable_set('field_test_bundles', $bundles);

  field_attach_rename_bundle($bundle_old, $bundle_new);
}

/**
 * Delete a bundle for test_entity objects.
 *
 * @param $bundle_name
 *   The machine-readable name of the bundle to delete.
 */
function field_test_delete_bundle($bundle_name) {
  $bundles = variable_get('field_test_bundles', array('test_bundle' => array('label' => 'Test Bundle')));
  unset($bundles[$bundle_name]);
  variable_set('field_test_bundles', $bundles);

  field_attach_delete_bundle($bundle_name);
}

/**
 * Implement hook_field_build_modes().
 */
function field_test_field_build_modes($obj_type) {
  $modes = array();
  if ($obj_type == 'test_entity' || $obj_type == 'test_cacheable_entity') {
    $modes = array(
      'full' => t('Full node'),
      'teaser' => t('Teaser'),
    );
  }
  return $modes;
}

/**
 * Helper function to create a basic 'test entity' structure.
 *
 * TODO : do we stil need this now that we can actualy load and save test_entities ?
 */
function field_test_create_stub_entity($id = 1, $vid = 1, $bundle = FIELD_TEST_BUNDLE) {
  $entity = new stdClass();
  // Only set id and vid properties if they don't come as NULL (creation form).
  if (isset($id)) {
    $entity->ftid = $id;
  }
  if (isset($vid)) {
    $entity->ftvid = $vid;
  }
  $entity->fttype = $bundle;

  return $entity;
}

function field_test_entity_load($ftid, $ftvid = NULL) {
  // Load basic strucure.
  $query = db_select('test_entity', 'fte', array())
    ->fields('fte')
    ->condition('ftid', $ftid);
  if ($ftvid) {
    $query->condition('ftvid', $ftvid);
  }
  $entities = $query->execute()->fetchAllAssoc('ftid');

  // Attach fields.
  if ($ftvid) {
    field_attach_load_revision('test_entity', $entities);
  }
  else {
    field_attach_load('test_entity', $entities);
  }

  return $entities[$ftid];
}

function field_test_entity_save(&$entity) {
  field_attach_presave('test_entity', $entity);

  if (!isset($entity->is_new)) {
    $entity->is_new = empty($entity->ftid);
  }

  if (!$entity->is_new && !empty($entity->revision)) {
    $entity->old_ftvid = $entity->ftvid;
    unset($entity->ftvid);
  }

  $update_entity = TRUE;
  if ($entity->is_new) {
    drupal_write_record('test_entity', $entity);
    drupal_write_record('test_entity_revision', $entity);
    $op = 'insert';
  }
  else {
    drupal_write_record('test_entity', $entity, 'ftid');
    if (!empty($entity->revision)) {
      drupal_write_record('test_entity_revision', $entity);
    }
    else {
      drupal_write_record('test_entity_revision', $entity, 'ftvid');
      $update_entity = FALSE;
    }
    $op = 'update';
  }
  if ($update_entity) {
    db_update('test_entity')
      ->fields(array('ftvid' => $entity->ftvid))
      ->condition('ftid', $entity->ftid)
      ->execute();
  }

  // Save fields.
  $function = "field_attach_$op";
  $function('test_entity', $entity);
}

function field_test_entity_add($fttype) {
  $fttype = str_replace('-', '_', $fttype);
  $entity = (object)array('fttype' => $fttype);
  drupal_set_title(t('Create test_entity @bundle', array('@bundle' => $fttype)), PASS_THROUGH);
  return drupal_get_form('field_test_entity_form', $entity);
}

function field_test_entity_edit($entity) {
  drupal_set_title(t('test_entity @ftid revision @ftvid', array('@ftid' => $entity->ftid, '@ftvid' => $entity->ftvid)), PASS_THROUGH);
  return drupal_get_form('field_test_entity_form', $entity);
}

/**
 * Form to set the value of fields attached to our entity.
 */
function field_test_entity_form(&$form_state, $entity) {
  $form = array();

  if (isset($form_state['test_entity'])) {
    $entity = $form_state['test_entity'] + (array)$entity;
  }
  $entity = (object)$entity;

  foreach (array('ftid', 'ftvid', 'fttype') as $key) {
    $form[$key] = array(
      '#type' => 'value',
      '#value' => isset($entity->$key) ? $entity->$key : NULL,
    );
  }

  // Add field widgets.
  $form['#builder_function'] = 'field_test_entity_form_submit_builder';
  field_attach_form('test_entity', $entity, $form, $form_state);

  $form['revision'] = array(
    '#access' => user_access('administer field_test content'),
    '#type' => 'checkbox',
    '#title' => t('Create new revision'),
    '#default_value' => FALSE,
    '#weight' => 100,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#weight' => 101,
  );

  return $form;
}

/**
 * Validate handler for field_test_set_field_values().
 */
function field_test_entity_form_validate($form, &$form_state) {
  $entity = field_test_create_stub_entity($form_state['values']['ftid'], $form_state['values']['ftvid'], $form_state['values']['fttype']);
  field_attach_form_validate('test_entity', $entity, $form, $form_state);
}

/**
 * Submit handler for field_test_set_field_values().
 */
function field_test_entity_form_submit($form, &$form_state) {
  $entity = field_test_entity_form_submit_builder($form, $form_state);
  $insert = empty($entity->ftid);
  field_test_entity_save($entity);

  $message = $insert ? t('test_entity @id has been created.', array('@id' => $entity->ftid)) : t('test_entity @id has been updated.', array('@id' => $entity->ftid));
  drupal_set_message($message);

  if ($entity->ftid) {
    unset($form_state['rebuild']);
    $form_state['redirect'] = 'test-entity/' . $entity->ftid . '/edit';
  }
  else {
    // Error on save.
    drupal_set_message(t('The entity could not be saved.'), 'error');
  }

}

/**
 * Build a test_entity by processing submitted form values and prepare for a form rebuild.
 */
function field_test_entity_form_submit_builder($form, &$form_state) {
  $entity = field_test_create_stub_entity($form_state['values']['ftid'], $form_state['values']['ftvid'], $form_state['values']['fttype']);
  field_attach_submit('test_entity', $entity, $form, $form_state);

  $form_state['test_entity'] = (array)$entity;
  $form_state['rebuild'] = TRUE;

  return $entity;
}

/**
 *
 * 'Field type' API.
 *
 */

/**
 * Implement hook_field_info().
 *
 * This field provides a textfield which only accepts the value 1.
 */
function field_test_field_info() {
  return array(
    'test_field' => array(
      'label' => t('Test Field'),
      'settings' => array(
        'test_field_setting' => 'dummy test string',
      ),
      'instance_settings' => array(
        'test_instance_setting' => 'dummy test string',
        'test_hook_field_load' => FALSE,
      ),
      'default_widget' => 'test_field_widget',
      'default_formatter' => 'field_test_default',
    ),
  );
}

/**
 * Implement hook_field_schema().
 */
function field_test_field_schema($field) {
  return array(
    'columns' => array(
      'value' => array(
        'type' => 'int',
        'size' => 'tiny',
        'not null' => FALSE,
      ),
    ),
    'indexes' => array(
      'value' => array('value'),
    ),
  );
}

/**
 * Implement hook_field_load().
 */
function field_test_field_load($obj_type, $objects, $field, $instances, $langcode, &$items, $age) {
  foreach ($items as $id => $item) {
    // To keep the test non-intrusive, only act for instances with the
    // test_hook_field_load setting explicitly set to TRUE.
    if ($instances[$id]['settings']['test_hook_field_load']) {
      foreach ($item as $delta => $value) {
        // Don't add anything on empty values.
        if ($value) {
          $items[$id][$delta]['additional_key'] = 'additional_value';
        }
      }
    }
  }
}

/**
 * Implement hook_field_validate().
 *
 * Possible error codes:
 * - 'field_test_invalid': The value is invalid.
 */
function field_test_field_validate($obj_type, $object, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if ($item['value'] == -1) {
      $errors[$field['field_name']][$langcode][$delta][] = array(
        'error' => 'field_test_invalid',
        'message' => t('%name does not accept the value -1.', array('%name' => $instance['label'])),
      );
    }
  }
}

/**
 * Implement hook_field_sanitize().
 */
function field_test_field_sanitize($obj_type, $object, $field, $instance, $langcode, &$items) {
  foreach ($items as $delta => $item) {
    $value = check_plain($item['value']);
    $items[$delta]['safe'] = $value;
  }
}

/**
 * Implement hook_field_is_empty().
 */
function field_test_field_is_empty($item, $field) {
  return empty($item['value']);
}

/**
 * Implement hook_field_widget_info().
 *
 * Here we indicate that the field module will handle
 * the default value and multiple values for these widgets.
 *
 * Callbacks can be omitted if default handing is used.
 * They're included here just so this module can be used
 * as an example for custom modules that might do things
 * differently.
 */
function field_test_field_widget_info() {
  return array(
    'test_field_widget' => array(
      'label' => t('Test field'),
      'field types' => array('test_field'),
      'settings' => array('test_widget_setting' => 'dummy test string'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
    'test_field_widget_multiple' => array(
      'label' => t('Test field 1'),
      'field types' => array('test_field'),
      'settings' => array('test_widget_setting_multiple' => 'dummy test string'),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
        'default value' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
  );
}

/**
 * Implement hook_field_widget().
 *
 * Attach a single form element to the form. It will be built out and
 * validated in the callback(s) listed in hook_elements. We build it
 * out in the callbacks rather than here in hook_widget so it can be
 * plugged into any module that can provide it with valid
 * $field information.
 *
 * If there are multiple values for this field, the field module will
 * call this function as many times as needed.
 *
 * @param $form
 *   the entire form array, $form['#node'] holds node information
 * @param $form_state
 *   the form_state, $form_state['values'][$field['field_name']]
 *   holds the field's form values.
 * @param $field
 *   The field structure.
 * @param $instance
 *   the instance array
 * @param $items
 *   array of default values for this field
 * @param $delta
 *   the order of this item in the array of subelements (0, 1, 2, etc)
 *
 * @return
 *   the form item for a single element for this field
 */
function field_test_field_widget(&$form, &$form_state, $field, $instance, $items, $delta = 0) {
  $element = array(
    'value' => array(
      '#title' => $instance['label'],
      '#type' => 'textfield',
      '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : '',
      '#required' => $instance['required'],
    ),
  );
  return $element;
}

/**
 * Implement hook_field_widget_error().
 */
function field_test_field_widget_error($element, $error) {
  form_error($element['value'], $error['message']);
}

/**
 * Implement hook_field_formatter_info().
 */
function field_test_field_formatter_info() {
  return array(
    'field_test_default' => array(
      'label' => t('Default'),
      'field types' => array('test_field'),
      'settings' => array(
        'test_formatter_setting' => 'dummy test string',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_DEFAULT,
      ),
    ),
    'field_test_multiple' => array(
      'label' => t('Default'),
      'field types' => array('test_field'),
      'settings' => array(
        'test_formatter_setting_multiple' => 'dummy test string',
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
      ),
    ),
  );
}

/**
 * Implement hook_theme().
 */
function field_test_theme() {
  return array(
    'field_formatter_field_test_default' => array(
      'arguments' => array('element' => NULL),
    ),
    'field_formatter_field_test_multiple' => array(
      'arguments' => array('element' => NULL),
    ),
  );
}

/**
 * Theme function for 'field_test_default' formatter.
 */
function theme_field_formatter_field_test_default($element) {
  $value = $element['#item']['value'];
  $settings = $element['#settings'];

  return $settings['test_formatter_setting'] . '|' . $value;
}

/**
 * Theme function for 'field_test_multiple' formatter.
 */
function theme_field_formatter_field_test_multiple($element) {
  $settings = $element['#settings'];

  $items = array();
  foreach (element_children($element) as $key) {
    $items[$key] = $key .':'. $element[$key]['#item']['value'];
  }
  $output = implode('|', $items);
  return $settings['test_formatter_setting_multiple'] . '|' . $output;
}

/**
 * Sample function to test default value assignment.
 */
function field_test_default_value($obj_type, $object, $field, $instance) {
  return array(array('value' => 99));
}

/**
 * Generic op to test _field_invoke behavior.
 */
function field_test_field_test_op($obj_type, $object, $field, $instance, $langcode, &$items) {
  return array($langcode => md5(serialize(array($obj_type, $object, $field['field_name'], $langcode, $items))));
}

/**
 * Generic op to test _field_invoke_multiple behavior.
 */
function field_test_field_test_op_multiple($obj_type, $objects, $field, $instances, $langcode, &$items) {
  $result = array();
  foreach ($objects as $id => $object) {
    $result[$id] = array($langcode => md5(serialize(array($obj_type, $object, $field['field_name'], $langcode, $items[$id]))));
  }
  return $result;
}

/**
 * Implement hook_field_languages().
 */
function field_test_field_languages($obj_type, $field, &$languages) {
  if ($field['settings']['test_hook_in']) {
    // Add an unavailable language.
    $languages[] = 'xx';
    // Remove an available language.
    unset($languages[0]);
  }
}

/**
 * Helper function to enable entity translations.
 */
function field_test_fieldable_info_translatable($obj_type = NULL, $translatable = NULL) {
  $stored_value = &drupal_static(__FUNCTION__, array());
  if (isset($obj_type) && isset($translatable)) {
    $stored_value[$obj_type] = $translatable;
    _field_info_collate_types(TRUE);
  }
  return $stored_value;
}

/**
 * Store and retrieve keyed data for later verification by unit tests.
 *
 * This function is a simple in-memory key-value store with the
 * distinction that it stores all values for a given key instead of
 * just the most recently set value.  field_test module hooks call
 * this function to record their arguments, keyed by hook name. The
 * unit tests later call this function to verify that the correct
 * hooks were called and were passed the correct arguments.
 *
 * This function ignores all calls until the first time it is called
 * with $key of NULL. Each time it is called with $key of NULL, it
 * erases all previously stored data from its internal cache, but also
 * returns the previously stored data to the caller. A typical usage
 * scenario is:
 *
 * @code
 *   // calls to field_test_memorize() here are ignored
 *
 *   // turn on memorization
 *   field_test_memorize();
 *
 *   // call some Field API functions that invoke field_test hooks
 *   $field = field_create_field(...);
 *
 *   // retrieve and reset the memorized hook call data
 *   $mem = field_test_memorize();
 *
 *   // make sure hook_field_create_field() is invoked correctly
 *   assertEqual(count($mem['field_test_field_create_field']), 1);
 *   assertEqual($mem['field_test_field_create_field'][0], array($field));
 * @endcode
 *
 * @param $key
 *   The key under which to store to $value, or NULL as described above.
 * @param $value
 *   A value to store for $key.
 * @return
 *   An array mapping each $key to an array of each $value passed in
 *   for that key.
 */
function field_test_memorize($key = NULL, $value = NULL) {
  $memorize = &drupal_static(__FUNCTION__, NULL);

  if (is_null($key)) {
    $ret = $memorize;
    $memorize = array();
    return $ret;
  }
  if (is_array($memorize)) {
    $memorize[$key][] = $value;
  }
}

/**
 * Memorize calls to hook_field_create_field().
 */
function field_test_field_create_field($field) {
  $args = func_get_args();
  field_test_memorize(__FUNCTION__, $args);
}

/**
 * Memorize calls to hook_field_insert().
 */
function field_test_field_insert($obj_type, $object, $field, $instance, $items) {
  $args = func_get_args();
  field_test_memorize(__FUNCTION__, $args);
}

/**
 * Memorize calls to hook_field_update().
 */
function field_test_field_update($obj_type, $object, $field, $instance, $items) {
  $args = func_get_args();
  field_test_memorize(__FUNCTION__, $args);
}

/**
 * Memorize calls to hook_field_delete().
 */
function field_test_field_delete($obj_type, $object, $field, $instance, $items) {
  $args = func_get_args();
  field_test_memorize(__FUNCTION__, $args);
}