我试图在yii2 /动态表单的帮助下更新数据。 表1-" sellsg" - 列(ssg_id,ssg_customer,ssg_invoiceno,ssg_date,ssg_amount) 表2 - " sellitemsg" - 列(ssgi_id,ssgi_invoiceno,ssgi_sgname,ssgi_price)
关系 - sellsg.ssg_invoiceno = sellitemsg.ssgi_invoiceno
创建部分工作正常。我正在努力应对更新部分。 问题1 。 当表单创建新记录时 - 表单中有一个javascript代码,每次都会增加1的发票。当我加载表单进行更新时,它还会增加1,从而覆盖原始的invoiceno。我想在我创建但不在更新时限制此功能。
问题2 当我更新表单时,它只更新sellsg表但不更新sellitemsg表。
_form
<?php
use yii\helpers\Html;
use kartik\form\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
use dosamigos\datepicker\DatePicker;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
use frontend\modules\sellsg\models\Customer;
use frontend\modules\sellsg\models\Sunglass;
/* @var $this yii\web\View */
/* @var $model frontend\modules\sellsg\models\Sellsg */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="sellsg-form">
<?php $form = ActiveForm::begin([
'id' => 'dynamic-form',
'type' => ActiveForm::TYPE_HORIZONTAL,
'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
]);
?>
<div class="row">
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<div class="col-xs-6 col-sm-6 col-lg-6">
<?= $form->field($model, 'ssg_customer')->label(false)->widget(Select2::classname(), [
'data' => ArrayHelper::map(Customer::find()->all(),'c_name','customerDetails'),
'language' => 'en',
'options' => ['placeholder' => 'Select Customer Details', 'id' => 'custid'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($model, 'ssg_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,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
</div>
</div>
</div>
</div>
<?= $form->field($model, 'ssg_invoiceno')->textInput() ?>
<div class="rows">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Sunglasses</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' => 20, // 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' => $modelsSellitemsg[0],
'formId' => 'dynamic-form',
'formFields' => [
'ssgi_sgname',
'ssgi_price',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsSellitemsg as $i => $modelSellitemsg): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelSellitemsg->isNewRecord) {
echo Html::activeHiddenInput($modelSellitemsg, "[{$i}]ssgi_id");
}
?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelSellitemsg, "[{$i}]ssgi_sgname")->label(false)->widget(Select2::classname(), [
'data' => ArrayHelper::map(Sunglass::find()->all(),'sg_name','sg_name'),
'language' => 'en',
'options' => ['placeholder' => 'Select Sunglass'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-sm-3">
<?= $form->field($modelSellitemsg, "[{$i}]ssgi_price")->textInput([
'maxlength' => true,
'class' => 'sumPart',
//'onfocus'=>'sum()', 'onBlur'=>'sum()'
]) ?>
</div>
<div class="col-sm-3">
<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>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<div class="col-xs-6 col-sm-6 col-lg-6">
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($model, 'ssg_amount')->textInput(['class' => 'sum']) ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
/* start getting the invoiceno */
$script = <<<EOD
$(window).load(function(){
$.get('get-for-invoiceno',{ invoiceid : 1 }, function(data){
//alert(data);
var data = $.parseJSON(data);
$('#sellsg-ssg_invoiceno').attr('value',data.invoiceno);
}
);
});
EOD;
$this->registerJs($script);
/*end getting the invoiceno */
?>
<?php
/* start getting the totalamount */
$script = <<<EOD
var getSum = function() {
var items = $(".item");
var sum = 0;
items.each(function (index, elem) {
var priceValue = $(elem).find(".sumPart").val();
//Check if priceValue is numeric or something like that
sum = parseInt(sum) + parseInt(priceValue);
});
//Assign the sum value to the field
$(".sum").val(sum);
};
//Bind new elements to support the function too
$(".container-items").on("change", ".sumPart", function() {
getSum();
});
EOD;
$this->registerJs($script);
/*end getting the totalamount */
?>
SellsgController
public function actionCreate()
{
$model = new Sellsg();
$modelsSellitemsg = [new Sellitemsg];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$modelsSellitemsg = Model::createMultiple(Sellitemsg::classname());
Model::loadMultiple($modelsSellitemsg, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsSellitemsg) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsSellitemsg as $modelSellitemsg) {
$modelSellitemsg->ssgi_invoiceno = $model->ssg_invoiceno;
if (! ($flag = $modelSellitemsg->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->ssg_id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
else {
return $this->render('create', [
'model' => $model,
'modelsSellitemsg' => (empty($modelsSellitemsg)) ? [new Sellitemsg] : $modelsSellitemsg
]);
}
}
/**
* Updates an existing Sellsg 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);
$modelsSellitemsg = $model->sellitemsg;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$oldIDs = ArrayHelper::map($modelsSellitemsg, 'id', 'id');
//var_dump($oldIDs);
$modelsSellitemsg = Model::createMultiple(Sellitemsg::classname(), $modelsSellitemsg);
Model::loadMultiple($modelsSellitemsg, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsSellitemsg, 'id', 'id')));
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsSellitemsg) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
Sellitemsg::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsSellitemsg as $modelSellitemsg) {
$modelSellitemsg->ssgi_invoiceno = $model->ssg_invoiceno;
if (! ($flag = $modelSellitemsg->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->ssg_id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
else {
return $this->render('update', [
'model' => $model,
'modelsSellitemsg' => (empty($modelsSellitemsg)) ? [new Sellitemsg] : $modelsSellitemsg
]);
}
}
sellsg model
<?php
namespace frontend\modules\sellsg\models;
use Yii;
/**
* This is the model class for table "sellsg".
*
* @property integer $ssg_id
* @property string $ssg_customer
* @property integer $ssg_invoiceno
* @property string $ssg_date
* @property integer $ssg_amount
*/
class Sellsg extends \yii\db\ActiveRecord
{
public $modelsSellitemsg;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'sellsg';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['ssg_customer', 'ssg_invoiceno', 'ssg_date', 'ssg_amount'], 'required'],
[['ssg_invoiceno', 'ssg_amount'], 'integer'],
[['ssg_customer'], 'string', 'max' => 200],
[['ssg_invoiceno'], 'unique'],
[['ssg_date'], 'string', 'max' => 10],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'ssg_id' => 'ID',
'ssg_customer' => 'Customer',
'ssg_invoiceno' => 'Invoice No',
'ssg_date' => 'Date',
'ssg_amount' => 'Amount',
];
}
public function getSellitemsg()
{
return $this->hasMany(Sellitemsg::className(), ['ssgi_invoiceno' => 'ssg_invoiceno']);
}
}
update.php
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model frontend\modules\sellsg\models\Sellsg */
$this->title = 'Update Sellsg: ' . $model->ssg_id;
$this->params['breadcrumbs'][] = ['label' => 'Sellsgs', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->ssg_id, 'url' => ['view', 'id' => $model->ssg_id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="sellsg-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'modelsSellitemsg' => $modelsSellitemsg,
]) ?>
</div>
使用当前代码我收到错误
Getting unknown property: frontend\modules\sellsg\models\Sellitemsg::id
答案 0 :(得分:0)
我找到了解决方案
问题1 -
我创建了_updateform.php
并重定向到那里更新并删除了javascript以加载invoicno -
Update.php
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model frontend\modules\sellsg\models\Sellsg */
$this->title = 'Update InvoiceNo: ' . $model->ssg_id;
$this->params['breadcrumbs'][] = ['label' => 'Sellsgs', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->ssg_id, 'url' => ['view', 'id' => $model->ssg_id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="sellsg-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_updateform', [
'model' => $model,
'modelsSellitemsg' => $modelsSellitemsg,
]) ?>
</div>
<强> Problem2 强> 我的actionUpdate代码现在看起来像 -
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsSellitemsg = $model->sellitemsg;
//$model->setScenario('update');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$oldIDs = ArrayHelper::map($modelsSellitemsg, 'ssgi_id', 'ssgi_id');
//var_dump($oldIDs);
$modelsSellitemsg = Model::createMultiple(Sellitemsg::classname(), $modelsSellitemsg);
Model::loadMultiple($modelsSellitemsg, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsSellitemsg, 'ssgi_id', 'ssgi_id')));
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsSellitemsg) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
Sellitemsg::deleteAll(['ssgi_id' => $deletedIDs]);
}
foreach ($modelsSellitemsg as $modelSellitemsg) {
$modelSellitemsg->ssgi_invoiceno = $model->ssg_invoiceno;
if (! ($flag = $modelSellitemsg->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->ssg_id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
else {
return $this->render('update', [
'model' => $model,
'modelsSellitemsg' => (empty($modelsSellitemsg)) ? [new Sellitemsg] : $modelsSellitemsg
]);
}
}
/**
* Deletes an existing Sellsg 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']);
}
和Model.php -
<?php
namespace frontend\modules\sellsg\models;
use Yii;
use yii\helpers\ArrayHelper;
class Model extends \yii\base\Model
{
/**
* Creates and populates a set of models.
*
* @param string $modelClass
* @param array $multipleModels
* @return array
*/
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'ssgi_id', 'ssgi_id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['ssgi_id']) && !empty($item['ssgi_id']) && isset($multipleModels[$item['ssgi_id']])) {
$models[] = $multipleModels[$item['ssgi_id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}
现在工作正常。