0

basically. I have a problem with 2 things:

  1. I'm using dynamic forms, the user can add as many as he needs to input all of the invoices at hand. I have a field (invoice_loadamount), i want to sum all of the invoice_loadamount fields. So if the user generates 3 forms i want it to sum dynamic form one(invoice_loadamount field 1) + dynamic form two.(invoice_loadamount field 2) + dynamic form three(invoice_loadamount field 3). How can i make this? Auto sum this field from every form he generated?
  2. My second problem is that i want to then retrieve data from a table (vehicles, column vehicle_capacity) and then compare in such a way that it will validate if the sum is greater than the vehicle_maxcap and then give an error if so.

enter image description here

enter image description here

My form:

<?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>

My archive model:

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

My vehicle model:

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


}

My invoice model:

<?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();

        }
}

My controller:

<?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.');
        }
    }
}
Rob
  • 26,989
  • 16
  • 82
  • 98

1 Answers1

0

As you can see from the HTML <input type="text" id="invoices-0-invoice_loadamount" class="form-control" name="Invoices[0][invoice_loadamount]" maxlength="100"> the loadamount input field is like this. So on the controller side either create function or update function will receive post data as $_POST['Invoices'] as an array like

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"),
    ...
);

where 0, 1 represents each form added. In your case form one, form two etc.

What you need to do is just loop through the array you get from the array. Like this:

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
}

for problem 2, you can then (assume that you already have the 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');
}

Since the second problem depends on a specific vehicles, you need to get its id first.

lhrec_106
  • 630
  • 5
  • 18
  • Where in the code would i add that code? I'm sorry, i'm pretty new to yii2 and i didn't even learn php before hand, it's been a week since i started but it's still confusing for me. –  May 06 '16 at 12:32
  • The code should be added to the `actionUpdate` in controller. Well, since you are new to php and yii, maybe you need to play with it first. Understand how the form information is sent to server and how php receive. Here is some information you can have a look http://php.net/manual/en/reserved.variables.post.php – lhrec_106 May 07 '16 at 02:15