Version: current

      1 <?php
      2 /**
      3  * Новая страница простого заказа на основе UserDefinedForm
      4  * Список полей формируется из полей SimpleOrderPage::get_simple_order_form_fields() и из полей Product::get_simple_order_additional_fields()
      5  *
      6  *
      7  * @package Catalog
      8  * @author menedem
      9  */
     10 class SimpleOrderForm extends UserDefinedForm {
     11
     12     static $defaults = array(
     13         'DevEditType' => 'Fixed',
     14     );
     15
     16     // список полей для формы простого заказа
     17     protected static $simple_order_form_fields = array(
     18         'ProductTitle' => array('type' => 'EditableHiddenField', 'required' => 1),
     19         // 'Num' => array('type' => 'EditableTextField', 'required' => 1),
     20         // RNW сменил тип поля с Text на Num
     21         'Num' => array('type' => 'EditableNumericField', 'required' => 1),
     22         'Client' => array('type' => 'EditableTextField', 'required' => 0),
     23         'City' => array('type' => 'EditableTextField', 'required' => 0),
     24         'Address' => array('type' => 'EditableTextField', 'required' => 0),
     25         'Email' => array('type' => 'EditableEmailField', 'required' => 0),
     26         'Phone' => array('type' => 'EditableTextField', 'required' => 0),
     27         'Comment' => array('type' => 'EditableTextField', 'required' => 0),
     28         'Capcha' => array('type' => 'EditableSpamProtectionField', 'required' => 0),
     29     );
     30
     31     /**
     32      * Получить список полей для формы простого заказа
     33      *
     34      * @return array
     35      */
     36     static function get_simple_order_form_fields() {
     37         return self::$simple_order_form_fields;
     38     }
     39
     40     /**
     41      * Добавить поле в форму простого заказа
     42      *
     43      * @param string $name - название
     44      * @param array $params - параметры
     45      */
     46     static function add_simple_order_form_field($name, $params) {
     47         self::$simple_order_form_fields[$name] = $params;
     48     }
     49
     50     /**
     51      * Удалить поле из формы простого заказа
     52      *
     53      * @param string $name
     54      */
     55     static function del_simple_order_form_field($name) {
     56         unset(self::$simple_order_form_fields[$name]);
     57     }
     58
     59     /**
     60      * Задать поля формы простого заказа
     61      *
     62      * @param array $fields - поля формы
     63      */
     64     static function set_simple_order_form_fields($fields) {
     65         self::$simple_order_form_fields = $fields;
     66     }
     67
     68     /**
     69      *
     70      *
     71      * @param <type> $orderPage
     72      *
     73      * @return <type>
     74      */
     75     static function generate_base_order_fields($orderPage) {
     76         $currentFields = $orderPage->Fields();
     77         $fields = self::get_simple_order_form_fields();
     78         $i = 1;
     79         foreach($fields as $name=>$params) {
     80             if (!$currentFields->find('CustomParameter', $name)) {
     81                 $formField = new $params['type']();
     82                 $formField->CustomParameter = $name;
     83                 $formField->Sort = $i++;
     84                 $formField->Title = _t("SimpleOrderForm.Title_" . $name);
     85                 $formField->Required = $params['required'];
     86                 $formField->ParentID = $orderPage->ID;
     87                 $formField->writeToStage('Stage');
     88                 $formField->Name = $formField->class.$formField->ID;
     89                 $formField->writeToStage('Stage');
     90                 $formField->publish('Stage', 'Live');
     91             }
     92         }
     93
     94         // берем адрес получателя заказов со старой страницы (если есть)
     95         $sc = SiteConfig::current_site_config();
     96         $orderEmail = $sc->AdminEmail();
     97         if ($oldOrderPage = DataObject::get_one('SimpleOrderPage')) {
     98             if ($oldOrderPage->OrderEmail) {
     99                 $orderEmail = $oldOrderPage->OrderEmail;
    100             }
    101             if ($oldOrderPage->PaymentTypes()->Count()) {
    102                 $paymentField = new EditableDropdown();
    103                 $paymentField->CustomParameter = 'PaymentMethod';
    104                 $paymentField->Sort = $i++;
    105                 $paymentField->Title = _t("SimpleOrderForm.Title_PaymentMethod");
    106                 $paymentField->Required = 1;
    107                 $paymentField->ParentID = $orderPage->ID;
    108                 $paymentField->writeToStage('Stage');
    109                 $paymentField->Name = $paymentField->class.$paymentField->ID;
    110                 $paymentField->writeToStage('Stage');
    111                 $paymentField->publish('Stage', 'Live');
    112
    113                 foreach($oldOrderPage->PaymentTypes("Active = 1") as $paymentType) {
    114                     $option = new EditableOption();
    115                     $option->Name = Convert::rus2lat($paymentType->Title);
    116                     $option->Title = $paymentType->Title;
    117                     $option->ParentID = $paymentField->ID;
    118                     $option->writeToStage('Stage');
    119                     $option->publish('Stage', 'Live');
    120                 }
    121             }
    122         }
    123
    124         if (trim($orderEmail)) {
    125             $newRecipient = new UserDefinedForm_EmailRecipient();
    126             $newRecipient->EmailSubject = sprintf(_t('SimpleOrderForm.AdminOrderLetterSubject'), $sc->Title);
    127 // это автоматом так, зато при смене AdminEmail не надо будет залезать в форму
    128 //          $newRecipient->EmailFrom = $sc->AdminEmail();
    129             $newRecipient->EmailAddress = trim($oldOrderPage->OrderEmail);
    130             $newRecipient->FormID = $orderPage->ID;
    131             $newRecipient->write();
    132         }
    133
    134         // добавляем отправку заказа клиенту на указанный в форме Email
    135         if ($emailField = DataObject::get_one('EditableFormField', "ParentID = {$orderPage->ID} AND CustomParameter = 'Email'")) {
    136             $sc = SiteConfig::current_site_config();
    137             $newRecipient = new UserDefinedForm_EmailRecipient();
    138             $newRecipient->EmailSubject = sprintf(_t('SimpleOrderForm.ClientOrderLetterSubject'), $sc->Title);
    139 // это автоматом так, зато при смене AdminEmail не надо будет залезать в форму
    140 //          $newRecipient->EmailFrom = $sc->AdminEmail;
    141             $newRecipient->SendEmailToFieldID = $emailField->ID;
    142             $newRecipient->FormID = $orderPage->ID;
    143             $newRecipient->write();
    144         }
    145     }
    146
    147     static function generate_additional_order_fields($orderPage) {
    148         $currentFields = $orderPage->Fields();
    149         $i = count(self::get_simple_order_form_fields()) + 1;
    150         if ($fields = Product::get_simple_order_additional_fields()) {
    151             foreach($fields as $name=>$params) {
    152                 if (!$currentFields->find('CustomParameter',$name)) {
    153                     $formField = new $params['type']();
    154                     $formField->CustomParameter = $name;
    155                     $formField->Sort = $i;
    156                     $formField->Title = _t("SimpleOrderPage.Title_" . $name);
    157                     $formField->Required = $params['required'];
    158                     $formField->ParentID = $orderPage->ID;
    159                     $formField->writeToStage('Stage');
    160                     $formField->Name = $formField->class.$formField->ID;
    161                     $formField->writeToStage('Stage');
    162                     $formField->publish('Stage', 'Live');
    163                 }
    164             }
    165         }
    166     }
    167
    168     function canCreate() {
    169         return (DataObject::get_one('SimpleOrderForm')) ? false : parent::canCreate();
    170     }
    171
    172     function canDelete() {
    173         return (Director::isDev()) ? parent::canDelete() : false;
    174     }
    175
    176     function onAfterWrite() {
    177         parent::onAfterWrite();
    178
    179         // генерируем поля формы заказа
    180         if (!DataObject::get('EditableFormField', "ParentID = {$this->ID}")) {
    181             self::generate_base_order_fields($this);
    182         }
    183
    184         // генерируем доп.поля формы заказа
    185         self::generate_additional_order_fields($this);
    186     }
    187
    188     function requireDefaultRecords() {
    189         if ($this->class != 'SimpleOrderForm') return;
    190         if (DataObject::get_one('SimpleOrderPage')) return;
    191         if (DataObject::get_one('SimpleOrderForm')) return;
    192
    193         // default pages
    194         $page = new SimpleOrderForm();
    195         $page->Title = _t('SimpleOrderPage.DefaultTitle', 'Order');
    196         $page->URLSegment = 'order';
    197         $page->Status = 'Published';
    198         $page->writeToStage('Stage');
    199         $page->publish('Stage', 'Live');
    200         $page->flushCache();
    201
    202         DB::alteration_message('SimpleOrderPage created', 'created');
    203     }
    204
    205     function getSubmitLetterEmail() {
    206         return new SimpleOrderPage_SubmittedFormEmail();
    207     }
    208 }
    209
    210 class SimpleOrderForm_Controller extends UserDefinedForm_Controller {
    211
    212     protected $item = false;
    213     protected $itemCount = 1;
    214     protected $totalSum = 0;
    215
    216     function init() {
    217         parent::init();
    218         $data = $this->getRequest();
    219         if ($data->param('Action') == 'finished') {
    220             return;
    221         }
    222         if (isset($data['Num']) && is_numeric($data['Num']) && $data['Num'] > 0) {
    223             $this->itemCount = (int) $data['Num'];
    224         }
    225         $id = 0;
    226         if (isset($data['itemId']) && is_numeric($data['itemId'])) {
    227             $id = $data['itemId'];
    228         }
    229         elseif (isset($data['ProductID']) && is_numeric($data['ProductID'])) {
    230             $id = $data['ProductID'];
    231         }
    232         if ($id && ($item = DataObject::get_by_id(singleton('Product')->ClassName, $id))) {
    233             $this->item = $item;
    234             $this->item->TotalSum = $item->Price(1) * $this->itemCount;
    235         } else {
    236             Director::redirect('');
    237         }
    238     }
    239
    240     function checkout() {
    241         if ($this->item) {
    242             return $this->index();
    243         }
    244         return $this->httpError(404);
    245     }
    246
    247     function getEmailData() {
    248         $data = parent::getEmailData();
    249         if ($this->item) {
    250             $data['Product'] = $this->item;
    251         }
    252         return $data;
    253     }
    254
    255     function getFormFields() {
    256         $fields = parent::getFormFields();
    257         if ($this->item) {
    258             $fields->push(new HiddenField('ProductID', 'ProductID', $this->item->ID)); // чтоб не вылетело в init()
    259             if ($field = $this->Fields()->find('CustomParameter', 'ProductTitle')) {
    260                 $fields->dataFieldByName($field->Name)->setValue($this->item->Title);
    261             }
    262             if ($field = $this->Fields()->find('CustomParameter', 'Num')) {
    263                 $fields->dataFieldByName($field->Name)->setValue($this->itemCount);
    264             }
    265             $fields->insertFirst(new LiteralField("ProductTitle", $this->item->renderWith('SimpleOrderFormProductTitle')));
    266             $orderFields = Product::get_simple_order_additional_fields();
    267             // подгружаем возможные значения в has_many-поля товара
    268             if (($has_many = $this->item->has_many()) && count($has_many)) {
    269                 foreach($has_many as $name=>$type) {
    270                     if ($field = $this->Fields()->find('CustomParameter', $name)) {
    271                         if (($formField = $fields->dataFieldByName($field->Name)) && isset($orderFields[$name])) {
    272                             if (($hasManyObjects = $this->item->$name()) && $hasManyObjects->Count()) {
    273                                 $map = $hasManyObjects->map('Title', 'Title');
    274                                 $formField->setSource($map);
    275                             } else {
    276                                 $fields->removeByName($name);
    277                             }
    278                         }
    279                     }
    280                 }
    281             }
    282         }
    283         return $fields;
    284     }
    285 }
    286
    287 class SimpleOrderPage_SubmittedFormEmail extends Email {
    288     protected $ss_template = "SimpleOrderEmail";
    289
    290 }

[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. -