0

基本上。我有两件事有问题:

  1. 我正在使用动态表单,用户可以根据需要添加任意数量的输入所有手头的发票。我有一个字段(invoice_loadamount),我想总结所有 invoice_loadamount 字段。因此,如果用户生成 3 个表单,我希望它汇总动态表单一(invoice_loadamount 字段 1)+ 动态表单二。(invoice_loadamount 字段 2)+ 动态表单三(invoice_loadamount 字段 3)。我怎么能做这个?从他生成的每个表格中自动总结这个字段?
  2. 我的第二个问题是,我想从表(车辆,列vehicle_capacity)中检索数据,然后以这样的方式进行比较,以验证总和是否大于vehicle_maxcap,如果是则给出错误。

在此处输入图像描述

在此处输入图像描述

我的表格:

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use wbraganca\dynamicform\DynamicFormWidget;
use app\models\Drivers;
use app\models\Vehicles;
use app\models\Invoices;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use yii\bootstrap\Modal;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $model app\models\Archive */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="archive-form">

    <?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
    <?= $form->field($model, 'driver_identitynum')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(Drivers::find()->all(),'driver_identitynum', 'fullname'),
    'language' => 'en',
    'options' => ['placeholder' => 'Ingrese el numero de cedula...'],
    'pluginOptions' => [
        'allowClear' => true],
    ]); ?>

        <div align="right"><?= Html::a('Add driver', ['/drivers/create'], 
       ['target'=>'_blank']); ?> 
       </div>

    <?= $form->field($model, 'vehicle_lp')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(Vehicles::find()->all(),'vehicle_lp', 'fulltruck'),
    'language' => 'en',
    'options' => ['placeholder' => 'Ingrese la placa del vehiculo...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
    ]); ?>

    <div align="right"><?= Html::a('Add vehicle', ['/vehicles/create'], 
       ['target'=>'_blank']); ?> 
       </div>

   <div class="row"> <div class="panel panel-default">
        <div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i>Facturas</h4></div>
        <div class="panel-body">
             <?php DynamicFormWidget::begin([
                'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
                'widgetBody' => '.container-items', // required: css class selector
                'widgetItem' => '.item', // required: css class
                'limit' => 4, // the maximum times, an element can be cloned (default 999)
                'min' => 1, // 0 or 1 (default 1)
                'insertButton' => '.add-item', // css class
                'deleteButton' => '.remove-item', // css class
                'model' => $modelsInvoices[0],
                'formId' => 'dynamic-form',
                'formFields' => [
                    'invoice_number',
                    'invoice_loadamount',
                    'invoice_date',
                ],
            ]); ?>

            <div class="container-items"><!-- widgetContainer -->
            <?php foreach ($modelsInvoices as $i => $modelInvoices): ?>
                <div class="item panel panel-default"><!-- widgetBody -->
                    <div class="panel-heading">
                        <h3 class="panel-title pull-left">Facturas</h3>
                        <div class="pull-right">
                            <button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
                            <button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
                        </div>
                        <div class="clearfix"></div>
                    </div>
                    <div class="panel-body">
                        <?php
                            // necessary for update action.
                            if (! $modelInvoices->isNewRecord) {
                                echo Html::activeHiddenInput($modelInvoices, "[{$i}]id");
                            }
                        ?>
                        <div class="row">
                            <div class="col-sm-6">
                                <?= $form->field($modelInvoices, "[{$i}]invoice_number")->textInput(['maxlength' => true]) ?>
                            </div>
                            <div class="col-sm-6">
                                <?= $form->field($modelInvoices, "[{$i}]invoice_loadamount")->textInput(['maxlength' => true]) ?>
                            </div>
                            <div class="col-sm-6">
                                <?= $form->field($modelInvoices, "[{$i}]invoice_date", ['enableAjaxValidation' => true])->widget(DatePicker::className(), [
                                            // inline too, not bad
                                             'inline' => false, 
                                             // modify template for custom rendering
                                            //'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
                                             'options' => ['class' => 'form-control picker'],
                                            'clientOptions' => [
                                                'autoclose' => true,
                                                'format' => 'dd-mm-yyyy'

                                                                                ]
                                                                            ]);?>

                            </div>
                        </div><!-- .row -->
                        <div class="row">

                    </div>
                </div>
            <?php endforeach; ?>
            </div>

            <?php DynamicFormWidget::end(); ?>
        </div>
    </div>
</div>


    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

我的存档模型:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "archive".
 *
 * @property integer $id
 * @property string $driver_identitynum
 * @property string $vehicle_lp
 * @property string $DateCreated
 *
 * @property Invoices[] $invoices
 */
class Archive extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'archive';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['driver_identitynum', 'vehicle_lp'], 'required'],
            [['DateCreated'], 'safe'],
            [['driver_identitynum', 'vehicle_lp'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'driver_identitynum' => 'Cedula del conductor:',
            'vehicle_lp' => 'Placa del vehiculo:',
            'DateCreated' => 'Date Created',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getInvoices()
    {
        return $this->hasMany(Invoices::className(), ['archive_id' => 'id']);
    }
}

我的车型:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "vehicles".
 *
 * @property integer $vehicle_id
 * @property string $vehicle_model
 * @property string $vehicle_lp
 * @property string $vehicle_maxcap
 */
class Vehicles extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'vehicles';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['vehicle_model', 'vehicle_lp', 'vehicle_maxcap'], 'required'],
            [['vehicle_model', 'vehicle_lp', 'vehicle_maxcap'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'vehicle_id' => 'Vehicle ID',
            'vehicle_model' => 'Vehicle Model',
            'vehicle_lp' => 'Vehicle Lp',
            'vehicle_maxcap' => 'Vehicle Maxcap',
        ];
    }

        public function getfullTruck()
        {
                return $this->vehicle_lp.' - '.$this->vehicle_model.' - '.$this->vehicle_maxcap.'kgs';
        }  


}

我的发票模型:

<?php

namespace app\models;

use Yii;
use yii\db\Query;
/**
 * This is the model class for table "invoices".
 *
 * @property integer $id
 * @property string $invoice_number
 * @property string $invoice_loadamount
 * @property string $invoice_date
 * @property integer $archive_id
 * @property string $DateProcessed
 *
 * @property Archive $archive
 */
class Invoices extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'invoices';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [            
            [['invoice_number', 'invoice_loadamount', 'invoice_date'], 'required'],
            [['archive_id'], 'integer'],
            [['DateProcessed'], 'safe'],
            //[['invoice_date'],'date','format'=>'dd-mm-yyyy','min'=>date('d-m-Y',time()-60*60*24*5)],
            //Checks if invoice date put in is older than 5 days
            [['invoice_date'], 'date', 'format'=>"dd-MM-yyyy", 'min'=>date("d-m-Y",strtotime('-5 days'))],

            [['invoice_number', 'invoice_loadamount', 'invoice_date'], 'string', 'max' => 100]];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'invoice_number' => 'Numero de factura:',
            'invoice_loadamount' => 'Carga de la factura(kgs):',
            'invoice_date' => 'Fecha de emision de la factura:',
            'archive_id' => 'Archive ID',
            'DateProcessed' => 'Fecha de registro:'];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getArchive()
    {
        return $this->hasOne(Archive::className(), ['id' => 'archive_id']);
    }

    public function compareweight($attribute,$params)
        {
        $inputlp=($this->invoice_loadamount);
        $row = (new \yii\db\Query())
        ->select('vehicle_lp')
        ->from('vehicles')
        ->where("vehicle_lp=$vehiclelp")
        ->all();

        }
}

我的控制器:

<?php

namespace app\controllers;

use Yii;
use app\models\Vehicles;
use app\models\VehiclesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * VehiclesController implements the CRUD actions for Vehicles model.
 */
class VehiclesController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Vehicles models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new VehiclesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Vehicles model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Vehicles model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Vehicles();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->vehicle_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Vehicles model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->vehicle_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Vehicles model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Vehicles model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Vehicles the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Vehicles::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
4

1 回答 1

0

正如您从 HTML 中看到的<input type="text" id="invoices-0-invoice_loadamount" class="form-control" name="Invoices[0][invoice_loadamount]" maxlength="100">那样,loadamount 输入字段是这样的。因此,在控制器端,无论是创建函数还是更新函数,都会以 $_POST['Invoices'] 作为数组接收发布数据,例如

array( 
    "0"=>array("invoice_number" => "132412", "invoice_loadamount" =>"34.00", "invoice_date" =>"2015-03-04"),
    "1"=>array("invoice_number" => "352223", "invoice_loadamount" =>"233.00", "invoice_date" =>"2016-03-04"),
    ...
);

其中 0, 1 表示添加的每个表单。在您的情况下,表格一,表格二等。

您需要做的只是遍历从数组中获得的数组。像这样:

if (Yii::$app->request->isPost) {
    $data = Yii::$app->request->post();
    $invoices = $data['Invoices'];
    $total = 0;
    if(sizeof($invoices) > 0){
         foreach($invoices as $one_invoice){
             $one_loadamount =  floatval($one_invoice['invoice_loadamount']);
             $total += $one_loadamount;
         }
    }
    //then you get the total amount as $total
}

对于问题 2,您可以(假设您已经拥有 vehicle_id)。

$vehicle = Vehicles::find()->where(['id'=>$vehicle_id])->one();
if($total > $vehicle->maxcap){
    \Yii::$app->getSession()->setFlash('danger', 'Total is larger than max cap');
}

由于第二个问题取决于特定的车辆,因此您需要先获取其 id。

于 2016-05-06T00:25:33.033 回答