我已经玩了一段时间,但我似乎无法弄清楚错误是什么或如何解决它。所有我能想到的都是因为我的wbranganca动态表单小部件在我设置自定义规则时不知道如何操作。
我的问题:我有wbranganca动态表单,我有一些字段可以验证基本规则,例如只允许整数,或者它是必需的,它不能留空,但是当我添加自定义规则时如果没有大于,或者日期规则(例如不超过5天),当我将其输入到字段中时,它不会显示任何错误,但是当我点击保存表单时,我会收到一个白色屏幕。并且数据没有保存到表中,这意味着我的规则有效,我也在动态表单之外的字段上尝试相同的规则并且它正常工作,那么我该如何设置正确的方法呢?
我的控制器:
<?php
namespace app\controllers;
use Yii;
use app\models\Archive;
use app\models\ArchiveSearch;
use app\models\Invoices;
use app\models\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* ArchiveController implements the CRUD actions for Archive model.
*/
class ArchiveController extends Controller
{
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Archive models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new ArchiveSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Archive model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Archive model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Archive();
$modelsInvoices = [new Invoices];
if (Yii::$app->request->isAjax && $model->load($_POST))
{
Yii::$app->response->format ='json';
return \yii\widgets\ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post()) && $model->save())
{
$modelsInvoices = Model::createMultiple(Invoices::classname());
Model::loadMultiple($modelsInvoices, Yii::$app->request->post());
/*if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ArrayHelper::merge(
ActiveForm::validateMultiple($modelsInvoices),
ActiveForm::validate($model)
);
}*/
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsInvoices) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsInvoices as $modelInvoices)
{
$modelInvoices->archive_id = $model->id;
if (! ($flag = $modelInvoices->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
return $this->render('create', [
'model' => $model,
'modelsInvoices' => (empty($modelsInvoices)) ? [new Invoices] : $modelsInvoices
]);
}
}
/**
* Updates an existing Archive 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->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Archive 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 Archive model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Archive the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Archive::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
我的模特:
<?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'],
//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' => 'Invoice Number',
'invoice_loadamount' => 'Invoice Loadamount',
'invoice_date' => 'Invoice Date',
'archive_id' => 'Archive ID',
'DateProcessed' => 'Date Processed'];
}
/**
* @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
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> Addresses</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">Address</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")->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>',
'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>
答案 0 :(得分:2)
查看强>
将['enableAjaxValidation' => true]
放在字段中。
<div class="col-sm-6">
<?= $form->field($modelInvoices, "[{$i}]invoice_date",['enableAjaxValidation' => true])->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'dd-MM-yyyy'
]
]);
?>
</div>
<强>控制器强>
添加use yii\web\Response;
&amp; use yii\widgets\ActiveForm;
并根据以下代码更改代码结构。
<?php
// These two lines are mandatory.
use yii\web\Response;
use yii\widgets\ActiveForm;
public function actionCreate()
{
$model = new Archive();
$modelsInvoices = [new Invoices];
$modelsInvoices = Model::createMultiple(Invoices::classname());
Model::loadMultiple($modelsInvoices, Yii::$app->request->post());
if (Yii::$app->request->isAjax)
{
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($modelsInvoices);
} elseif ($model->load(Yii::$app->request->post()) && $model->save()) {
.
.
}
.
.
}
它会起作用。
有关详情,请点击Validating unique email using DynamicFormWidget - Yii2