简体   繁体   中英

How to call a controller function on button onclick in yii2

After trying some possible solutions that i found in other questions here, I can't seen to find the problem with my code.. I want to call a function from Yii2 controller after clicking a button in view.

In the view this is the button:

<div class="form-group-result"> <?php echo Html::submitButton('Delete', [ 'onclick' => ' $.ajax({ type: "POST", url: "/search/clearJson" ']);?> </div> </div>

In my SearchController i have this function:

public function clearJson(){........}

This function will delete a json file...

Sorry for my bad english.

I solved. That's how i solved it:

<?php echo Html::submitButton('Delete', [ $this->context->clearJson()]);?>

What is the purpose of you using javascript in the first instance? Your solution has bypassed the need for javascript since you are simply running an equivalent command like the following which accesses the Controller directly and not via javascript.

<?php echo Html::submitButton('Delete', ['clearJson']); ?>

Here is an example that uses Kartiks Gridview with tick selection that access Javascript in a separate location.

Long term you are better doing the following if you are intending to use Javascript:

Button -> Javascript in AppAsset folder -> Controller

Button in index.php

<li class = "btn btn-danger btn-lg" onclick="js:getCopyitbybimonthly()" data-toggle="tooltip" title="<?php echo Yii::t('app','If you tick one of the previous cleans, the detail will be copied to a date roughly two months ahead of its date. Adjust the date once copied to get a more realistic date.')?>"><?php echo Yii::t('app',' + 2 month') ?></li>

Javascript in scripts2.js

function getCopyitbybimonthly (){
var keys = $('#w0').yiiGridView('getSelectedRows'); 
$.post({ type: "GET",
         url: '/salesorderheader/copyticked/4',
    dataType: "json",
    data: {keylist: keys,          
    },
    success: $.pjax.reload({container:'#kv-unique-id-0'}) 
});

}

actionCopyticked($id) in SalesorderheaderController.php

public function actionCopyticked($id)
{
  if (!\Yii::$app->user->can('Update Daily Clean')) {
        throw new \yii\web\ForbiddenHttpException(Yii::t('app','You do not have permission to copy the ticked step.'));
  }
  $keylist = Yii::$app->request->get('keylist');
  foreach ($keylist as $key => $value)
  {
   //find the record of the $value checked item
   $model2 = Salesorderheader::findOne($value);
   $salesorderdetails = [];
   $salesorderdetails = $model2->salesorderdetails;
   $model = new Salesorderheader();
   $model->status = $model2->status;
   $model->statusfile = $model2->statusfile;
   $model->employee_id = $model2->employee_id;
    if ($id == 1) { $model->clean_date = date('Y-m-d');}
    if ($id == 2)
    { 
        $date = $model2->clean_date;
        $addeddate = date('Y-m-d', strtotime($date. ' + 31 days'));
        $model->clean_date = $addeddate;
    }
    if ($id == 3)
    { 
        $date = $model2->clean_date;
        $addeddate = date('Y-m-d', strtotime($date. ' + 14 days'));
        $model->clean_date = $addeddate;
    }
    if ($id == 4)
    { 
        $date = $model2->clean_date;
        $addeddate = date('Y-m-d', strtotime($date. ' + 60 days'));
        $model->clean_date = $addeddate;
    }
    if ($id == 5)
    { 
        $date = $model2->clean_date;
        $addeddate = date('Y-m-d', strtotime($date. ' + 7 days'));
        $model->clean_date = $addeddate;
    }
   $model->sub_total = 0;
   $model->tax_amt=0;
   $model->total_due=0;
   $model->save();
   Yii::$app->session['sod'] = $salesorderdetails;
   foreach ($salesorderdetails as $key => $value)
   {
       $model3= new Salesorderdetail();
       $model3->sales_order_id = $model->sales_order_id;
       $model3->cleaned = "Not Cleaned";
       $product_id = $salesorderdetails[$key]['product_id'];
       $found = Product::find()->where(['id'=>$product_id])->one();
       if ($found->frequency == "Weekly")
        {
                $date = strtotime("+7 day");
                $addeddate = date("Y-m-d" , $date);
                $model3->nextclean_date = $addeddate;
        };
        if ($found->frequency == "Monthly")
            {
               $date = strtotime("+30 day");
               $addeddate = date("Y-m-d" , $date);
               $model3->nextclean_date = $addeddate;
            };
        if ($found->frequency == "Fortnightly")
            {
               $date = strtotime("+15 day");
               $addeddate = date("Y-m-d" , $date);
               $model3->nextclean_date = $addeddate;
            };
        if ($found->frequency == "Every two months")
            {
               $date = strtotime("+60 day");
               $addeddate = date("Y-m-d" , $date);
               $model3->nextclean_date = $addeddate;
            }; 
       if ($found->frequency == "Not applicable")
            {
               $model3->nextclean_date = date("Y-m-d"); 
            };  
       $model3->productcategory_id = $salesorderdetails[$key]['productcategory_id'];
       $model3->productsubcategory_id =$salesorderdetails[$key]['productsubcategory_id'];
       $model3->product_id = $salesorderdetails[$key]['product_id'];
       $model3->unit_price = Yii::$app->formatter->asDecimal($salesorderdetails[$key]['unit_price'],2);
       $model3->paid = 0;
       $model3->save();
   } 

 };
 //return;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM