0

基本的。私は2つのことに問題があります:

  1. 私は動的フォームを使用しています。ユーザーは手元にあるすべての請求書を入力するために必要なだけ追加できます。フィールド (invoice_loadamount) があります。invoice_loadamount フィールドのすべてを合計したいです。したがって、ユーザーが 3 つのフォームを生成する場合、動的フォーム 1 (invoice_loadamount フィールド 1) + 動的フォーム 2 (invoice_loadamount フィールド 2) + 動的フォーム 3 (invoice_loadamount フィールド 3) を合計します。どうすればこれを作ることができますか? 彼が生成したすべてのフォームからこのフィールドを自動的に合計しますか?
  2. 私の 2 番目の問題は、テーブル (vehicles、列 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">ように、loadmount 入力フィールドはこのようなものです。したがって、コントローラー側では、作成関数または更新関数のいずれかが $_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 は追加された各フォームを表します。あなたの場合、フォーム1、フォーム2など。

あなたがする必要があるのは、配列から取得した配列をループするだけです。このような:

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');
}

2 番目の問題は特定の車両に依存するため、最初にその ID を取得する必要があります。

于 2016-05-06T00:25:33.033 に答える