/
ComplexTableField.php
executable file
·1079 lines (893 loc) · 31.2 KB
/
ComplexTableField.php
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Provides a tabuar list in your form with view, edit and add links to edit records
* with a "has-one"-relationship. Detail-views are shown in a greybox-iframe.
* Features pagination in the overview as well as the detail-views.
*
* CAUTION: You need to make sure that the original form-call to the main controller (e.g. EditForm())
* returns a form which includes this field even if no data is loaded,
* to provide a "starting point" for action_callfieldmethod and ReferencedField.
*
* All URL data sent to and from ComplexTableField is encapsulated in $_REQUEST['ctf']
* to avoid side-effects with the main controller.
*
* Example-URL for a "DetailForm"-call explained:
* "/admin/family/?executeForm=EditForm&action_callfieldmethod&fieldName=Individual&childID=7&methodName=edit"
* - executeForm Name of the form on the main rendering page (e.g. "FamilyAdmin")
* - action_callfieldmethod Trigger to call a method of a single field in "EditForm" instead of rendering the whole thing
* - fieldName Name of the targeted formField
* - methodName Method on the formfield (e.g. "ComplexTableField")
* - childID Identifier of the database-record (the targeted table is determined by the $sourceClass parameter)
*
* @todo Find a less fragile solution for accessing this field through the main controller and ReferencedField, e.g.
* build a seperate CTF-instance (doesn't necessarly have to be connected to the original by ReferencedField)
* @todo Control width/height of popup by constructor (hardcoded at the moment)
* @todo Integrate search from MemberTableField.php
* @todo Less performance-hungry implementation of detail-view paging (don't return all items on a single view)
* @todo Use automatic has-many and many-many functions to return a ComponentSet rather than building the join manually
* @package forms
* @subpackage fields-relational
*/
class ComplexTableField extends TableListField {
/**
* Determines the fields of the detail pop-up form. It can take many forms:
* - A FieldSet object: Use that field set directly.
* - A method name, eg, 'getCMSFields': Call that method on the child object to get the fields.
*/
protected $addTitle;
protected $detailFormFields;
protected $viewAction, $sourceJoin, $sourceItems;
/**
* @var Controller
*/
protected $controller;
/**
* @var string Classname of the parent-relation to correctly link new records.
*/
public $parentClass;
/**
* @var string Database column name for the used relation (e.g. FamilyID
* if one Family has_many Individuals).
*/
protected $parentIdName;
/**
* @var array Influence output without having to subclass the template.
*/
protected $permissions = array(
"add",
"edit",
"show",
"delete",
//"export",
);
/**
* Template for main rendering
*
* @var string
*/
protected $template = "ComplexTableField";
/**
* Template for popup (form rendering)
*
* @var string
*/
public $templatePopup = "ComplexTableField_popup";
/**
* Classname for each row/item
*
* @var string
*/
public $itemClass = 'ComplexTableField_Item';
/**
* Classname for the popup form
*
* @var string
*/
public $popupClass = 'ComplexTableField_Popup';
/**
* @var boolean Trigger pagination (defaults to true for ComplexTableField)
*/
protected $showPagination = true;
/**
* @var string Caption the popup will show (defaults to the selected action).
* This is set by javascript and used by greybox.
*/
protected $popupCaption = null;
/**
* @var $detailFormValidator Validator
*/
protected $detailFormValidator = null;
/**
* Automatically detect a has-one relationship
* in the popup (=child-class) and save the relation ID.
*
* @var boolean
*/
protected $relationAutoSetting = true;
/**
* Default size for the popup box
*/
protected $popupWidth = 560;
protected $popupHeight = 390;
public $defaultAction = 'show';
public $actions = array(
'show' => array(
'label' => 'Show',
'icon' => 'cms/images/show.png',
'icon_disabled' => 'cms/images/show_disabled.png',
'class' => 'popuplink showlink',
),
'edit' => array(
'label' => 'Edit',
'icon' => 'cms/images/edit.gif',
'icon_disabled' => 'cms/images/edit_disabled.gif',
'class' => 'popuplink editlink',
),
'delete' => array(
'label' => 'Delete',
'icon' => 'cms/images/delete.gif',
'icon_disabled' => 'cms/images/delete_disabled.gif',
'class' => 'popuplink deletelink',
),
);
static $url_handlers = array(
'item/$ID' => 'handleItem',
'$Action!' => '$Action',
);
function handleItem($request) {
return new ComplexTableField_ItemRequest($this, $request->param('ID'));
}
function getViewer() {
return new SSViewer($this->template);
}
function setPopupSize($width, $height) {
$width = (int)$width;
$height = (int)$height;
if($width < 0 || $height < 0) {
user_error("setPopupSize expects non-negative arguments.", E_USER_WARNING);
return;
}
$this->popupWidth = $width;
$this->popupHeight = $height;
}
function PopupWidth() {
return $this->popupWidth;
}
function PopupHeight() {
return $this->popupHeight;
}
/**
* See class comments
*
* @param ContentController $controller
* @param string $name
* @param string $sourceClass
* @param array $fieldList
* @param FieldSet $detailFormFields
* @param string $sourceFilter
* @param string $sourceSort
* @param string $sourceJoin
*/
function __construct($controller, $name, $sourceClass, $fieldList = null, $detailFormFields = null, $sourceFilter = "", $sourceSort = "", $sourceJoin = "") {
$this->detailFormFields = $detailFormFields;
$this->controller = $controller;
$this->pageSize = 10;
parent::__construct($name, $sourceClass, $fieldList, $sourceFilter, $sourceSort, $sourceJoin);
}
/**
* Return the record filter for this table.
* It will automatically add a relation filter if relationAutoSetting is true, and it can determine an appropriate
* filter.
*/
function sourceFilter() {
$sourceFilter = parent::sourceFilter();
if($this->relationAutoSetting
&& $this->getParentClass()
&& ($filterKey = $this->getParentIdName($this->getParentClass(), $this->sourceClass()))
&& ($filterValue = $this->sourceID()) ) {
$newFilter = "\"$filterKey\" = '" . Convert::raw2sql($filterValue) . "'";
if($sourceFilter && is_array($sourceFilter)) {
// Note that the brackets below are taken into account when building this
$sourceFilter = implode(") AND (", $sourceFilter);
}
$sourceFilter = $sourceFilter ? "($sourceFilter) AND ($newFilter)" : $newFilter;
}
return $sourceFilter;
}
function isComposite() {
return false;
}
/**
* @return String
*/
function FieldHolder() {
Requirements::javascript(THIRDPARTY_DIR . "/greybox/AmiJS.js");
Requirements::javascript(THIRDPARTY_DIR . "/greybox/greybox.js");
Requirements::add_i18n_javascript(SAPPHIRE_DIR . '/javascript/lang');
Requirements::javascript(SAPPHIRE_DIR . '/javascript/TableListField.js');
Requirements::javascript(SAPPHIRE_DIR . "/javascript/ComplexTableField.js");
Requirements::css(THIRDPARTY_DIR . "/greybox/greybox.css");
Requirements::css(SAPPHIRE_DIR . "/css/TableListField.css");
Requirements::css(SAPPHIRE_DIR . "/css/ComplexTableField.css");
// set caption if required
if($this->popupCaption) {
$id = $this->id();
if(Director::is_ajax()) {
$js = <<<JS
$('$id').GB_Caption = '$this->popupCaption';
JS;
FormResponse::add($js);
} else {
$js = <<<JS
Event.observe(window, 'load', function() { \$('$id').GB_Caption = '$this->popupCaption'; });
JS;
Requirements::customScript($js);
}
}
// compute sourceItems here instead of Items() to ensure that
// pagination and filters are respected on template accessors
$this->sourceItems();
return $this->renderWith($this->template);
}
function sourceClass() {
return $this->sourceClass;
}
/**
* @return DataObjectSet
*/
function Items() {
$this->sourceItems = $this->sourceItems();
if(!$this->sourceItems) {
return null;
}
$pageStart = (isset($_REQUEST['ctf'][$this->Name()]['start']) && is_numeric($_REQUEST['ctf'][$this->Name()]['start'])) ? $_REQUEST['ctf'][$this->Name()]['start'] : 0;
$this->sourceItems->setPageLimits($pageStart, $this->pageSize, $this->totalCount);
$output = new DataObjectSet();
foreach($this->sourceItems as $pageIndex=>$item) {
$output->push(Object::create($this->itemClass,$item, $this, $pageStart+$pageIndex));
}
return $output;
}
/**
* Sets the popup-title by javascript. Make sure to use FormResponse in ajax-requests,
* otherwise the title-change will only take effect on items existing during page-load.
*
* @param $caption String
*/
function setPopupCaption($caption) {
$this->popupCaption = Convert::raw2js($caption);
}
/**
* @param $validator Validator
*/
function setDetailFormValidator( Validator $validator ) {
$this->detailFormValidator = $validator;
}
function setAddTitle($addTitle) {
if(is_string($addTitle))
$this->addTitle = $addTitle;
}
function Title() {
return $this->addTitle ? $this->addTitle : parent::Title();
}
/**
* Calculates the number of columns needed for colspans
* used in template
*
* @return Int
*/
function ItemCount() {
return count($this->fieldList);
}
/**
* Used to toggle paging (makes no sense when adding a record)
*
* @return Boolean
*/
function IsAddMode() {
return ($this->methodName == "add" || $this->request->param('Action') == 'AddForm');
}
function sourceID() {
$idField = $this->form->dataFieldByName('ID');
// disabled as it conflicts with scaffolded formfields, and not strictly necessary
// if(!$idField) user_error("ComplexTableField needs a formfield named 'ID' to be present", E_USER_ERROR);
// because action_callfieldmethod never actually loads data into the form,
// we can't rely on $idField being populated, and fall back to the request-params.
// this is a workaround for a bug where each subsequent popup-call didn't have ID
// of the parent set, and so didn't properly save the relation
return ($idField) ? $idField->Value() : (isset($_REQUEST['ctf']['ID']) ? $_REQUEST['ctf']['ID'] : null);
}
function AddLink() {
return $this->Link() . '/add';
}
/**
* @return FieldSet
*/
function createFieldSet() {
$fieldset = new FieldSet();
foreach($this->fieldTypes as $key => $fieldType){
$fieldset->push(new $fieldType($key));
}
return $fieldset;
}
function setController($controller) {
$this->controller = $controller;
}
/**
* Determines on which relation-class the DetailForm is saved
* by looking at the surrounding form-record.
*
* @return String
*/
function getParentClass() {
if($this->parentClass === false) {
// purposely set parent-relation to false
return false;
} elseif(!empty($this->parentClass)) {
return $this->parentClass;
} elseif($this->form && $this->form->getRecord()) {
return $this->form->getRecord()->ClassName;
}
}
/**
* (Optional) Setter for a correct parent-relation-class.
* Defaults to the record loaded into the surrounding form as a fallback.
* Caution: Please use the classname, not the actual column-name in the database.
*
* @param $className string
*/
function setParentClass($className) {
$this->parentClass = $className;
}
/**
* Returns the db-fieldname of the currently used has_one-relationship.
*/
function getParentIdName($parentClass, $childClass) {
return $this->getParentIdNameRelation($childClass, $parentClass, 'has_one');
}
/**
* Manually overwrites the parent-ID relations.
* @see setParentClass()
*
* @param String $str Example: FamilyID (when one Individual has_one Family)
*/
function setParentIdName($str) {
$this->parentIdName = $str;
}
/**
* Returns the db-fieldname of the currently used relationship.
* Note: constructed resolve ambiguous cases in the same manner as
* DataObject::getComponentJoinField()
*/
function getParentIdNameRelation($parentClass, $childClass, $relation) {
if($this->parentIdName) return $this->parentIdName;
$relations = array_flip(singleton($parentClass)->$relation());
$classes = array_reverse(ClassInfo::ancestry($childClass));
foreach($classes as $class) {
if(isset($relations[$class])) return $relations[$class] . 'ID';
}
return false;
}
function setTemplatePopup($template) {
$this->templatePopup = $template;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Return the object-specific fields for the given record, to be shown in the detail pop-up
*
* This won't include all the CTF-specific 'plumbing; this method is called by self::getFieldsFor()
* and the result is then processed further to get the actual FieldSet for the form.
*
* The default implementation of this processes the value of $this->detailFormFields; consequently, if you want to
* set the value of the fields to something that $this->detailFormFields doesn't allow, you can do so by overloading
* this method.
*/
function getCustomFieldsFor($childData) {
if($this->detailFormFields instanceof FieldSet) {
return $this->detailFormFields;
}
$fieldsMethod = $this->detailFormFields;
if(!is_string($fieldsMethod)) {
$this->detailFormFields = 'getCMSFields';
$fieldsMethod = 'getCMSFields';
}
if(!$childData->hasMethod($fieldsMethod)) {
$fieldsMethod = 'getCMSFields';
}
return $childData->$fieldsMethod();
}
function getFieldsFor($childData) {
// See if our parent class has any many_many relations by this source class
if($this->getParentClass()) {
if($this->sourceID()) {
$parentClass = DataObject::get_by_id($this->getParentClass(), $this->sourceID());
} else {
$parentClass = singleton($this->getParentClass());
}
$manyManyRelations = $parentClass->many_many();
$manyManyRelationName = null;
$manyManyComponentSet = null;
$hasManyRelations = $parentClass->has_many();
$hasManyRelationName = null;
$hasManyComponentSet = null;
if($manyManyRelations) foreach($manyManyRelations as $relation => $class) {
if($class == $this->sourceClass()) {
$manyManyRelationName = $relation;
}
}
if($hasManyRelations) foreach($hasManyRelations as $relation => $class) {
if($class == $this->sourceClass()) {
$hasManyRelationName = $relation;
}
}
}
// Add the relation value to related records
if(!$childData->ID && $this->getParentClass()) {
// make sure the relation-link is existing, even if we just add the sourceClass and didn't save it
$parentIDName = $this->getParentIdName($this->getParentClass(), $this->sourceClass());
$childData->$parentIDName = $this->sourceID();
}
$detailFields = $this->getCustomFieldsFor($childData);
if($this->getParentClass() && $hasManyRelationName && $childData->ID) {
$hasManyComponentSet = $parentClass->getComponents($hasManyRelationName);
}
// the ID field confuses the Controller-logic in finding the right view for ReferencedField
$detailFields->removeByName('ID');
// only add childID if we're not adding a record
if($childData->ID) {
$detailFields->push(new HiddenField('ctf[childID]', '', $childData->ID));
}
// add a namespaced ID instead thats "converted" by saveComplexTableField()
$detailFields->push(new HiddenField('ctf[ClassName]', '', $this->sourceClass()));
if($this->getParentClass()) {
$detailFields->push(new HiddenField('ctf[parentClass]', '', $this->getParentClass()));
if($manyManyRelationName && $this->relationAutoSetting) {
$detailFields->push(new HiddenField('ctf[manyManyRelation]', '', $manyManyRelationName));
}
if($hasManyRelationName && $this->relationAutoSetting) {
$detailFields->push(new HiddenField('ctf[hasManyRelation]', '', $hasManyRelationName));
}
if($manyManyRelationName || $hasManyRelationName) {
$detailFields->push(new HiddenField('ctf[sourceID]', '', $this->sourceID()));
}
$parentIdName = $this->getParentIdName($this->getParentClass(), $this->sourceClass());
if($parentIdName) {
if($this->relationAutoSetting) {
// Hack for model admin: model admin will have included a dropdown for the relation itself
$detailFields->removeByName($parentIdName);
$detailFields->push(new HiddenField($parentIdName, '', $this->sourceID()));
}
}
}
return $detailFields;
}
function getValidatorFor($childData) {
// if no custom validator is set, and there's on present on the object (e.g. Member), use it
if(!isset($this->detailFormValidator) && $childData->hasMethod('getValidator')) {
$this->detailFormValidator = $childData->getValidator();
}
return $this->detailFormValidator;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
function add() {
if(!$this->can('add')) return;
return $this->customise(array(
'DetailForm' => $this->AddForm(),
))->renderWith($this->templatePopup);
}
function AddForm($childID = null) {
$className = $this->sourceClass();
$childData = new $className();
$fields = $this->getFieldsFor($childData);
$validator = $this->getValidatorFor($childData);
$form = Object::create(
$this->popupClass,
$this,
'AddForm',
$fields,
$validator,
false,
$childData
);
return $form;
}
/**
* By default, a ComplexTableField will assume that the field name is the name of a has-many relation on the object being
* edited. It will identify the foreign key in the object being listed, and filter on that column, as well as auto-setting
* that column for newly created records.
*
* Calling $this->setRelationAutoSetting(false) will disable this functionality.
*
* @param boolean $value Should the relation auto-setting functionality be enabled?
*/
function setRelationAutoSetting($value) {
$this->relationAutoSetting = $value;
}
/**
* Use the URL-Parameter "action_saveComplexTableField"
* to provide a clue to the main controller if the main form has to be rendered,
* even if there is no action relevant for the main controller (to provide the instance of ComplexTableField
* which in turn saves the record.
*
* This is for adding new item records. {@link ComplexTableField_ItemRequest::saveComplexTableField()}
*
* @see Form::ReferencedField
*/
function saveComplexTableField($data, $form, $params) {
$className = $this->sourceClass();
$childData = new $className();
$form->saveInto($childData);
try {
$childData->write();
} catch(ValidationException $e) {
$form->sessionMessage($e->getResult()->message(), 'bad');
return Director::redirectBack();
}
// Save the many many relationship if it's available
if(isset($data['ctf']['manyManyRelation'])) {
$parentRecord = DataObject::get_by_id($data['ctf']['parentClass'], (int) $data['ctf']['sourceID']);
$relationName = $data['ctf']['manyManyRelation'];
$componentSet = $parentRecord->getManyManyComponents($relationName);
$componentSet->add($childData);
}
if(isset($data['ctf']['hasManyRelation'])) {
$parentRecord = DataObject::get_by_id($data['ctf']['parentClass'], (int) $data['ctf']['sourceID']);
$relationName = $data['ctf']['hasManyRelation'];
$componentSet = $parentRecord->getComponents($relationName);
$componentSet->add($childData);
}
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
$closeLink = sprintf(
'<small><a href="%s" onclick="javascript:window.top.GB_hide(); return false;">(%s)</a></small>',
$referrer,
_t('ComplexTableField.CLOSEPOPUP', 'Close Popup')
);
$message = sprintf(
_t('ComplexTableField.SUCCESSADD', 'Added %s %s %s'),
$childData->singular_name(),
'<a href="' . $this->Link() . '/item/' . $childData->ID . '/edit">' . $childData->Title . '</a>',
$closeLink
);
$form->sessionMessage($message, 'good');
Director::redirectBack();
}
}
/**
* @todo Tie this into ComplexTableField_Item better.
*/
class ComplexTableField_ItemRequest extends RequestHandler {
protected $ctf;
protected $itemID;
protected $methodName;
static $url_handlers = array(
'$Action!' => '$Action',
'' => 'index',
);
function Link($action = null) {
return Controller::join_links($this->ctf->Link(), '/item/', $this->itemID, $action);
}
function __construct($ctf, $itemID) {
$this->ctf = $ctf;
$this->itemID = $itemID;
parent::__construct();
}
function index() {
return $this->show();
}
/**
* Just a hook, processed in {DetailForm()}
*
* @return String
*/
function show() {
if($this->ctf->Can('show') !== true) {
return false;
}
$this->methodName = "show";
echo $this->renderWith($this->ctf->templatePopup);
}
/**
* Returns a 1-element data object set that can be used for pagination.
*/
/* this doesn't actually work :-(
function Paginator() {
$paginatingSet = new DataObjectSet(array($this->dataObj()));
$start = isset($_REQUEST['ctf']['start']) ? $_REQUEST['ctf']['start'] : 0;
$paginatingSet->setPageLimits($start, 1, $this->ctf->TotalCount());
return $paginatingSet;
}
*/
/**
* Just a hook, processed in {DetailForm()}
*
* @return String
*/
function edit() {
if($this->ctf->Can('edit') !== true) {
return false;
}
$this->methodName = "edit";
echo $this->renderWith($this->ctf->templatePopup);
}
function delete() {
if($this->ctf->Can('delete') !== true) {
return false;
}
$this->dataObj()->delete();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Return the data object being manipulated
*/
function dataObj() {
// used to discover fields if requested and for population of field
if(is_numeric($this->itemID)) {
// we have to use the basedataclass, otherwise we might exclude other subclasses
return DataObject::get_by_id(ClassInfo::baseDataClass(Object::getCustomClass($this->ctf->sourceClass())), $this->itemID);
}
}
/**
* Renders view, edit and add, depending on the given information.
* The form needs several parameters to function independently of its "parent-form", some derived from the context into a hidden-field,
* some derived from the parent context (which is not accessible here) and delivered by GET:
* ID, Identifier of the currently edited record (only if record is loaded).
* <parentIDName>, Link back to the correct parent record (e.g. "parentID").
* parentClass, Link back to correct container-class (the parent-record might have many 'has-one'-relationships)
* CAUTION: "ID" in the DetailForm would be the "childID" in the overview table.
*
* @param int $childID
*/
function DetailForm($childID = null) {
$childData = $this->dataObj();
$fields = $this->ctf->getFieldsFor($childData);
$validator = $this->ctf->getValidatorFor($childData);
$readonly = ($this->methodName == "show");
$form = Object::create(
$this->ctf->popupClass,
$this, "DetailForm",
$fields, $validator, $readonly, $childData);
$form->loadDataFrom($childData);
if ($readonly) $form->makeReadonly();
return $form;
}
/**
* Use the URL-Parameter "action_saveComplexTableField"
* to provide a clue to the main controller if the main form has to be rendered,
* even if there is no action relevant for the main controller (to provide the instance of ComplexTableField
* which in turn saves the record.
*
* This is for editing existing item records. {@link ComplexTableField::saveComplexTableField()}
*
* @see Form::ReferencedField
*/
function saveComplexTableField($data, $form, $request) {
$dataObject = $this->dataObj();
$form->saveInto($dataObject);
try {
$dataObject->write();
} catch(ValidationException $e) {
$form->sessionMessage($e->getResult()->message(), 'bad');
return Director::redirectBack();
}
// Save the many many relationship if it's available
if(isset($data['ctf']['manyManyRelation'])) {
$parentRecord = DataObject::get_by_id($data['ctf']['parentClass'], (int) $data['ctf']['sourceID']);
$relationName = $data['ctf']['manyManyRelation'];
$componentSet = $parentRecord->getManyManyComponents($relationName);
$componentSet->add($dataObject);
}
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
$closeLink = sprintf(
'<small><a href="' . str_replace('%', '%%', $referrer) . '" onclick="javascript:window.top.GB_hide(); return false;">(%s)</a></small>',
_t('ComplexTableField.CLOSEPOPUP', 'Close Popup')
);
$message = sprintf(
_t('ComplexTableField.SUCCESSEDIT', 'Saved %s %s %s'),
$dataObject->singular_name(),
'<a href="' . $this->Link() . '">"' . $dataObject->Title . '"</a>',
$closeLink
);
$form->sessionMessage($message, 'good');
Director::redirectBack();
}
function PopupCurrentItem() {
return $_REQUEST['ctf']['start']+1;
}
function PopupFirstLink() {
$this->ctf->LinkToItem();
if(!isset($_REQUEST['ctf']['start']) || !is_numeric($_REQUEST['ctf']['start']) || $_REQUEST['ctf']['start'] == 0) {
return null;
}
$start = 0;
return Controller::join_links($this->Link(), "$this->methodName?ctf[start]={$start}");
}
function PopupLastLink() {
if(!isset($_REQUEST['ctf']['start']) || !is_numeric($_REQUEST['ctf']['start']) || $_REQUEST['ctf']['start'] == $this->totalCount-1) {
return null;
}
$start = $this->totalCount - 1;
return Controller::join_links($this->Link(), "$this->methodName?ctf[start]={$start}");
}
function PopupNextLink() {
if(!isset($_REQUEST['ctf']['start']) || !is_numeric($_REQUEST['ctf']['start']) || $_REQUEST['ctf']['start'] == $this->totalCount-1) {
return null;
}
$start = $_REQUEST['ctf']['start'] + 1;
return Controller::join_links($this->Link(), "$this->methodName?ctf[start]={$start}");
}
function PopupPrevLink() {
if(!isset($_REQUEST['ctf']['start']) || !is_numeric($_REQUEST['ctf']['start']) || $_REQUEST['ctf']['start'] == 0) {
return null;
}
$start = $_REQUEST['ctf']['start'] - 1;
return Controller::join_links($this->Link(), "$this->methodName?ctf[start]={$start}");
}
/**
* Method handles pagination in asset popup.
*
* @return Object DataObjectSet
*/
function Pagination() {
$this->pageSize = 9;
$currentItem = $this->PopupCurrentItem();
$result = new DataObjectSet();
if($currentItem < 6) {
$offset = 1;
} elseif($this->totalCount - $currentItem <= 4) {
$offset = $currentItem - (10 - ($this->totalCount - $currentItem));
$offset = $offset <= 0 ? 1 : $offset;
} else {
$offset = $currentItem - 5;
}
for($i = $offset;$i <= $offset + $this->pageSize && $i <= $this->totalCount;$i++) {
$start = $i - 1;
$links['link'] = Controller::join_links($this->Link() . "$this->methodName?ctf[start]={$start}");
$links['number'] = $i;
$links['active'] = $i == $currentItem ? false : true;
$result->push(new ArrayData($links));
}
return $result;
}
function ShowPagination() {
return false;
}
/**
* #################################
* Utility
* #################################
*/
/**
* Get part of class ancestry (even if popup is not subclassed it might be styled differently in css)
*/
function PopupClasses() {
global $_ALL_CLASSES;
$items = array();
$parents = isset($_ALL_CLASSES['parents'][$this->class]) ? $_ALL_CLASSES['parents'][$this->class] : null;
if($parents) {
foreach($parents as $parent) {
if(!in_array($parent, $_ALL_CLASSES['parents']['TableListField'])) {
$items[] = $parent . '_Popup';
}
}
}
$items[] = $this->class . '_Popup';
return implode(' ', $items);
}
/**
* Returns the db-fieldname of the currently used has_one-relationship.
*/
function getParentIdName($parentClass, $childClass) {
return $this->getParentIdNameRelation($childClass, $parentClass, 'has_one');
}
/**
* Manually overwrites the parent-ID relations.
* @see setParentClass()
*
* @param String $str Example: FamilyID (when one Individual has_one Family)
*/
function setParentIdName($str) {
$this->parentIdName = $str;
}
/**
* Returns the db-fieldname of the currently used relationship.
*/
function getParentIdNameRelation($parentClass, $childClass, $relation) {
if($this->parentIdName) return $this->parentIdName;
$relations = singleton($parentClass)->$relation();
$classes = ClassInfo::ancestry($childClass);
if($relations) {
foreach($relations as $k => $v) {
if(array_key_exists($v, $classes)) return $k . 'ID';
}
}
return false;
}
function setTemplatePopup($template) {
$this->templatePopup = $template;
}
}
/**
* Single row of a {@link ComplexTableField}.
* @package forms
* @subpackage fields-relational
*/
class ComplexTableField_Item extends TableListField_Item {
/**
* Needed to transfer pagination-status from overview.
*/
protected $start;
function __construct(DataObject $item, ComplexTableField $parent, $start) {
$this->start = $start;
parent::__construct($item, $parent);
}
function Link($action = null) {
return Controller::join_links($this->parent->Link(), '/item/', $this->item->ID, $action);
}
function EditLink() {
return $this->Link() . "/edit";
}