O
O
Oleg Lysenko2016-05-23 13:09:26
Yii
Oleg Lysenko, 2016-05-23 13:09:26

Is it possible to dynamically pass a variable to a widget using Pjax?

Hello, the essence of the question is this: there is a widget in the view that takes the $type parameter and, based on it, renders a certain view. This parameter is passed from the controller that renders the main view file, there is a default value. The main view has a Pjax and JS onchange event that passes the same $type to the controller. But when updating with Pjax, the widget for some reason does not pick up the parameter, or does not have time to render the required view, please help.
main view

<?php Pjax::begin(); ?>
        <?php if($productsInCart):?>

            <table id="cart_products"cellspacing="0">
                <tr>
                    <th>Удалить</th>
                    <th>Наименование</th>
                    <th>Цена</th>
                    <th>Количество</th>
                    <th>Всего</th>
                </tr>

                <?php foreach($prods as $product):?>
                    <tr>
                        <td><a href="" class="del" data-id="<?= $product->id;?>">
                                <img src="/img/del_prod_pic.png">
                            </a></td>
                        <td><?= $product->name;?></td>
                        <td><?= $product['prices'][0]->price;?></td>
                        <td>
                            <?= $productsInCart[$product['id']];?> шт.
                            <a href="" class="to_cart" data-id="<?= $product->id;?>">
                                <img src="/img/plus.png">
                            </a>
                            <a href="" class="cart_del" data-id="<?= $product->id;?>">
                                <img src="/img/minus.png">
                            </a>
                        </td>
                        <td><?= Order::getProdTotalPrice($product->id);?></td>
                    </tr>
                <?php endforeach;?>
                <tr id="total_sum">
                    <td></td>
                    <td></td>
                    <td></td>
                    <td>Итого в корзине: </td>
                    <td><?= $totalPrice;?></td>
                </tr>
            </table>

            <?php
                $form = ActiveForm::begin(['id' => 'delivery_form']);

                echo $form->field($model_order, 'FIO')->textInput(['value' => $user->username]);

                echo $form->field($model_order, 'email')->textInput(['value' => $user->email]);

                echo $form->field($model_order, 'phone')->textInput(['value' => $user->phone]);

                echo $form->field($model_address, 'address')->textarea();

                echo $form->field($model_order, 'comment')->textarea();

                echo $form->field($model_delivery_type, 'name')->dropDownList(
                    ArrayHelper::map(DeliveryType::find()
                        ->orderBy('prior ASC')
                        ->all(), 'alias', 'name'
                    ),['id' => 'delivery_type']);

                echo DeliveryWidget::widget(['type' => $type, 'form' => $form]);

                ActiveForm::end();
            ?>

            <a href="/cart/checkout" class="checkout">
                Оформить заказ
            </a>

        <?php else:?>
            <h2 id="empty_cart">Ваша корзина пуста</h2>
            <a href="/" id="empty_cart_to_main">Продолжить покупки</a>
        <?php endif;?>
        <?= Html::a("Обновить", ['/cart'], ['class' => 'refresh btn btn-lg btn-primary']);?>
        <?php Pjax::end(); ?>

Controller
public function actionIndex () {
//echo Yii::$app->request->post('alias');exit;
        $type = 'empty';

        //Получаем данные из корзины
        $productsInCart = Order::getProducts();
        if ($productsInCart) {
            //Получаем полную информацию о товаре
            $productsId = array_keys($productsInCart);
            $productsId;
            $prods = ShopProducts::find()->joinWith('prices')->where([
                    'shop_products.id' => $productsId,
                ])->all();
            //Получаем общую стоимость товаров
            $totalPrice = Order::getTotalPrice($prods);
        }

        if(Yii::$app->request->isPost && !empty(Yii::$app->request->post('alias'))){
            $type = Yii::$app->request->post('alias');
        }

        $model_order = new Order;
        $model_delivery_type = new DeliveryType;

        switch($type){

            case 'courier' : $model_address = new DeliveryCourier;
                break;

            case 'pickup' : $model_address = new DeliveryPickup;
                break;

            case 'novaposhta' : $model_address = new DeliveryNovaposhta;
                break;

            default: $model_address = new DeliveryCourier;
        }

        if(!Yii::$app->user->isGuest){
            $user = User::findOne(Yii::$app->user->identity->id);
        }

        return $this->render('index', [
            'prods' => $prods,
            'productsInCart' => $productsInCart,
            'totalPrice' => $totalPrice,
            'type' => $type,
            'model_order' => $model_order,
            'model_delivery_type' => $model_delivery_type,
            'user' => $user,
            'model_address' => $model_address
        ]);
    }

Widget
class DeliveryWidget extends Widget
{

    public $type = 'empty';
    public $form;

    public function run()
    {
        return $this->render("delivery_$this->type", [
            'form' => $this->form
        ]);
    }
}

JS
$('body').on('change', '#delivery_type', function(){
        var alias = $(this).val();

        $.post("/cart", {'alias': alias}, function(data){

        });

        $('.refresh').click();
        return false;
    });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
SharuPoNemnogu, 2016-05-25
@oleglysenko

It works, it means ok, it can be useful to someone:
and in js

$('body').on('change', '#delivery_type', function(){
    var alias = $(this).val();
    $.pjax({
        type : 'POST',
        url : '/cart',
        container : '#cart-wrapper',
        data : {alias: alias}
    });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question