0

Есть такая функция-обработчик формы. С вида данные отправляются ajax/ После обработки функцией, данные передаются обратно, в вид, в формате json. Требуется проверить, какие данные приходят из поля post['quantity']). Как это сделать?

public function add() {
    $this->load->language('checkout/cart');

    $json = array();

    if (isset($this->request->post['product_id'])) {
        $product_id = (int)$this->request->post['product_id'];
    } else {
        $product_id = 0;
    }

    $this->load->model('catalog/product');

    $product_info = $this->model_catalog_product->getProduct($product_id);



    if ($product_info) {
        if (isset($this->request->post['quantity'])) {
            $quantity = $this->request->post['quantity'];
        } else {
            $quantity = 1;
        }

        if (isset($this->request->post['option'])) {
            $option = array_filter($this->request->post['option']);
        } else {
            $option = array();
        }

        $product_options = $this->model_catalog_product->getProductOptions($this->request->post['product_id']);

        foreach ($product_options as $product_option) {
            if ($product_option['required'] && empty($option[$product_option['product_option_id']])) {
                $json['error']['option'][$product_option['product_option_id']] = sprintf($this->language->get('error_required'), $product_option['name']);
            }
        }

        if (isset($this->request->post['recurring_id'])) {
            $recurring_id = $this->request->post['recurring_id'];
        } else {
            $recurring_id = 0;
        }

        $recurrings = $this->model_catalog_product->getProfiles($product_info['product_id']);

        if ($recurrings) {
            $recurring_ids = array();

            foreach ($recurrings as $recurring) {
                $recurring_ids[] = $recurring['recurring_id'];
            }

            if (!in_array($recurring_id, $recurring_ids)) {
                $json['error']['recurring'] = $this->language->get('error_recurring_required');
            }
        }

        if (!$json) {
            $this->cart->add($this->request->post['product_id'], (float)$quantity, $option, $recurring_id);

            $json['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']), $product_info['name'], $this->url->link('checkout/cart'));

            // Unset all shipping and payment methods
            unset($this->session->data['shipping_method']);
            unset($this->session->data['shipping_methods']);
            unset($this->session->data['payment_method']);
            unset($this->session->data['payment_methods']);

            // Totals
            $this->load->model('setting/extension');

            $totals = array();
            $taxes = $this->cart->getTaxes();
            $total = 0;

            // Because __call can not keep var references so we put them into an array.             
            $total_data = array(
                'totals' => &$totals,
                'taxes'  => &$taxes,
                'total'  => &$total
            );

            // Display prices
            if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
                $sort_order = array();

                $results = $this->model_setting_extension->getExtensions('total');

                foreach ($results as $key => $value) {
                    $sort_order[$key] = $this->config->get('total_' . $value['code'] . '_sort_order');
                }

                array_multisort($sort_order, SORT_ASC, $results);

                foreach ($results as $result) {
                    if ($this->config->get('total_' . $result['code'] . '_status')) {
                        $this->load->model('extension/total/' . $result['code']);

                        // We have to put the totals in an array so that they pass by reference.
                        $this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
                    }
                }

                $sort_order = array();

                foreach ($totals as $key => $value) {
                    $sort_order[$key] = $value['sort_order'];
                }

                array_multisort($sort_order, SORT_ASC, $totals);
            }

            $json['total'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total, $this->session->data['currency']));
        } else {
            $json['redirect'] = str_replace('&', '&', $this->url->link('product/product', 'product_id=' . $this->request->post['product_id']));
        }
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}
4
  • opencart3 полагаю?
    – Kirill
    5 дек 2019 в 8:46
  • @ Kiril - все верно. Не могу найти, как поменять тип quantity на float, чтобы пересчитывать дробные числа, вводимые в форме
    – Proshka
    5 дек 2019 в 8:53
  • quantity - это переменная поля для количества товара, а товар - число дробное. Цена располагается в переменной price
    – Proshka
    5 дек 2019 в 9:08
  • ага, ясн, спасибо.
    – Kirill
    5 дек 2019 в 9:09

1 ответ 1

2

Произведите замену привидения типа для сущности quantity по всем файлам проекта, где будут найдены такие записи:

  # найденные
(int)$product['quantity']
  # заменять на
(float)$product['quantity']

  # найденные
(int)$this->request->post['quantity'];
  # заменять на 
(float)$this->request->post['quantity'];

  # найденные
(int)$quantity
  # заменять на
(float)$quantity

Далее, в базе данных проекта, надо поменять тип поля quantity по всем таблицам, где данное поле присутствует. По умолчанию это 6 таблиц - cart, order_product, product, product_discount, order_recurring и return.

int(X) -> decimal(X,2)

Не забывайте о том, что екстеншены могут (и будут) затирать данные изменения. Так же вы теряете возможность 'правильно продавать' штучный товар. Поэтому лучше подпилить малость и добавить к продуктам атрибут, идентифицирующий его как штучный/весовой и соответственно организовать везде проверки.

1
  • Спасибо за помощь.
    – Proshka
    6 дек 2019 в 19:57

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.