Advertisement
Guest User

SS - Parent/Child GridField Relations

a guest
Mar 14th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.50 KB | None | 0 0
  1. <?php
  2.  
  3. class ClientProjectCategory extends DataObject {
  4.    
  5.     private static $db = array(
  6.             'Title'                         => 'Varchar(32)',
  7.             'SortOrder'                     => 'Int',
  8.             'URLSegment'                    => 'Varchar(32)',
  9.             'Description'                   => 'HTMLText'
  10.     );
  11.    
  12.     private static $has_one = array(
  13.             'ParentCategory'    => 'ClientProjectCategory'
  14.     );
  15.  
  16.     private static $default_sort = array(
  17.             'SortOrder',
  18.     );
  19.    
  20.     public function getCMSFields(){
  21.         $fields = parent::getCMSFields();
  22.         $fields->addFieldToTab('Root.Main', DropdownField::create('ParentCategoryID', 'Parent Category')
  23.             ->setSource($this->ClientCategoriesForDropdown()->map('ID', 'Title'))
  24.             ->setEmptyString(' -No Parent- '), 'Description');
  25.         $fields->addFieldToTab('Root.Main', GridField::create('ClientProjectCategory', 'SubCategories', $this->getAllChildren(@$this->ID), GridFieldConfig_RelationEditor::create()));
  26.         return $fields;
  27.     }
  28.  
  29.     public function getAllChildren( $currentCategoryID = null ){
  30.         if( $currentCategoryID == null ){
  31.             return ClientProjectCategory::get()->filter('ParentCategoryID', -1);
  32.         }
  33.         $resultCategories = new ArrayList();
  34.         $childrenCategories = ClientProjectCategory::get()->filter('ParentCategoryID', $currentCategoryID);
  35.         if( $childrenCategories->exists() ){
  36.             $resultCategories->merge($childrenCategories->toArray());
  37.             foreach( $childrenCategories as $childCategory ){
  38.                 $resultCategories->merge($this->getAllChildren($childCategory->ID));
  39.             }
  40.         } else {
  41.             return $childrenCategories;
  42.         }
  43.         return $resultCategories;
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement