0

Apply Coupon私はフォームを持つCakePHP 3プロジェクトに取り組んでいます。

Ajaxを使ってクーポンを適用したい。

クーポンフォームの見方は

<?= $this->Form->create(null, [
  'url' => ['controller' => 'Coupons', 'action' => 'checkCoupon'],
  'name' => 'checkCoupon'
]) ?>
<?= $this->Form->input('coupon_code', [
  'type' => 'text',
  'placeholder' => 'Apply Coupon Code',
  'label' => false
]) ?>
<?= $this->Form->submit('Apply Coupon') ?>

でのcheckCouponアクションCouponsController

public function checkCoupon()
{
  $this->request->onlyAllow('ajax'); // No direct access via browser URL

  if ($this->request->is('post')) {
    $couponCode = $this->request->data['coupon_code'];
    $couponCheck = $this->Coupons->find('all', [
      'conditions' => [
      'coupon_code' => $couponCode
      ]
    ]);
    if ($couponCheck->count() === 1) {
       $coupon = $couponCheck->first();
       $valid_till = $coupon->valid_till;
       $dt = new Time($valid_till);
       $date = $dt->format('Y-m-d');

       if ($date >= date('Y-m-d')) {
         echo 'Coupon is Valid. Discount of '.$coupon->value.'has been applied';
       } else {
         echo 'Coupon is Expired';
       }
    } else {
       echo 'This is not a valid coupon code';
    }
  }
}

$coupon->value$coupon->idを取得して、チェックアウト リンクに次のように追加したい

<?= $this->Html->link(__('Confirm Checkout'), ['controller' => 'ServiceRequests', 'action' => 'confirmCheckout', $service->id, $primaryAddressId, $serviceArea->id, $coupon->id], ['class' => 'btn btn-block btn-success']) ?>

Apply Couponフォームはcheckout動作中ですまたRequestsController 、フォームはうまく機能しています。行を削除してonlyAllow('ajax')値をcheck_coupon.ctp表示して確認しました。

Ajax を使用してどのように行うことができますか?

編集 2: checkout.ctp

<div class="form-info coupon">
  <?= $this->Form->create(null, [
    'url' => ['controller' => 'Coupons', 'action' => 'ajax_checkCoupon'],
    'name' => 'checkCoupon',
    'id' => 'checkCoupon'
  ]) ?>
  <?= $this->Form->input('coupon_code', [
    'type' => 'text',
    'placeholder' => 'Apply Coupon Code',
    'label' => false
  ]) ?>
  <label class="hvr-sweep-to-right">
    <?= $this->Form->submit('Apply Coupon', ['id' => 'applyCoupon']) ?>
  </label>
  <label id="couponUpdate"></label>
  <label id="loading" style="display:none;">Loading...</label>
  <?php
     $data = $this->Html->script('#checkCoupon')->serializeForm(['isForm' => true, 'inline' => true]);
     $this->Html->script('#checkCoupon')->event(
       'submit',
       $this->Html->script(
        [
          'controller' => 'Coupons',
          'action' => 'ajax_checkCoupon'
        ],
        [
          'update' => '#couponUpdate',
          'data' => $data,
          'async' => true,
          'dataExpression' => true,
          'before' => "$('#loading').fadeIn();$('#applyCoupon').attr('disabled','disabled');",
          'complete' => "$('#loading').fadeOut();$('#applyCoupon').removeAttr('disabled');"
        ]
      )
    );
   ?>
  </div>

エラー : 文字列の 18 行目のメンバ関数 serializeForm() の呼び出しcheckout.ctp

4

0 に答える 0