Version: current

      1 <?php
      2
      3 /**
      4  * Редактор товаов вне дерева страниц сайта
      5  * Если товаров много искать и редакировать в дереве их неудобно...
      6  *
      7  *
      8  * @package Catalog
      9  * @author menedem, dvp
     10  */
     11 class CatalogAdmin extends ModelAdmin {
     12
     13     public static $managed_models = array(
     14         'Product',
     15     );
     16
     17     static $url_segment = 'catalog';
     18     static $url_rule = '/$Action';
     19     static $menu_title = 'Catalog';
     20     public static $allowed_actions = array('edit', 'delete');
     21
     22     public static $collection_controller_class = "CatalogAdmin_CollectionController";
     23     public static $record_controller_class = "CatalogAdmin_RecordController";
     24
     25     protected $resultsTableClassName = 'TableField';
     26
     27     // поля для показа в таблице (array('НазваниеПоля' => 'ТипПоля'))
     28     // для чекбоксов, которые нужно менять, тип CheckboxField, для остальных - ReadonlyField
     29     protected static $table_fields = array('SKU' => 'ReadonlyField', 'Title' => 'ReadonlyField', 'BasePrice' => 'ReadonlyField', 'CostPrice' => 'ReadonlyField', 'Vendor' => 'ReadonlyField', 'ImportID' => 'ReadonlyField', 'Available' => 'CheckboxField', 'AllowPurchase' => 'CheckboxField');
     30
     31     static function set_table_fields($fields) {
     32         return self::$table_fields = $fields;
     33     }
     34
     35     static function get_table_fields() {
     36         return self::$table_fields;
     37     }
     38
     39     function init(){
     40         parent::init();
     41
     42         Requirements::javascript('catalog/javascript/CatalogAdmin.js');
     43         Requirements::css('catalog/css/CatalogAdmin.css');
     44     }
     45 }
     46
     47
     48 class CatalogAdmin_CollectionController extends ModelAdmin_CollectionController {
     49
     50     /**
     51      * Мы пока не умеем импорировать товар из CSV
     52      *
     53      * @return false
     54      */
     55     public function ImportForm() {
     56         return false;
     57     }
     58
     59     /**
     60      * Создаем товары только к рубрике
     61      *
     62      */
     63     public function CreateForm() {
     64         return false;
     65     }
     66
     67     public function SearchForm() {
     68         // добавим перевод для рубрики
     69         $form = parent::SearchForm();
     70         if (($catalogs = DataObject::get('Catalog')) && ($rubricField = $form->Fields()->dataFieldByName('ParentID'))) {
     71             $rubricField->setTitle(_t('CatalogAdmin.ParentIDTitle'));
     72             $rubricField->setSource($catalogs->map());
     73         }
     74         return $form;
     75     }
     76
     77     function ResultsForm($searchCriteria) {
     78
     79         if($searchCriteria instanceof SS_HTTPRequest) $searchCriteria = $searchCriteria->getVars();
     80
     81         $tf = $this->getResultsTable($searchCriteria);
     82
     83         // implemented as a form to enable further actions on the resultset
     84         // (serverside sorting, export as CSV, etc)
     85         $form = new Form(
     86             $this,
     87             'ResultsForm',
     88             new FieldSet(
     89                 new HeaderField('SearchResultsHeader',_t('ModelAdmin.SEARCHRESULTS','Search Results'), 2),
     90                 $tf
     91             ),
     92             new FieldSet(
     93                 new FormAction("doSave", _t('CatalogAdmin.doSave', "Save"))
     94             )
     95         );
     96
     97         // Include the search criteria on the results form URL, but not dodgy variables like those below
     98         $filteredCriteria = $searchCriteria;
     99         unset($filteredCriteria['ctf']);
    100         unset($filteredCriteria['url']);
    101         unset($filteredCriteria['action_search']);
    102
    103         $form->setFormAction($this->Link() . '/ResultsForm?' . http_build_query($filteredCriteria));
    104         return $form;
    105     }
    106
    107     function doSave($data, $form) {
    108         if (isset($data['Product']) && is_array($data['Product']) && count($data['Product'])) {
    109             foreach($data['Product'] as $productID=>$productData) {
    110                 if ($product = DataObject::get_by_id('Product', (int)$productID)) {
    111                     foreach(CatalogAdmin::get_table_fields() as $fieldName=>$fieldClass) {
    112                         if ($fieldClass == 'CheckboxField') {
    113                             $product->{$fieldName} = 0;
    114                             if (isset($productData[$fieldName])) {
    115                                 $product->{$fieldName} = $productData[$fieldName];
    116                             }
    117                         }
    118                     }
    119                     $product->writeToStage('Stage');
    120                     if ($product->isPublished()) {
    121                         $product->publish('Stage', 'Live');
    122                     }
    123                 }
    124             }
    125         }
    126     }
    127
    128     function getResultsTable($searchCriteria) {
    129         $summaryFields = array();
    130         $nonCheckboxSummaryFields = array();
    131         foreach(CatalogAdmin::get_table_fields() as $fieldName=>$fieldClass) {
    132             $title = singleton('Product')->fieldLabel($fieldName);
    133             if ($fieldClass == 'CheckboxField') {
    134                 $title .= ' (<span class="select_all_checkboxes" field="'.$fieldName.'"></span> / <span class="unselect_all_checkboxes" field="'.$fieldName.'"></span>)';
    135             } else {
    136                 $nonCheckboxSummaryFields[] = $fieldName;
    137             }
    138             $summaryFields[$fieldName] = $title;
    139         }
    140
    141         $className = $this->parentController->resultsTableClassName();
    142         $tf = new $className(
    143             $this->modelClass,
    144             $this->modelClass,
    145             $summaryFields,
    146             CatalogAdmin::get_table_fields()
    147         );
    148
    149         $tf->setCustomQuery($this->getSearchQuery($searchCriteria));
    150         $tf->setPageSize($this->parentController->stat('page_length'));
    151         $tf->setShowPagination(true);
    152         $tf->showAddRow = false;
    153         // @todo Remove records that can't be viewed by the current user
    154         $tf->setPermissions(array('view','export','edit'));
    155
    156         // csv export settings (select all columns regardless of user checkbox settings in 'ResultsAssembly')
    157         $exportFields = $this->getResultColumns($searchCriteria, false);
    158         $tf->setFieldListCsv($exportFields);
    159
    160         $url = '<a href=\"' . $this->Link() . '/$ID/edit\">$value</a>';
    161         $tf->setFieldFormatting(array_combine($nonCheckboxSummaryFields, array_fill(0,count($nonCheckboxSummaryFields), $url)));
    162
    163         return $tf;
    164     }
    165
    166     public function columnsSelectedByDefault() {
    167         return array('Title', 'BasePrice', 'CostPrice', 'Vendor', 'Available');
    168     }
    169
    170 }
    171
    172 class CatalogAdmin_RecordController extends ModelAdmin_RecordController{
    173     static $allowed_actions = array('add', 'edit', 'view', 'EditForm', 'ViewForm');
    174
    175     public function EditForm() {
    176         $fields = $this->currentRecord->getCMSFields();
    177         $fields->push(new HiddenField("ID"));
    178
    179         $validator = ($this->currentRecord->hasMethod('getCMSValidator')) ? $this->currentRecord->getCMSValidator() : new RequiredFields();
    180         $validator->setJavascriptValidationHandler('none');
    181         $actions = $this->currentRecord->getCMSActions();
    182
    183         if($this->currentRecord->canEdit(Member::currentUser())){
    184             //$actions->push(new FormAction("doSave", _t('ModelAdmin.SAVE', "Save")));
    185         }else{
    186             $fields = $fields->makeReadonly();
    187         }
    188
    189         if(!$this->currentRecord->canEdit(Member::currentUser())){
    190             $fields = $fields->makeReadonly();
    191         }
    192
    193         $actions->dataFieldByName('action_goBack')->setTitle(_t('CatalogAdmin.GOBACK', 'Go Back'));
    194         $actions->removeByName('action_rollback');
    195         // прямое удаление вместе со снятием с публикации
    196         $actions->dataFieldByName('action_delete')->setTitle(_t('CatalogAdmin.DELETE', 'Delete'));
    197
    198         $form = new Form($this, "EditForm", $fields, $actions, $validator);
    199         $form->loadDataFrom($this->currentRecord);
    200
    201         return $form;
    202     }
    203
    204     // Сохранить и опубликовать
    205     function publish($data, $form, $request){
    206         $form->saveInto($this->currentRecord);
    207
    208         try {
    209             $this->currentRecord->write();
    210         } catch(ValidationException $e) {
    211             $form->sessionMessage($e->getResult()->message(), 'bad');
    212         }
    213         $this->currentRecord->doPublish();
    214         return $this->result($request);
    215     }
    216
    217     // Отмена публикации
    218     function unpublish($data, $form, $request){
    219         $this->currentRecord->doUnpublish();
    220         return $this->result($request);
    221     }
    222
    223     // Сохранить
    224     function save($data, $form, $request){
    225         $form->saveInto($this->currentRecord);
    226
    227         try {
    228             $this->currentRecord->write();
    229         } catch(ValidationException $e) {
    230             $form->sessionMessage($e->getResult()->message(), 'bad');
    231         }
    232
    233         return $this->result($request);
    234     }
    235
    236     // Удалить с тестового сайта
    237     function delete($data, $form, $request){
    238         $this->currentRecord->doUnpublish();
    239         $this->currentRecord->delete();
    240         return;
    241     }
    242
    243     function result($request){
    244         // Behaviour switched on ajax.
    245         if(Director::is_ajax()) {
    246             return $this->edit($request);
    247         } else {
    248             Director::redirectBack();
    249         }
    250     }
    251
    252 }
    253

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -