如何从查询到表进行验证? yii2

时间:2016-05-05 13:30:17

标签: yii2 yii2-basic-app yii2-validation

我的问题是:我有一个表单,我有select2,用户可以从一个表中填充的下拉列表中选择,所以,基本上我想要发生的是当用户试图选择一个驱动程序时验证规则将在那天检查驱动程序是否已通过系统注册。

我有一个如何做到这一点的想法,我有我的存档表格,它注册进入存档表的人,它检查它是否存在于驱动程序表中,如果不是,你必须注册它们,如果它们如果您继续填写表单,则此存档表中的每个字段都有一个datedated列,该字段是输入字段的日期,所以基本上是他最后一次进入。

如何制作一个调用此列的规则与当前日期相比较,如果他当天已经输入则会出错?规则应该在驱动程序模型中。(我的代码令人困惑,这就是为什么我要澄清,我是Yii2的新手)

我的观点(存档表格):

<?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 "drivers".
 *
 * @property integer $driver_id
 * @property string $driver_name
 * @property string $driver_lastname
 * @property string $driver_identitynum
 */
class Drivers extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'drivers';
    }

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

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'driver_id' => 'Driver ID',
            'driver_name' => 'Driver Name',
            'driver_lastname' => 'Driver Lastname',
            'driver_identitynum' => 'Driver Identitynum',
        ];
    }

    public function getfullName()
        {
                return $this->driver_identitynum.' - '.$this->driver_name.' '.$this->driver_lastname.' ';
        }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getArchives()
    {
        return $this->hasMany(Archive::className(), ['driver_identitynum' => 'driver_identitynum']);
    }
}

我的档案模型:

<?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']);
    }
    public function __toString()
    {
        return 'CI:'.$this->driver_identitynum.' Placa: '.$this->vehicle_lp;
    }

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

}

enter image description here

1 个答案:

答案 0 :(得分:0)

因此,规则是只有一个 driver_identitynumDateCreated 组合可以存在于存档表中。

要为此验证driver_identity字段,您可以使用本机unique验证程序并指定需要一起唯一的属性。

相应的规则是:

[['driver_identitynum'], 'unique', 
    'targetAttribute' => ['driver_identitynum', 'DateCreated'],
],

如果从另一个模型调用此验证,则会使问题复杂化。除上述内容外:

  • 指定目标类
  • 在其他模型中声明公共日期变量
  • 在此字段中存储当前日期
  • 表示此date属性应用作值以检查DateCreated的唯一性

调整后的规则是:

[['driver_identitynum'], 'unique', 
    'targetAttribute' => ['driver_identitynum', 'date' => 'DateCreated'],
    'targetClass' => '\app\models\Archive'
],