Yii2:动态表单小部件wbraganca不是

时间:2016-11-28 13:37:58

标签: php mysql yii2

我的Yii2项目中有 3个相关表(模型)。

  
      
  1. 用户,其中包含| ID (primary key) | username |
  2.   
  3. Phonetype ,其中包含| ID (primary key) | typename |
  4.   
  5. Phonenumber
  6.         

    | ID | user_ID (foreign key) | type_ID (foreign key) | phonenumbers |

我已整合了" wbraganca Yii2动态表格"在我的Yii2应用程序中,但是当我点击"创建"按钮什么都没发生,只是空白页面。但是,当我在刷新数据库时,我获得的用户名是在没有数字的情况下创建的。

请不要将其标记为重复,因为直到现在我还没有找到解决此问题的方法。 提前致谢

这是我的UserController代码

public function actionCreate()
{
    $model = new User();
    $modelsPhone = [new Phonenumber];

    if ($model->load(Yii::$app->request->post())) {
        if($model->save()):

        $modelsPhone = Model::createMultiple(Phonenumber::classname());

        Model::loadMultiple($modelsPhone, Yii::$app->request->post());

        // validate all models
        $valid = $model->validate();
        $valid = Model::validateMultiple($modelsPhone) && $valid;

        if ($valid) {
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                if ($flag = $model->save(false)) {
                    foreach ($modelsPhone as $modelPhone) {
                        $modelPhone->user_id = $model->id;
                        if (! ($flag = $modelPhone->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }
                }
                if ($flag) {
                    $transaction->commit();
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            } catch (Exception $e) {
                $transaction->rollBack();
            }
        }
        endif;

    } else {
        return $this->render('create', [
            'model' => $model,
            'modelsPhone' => (empty($modelsPhone)) ? [new Phonenumber] : $modelsPhone
        ]);
    }
}

/**
 * Updates an existing User 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);
    $modelsPhone = $model->phonenumbers;

    if ($model->load(Yii::$app->request->post())) {

        $oldIDs = ArrayHelper::map($modelsPhone, 'id', 'id');
        $modelsPhone = Model::createMultiple(Phonenumber::classname(), $modelsPhone);
        Model::loadMultiple($modelsPhone, Yii::$app->request->post());
        $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPhone, 'id', 'id')));


        $valid = $model->validate();
        $valid = Model::validateMultiple($modelsPhone) && $valid;

        if ($valid) {
            $transaction = \Yii::$app->db->beginTransaction();
            try {
                if ($flag = $model->save(false)) {
                    if (! empty($deletedIDs)) {
                        Phonenumber::deleteAll(['id' => $deletedIDs]);
                    }
                    foreach ($modelsPhone as $modelPhone) {
                        $modelPhone->user_id = $model->id;
                        if (! ($flag = $modelPhone->save(false))) {
                            $transaction->rollBack();
                            break;
                        }
                    }
                }
                if ($flag) {
                    $transaction->commit();
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            } catch (Exception $e) {
                $transaction->rollBack();
            }
        }
    }

    return $this->render('update', [
        'model' => $model,
        'modelsPhone' => (empty($modelsPhone)) ? [new Phonenumber] : $modelsPhone
    ]);
}

/**
 * Deletes an existing User 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 User model based on its primary key value.
 * If the model is not found, a 404 HTTP exception will be thrown.
 * @param integer $id
 * @return User the loaded model
 * @throws NotFoundHttpException if the model cannot be found
 */
protected function findModel($id)
{
    if (($model = User::findOne($id)) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

protected function findModelPhones($id)
{
    if (($model = Phonenumber::find()->where(['user_id'=>$id])) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

下面的_form.php代码

<div class="user-form">

<?php $form = ActiveForm::begin(['id'=>'dynamic-form']); ?>

<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>

<!-- Creating Phone numbers for user -->
<div class="row">
    <div class="panel panel-default">
        <div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Телефонные номера </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' => 5, // 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' => $modelsPhone[0],
                'formId' => 'dynamic-form',
                'formFields' => [
                    'phonenumbers',
                ],
            ]); ?>

            <div class="container-items"><!-- widgetContainer -->
            <?php foreach ($modelsPhone as $i => $modelPhone): ?>
                <div class="item panel panel-default"><!-- widgetBody -->
                    <div class="panel-heading">
                        <h3 class="panel-title pull-left">Телефонный номер </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 (! $modelPhone->isNewRecord) {
                                echo Html::activeHiddenInput($modelPhone, "[{$i}]id");
                            }
                        ?>

                        <div class="row">
                            <div class="col-sm-6">
                                <?= $form->field($modelPhone, "[{$i}]type_id")->dropDownList(
                                    ArrayHelper::map(Phonetype::find()->all(), 'id','typename'),
                                    ['prompt'=>'Выберите категорию ...']
                                ) ?>
                            </div>
                            <div class="col-sm-6">
                                <?= $form->field($modelPhone, "[{$i}]phonenumbers")->textInput(['maxlength' => true]) ?>
                            </div>
                        </div><!-- .row -->
                    </div>
                </div>
            <?php endforeach; ?>
            </div>
            <?php DynamicFormWidget::end(); ?>
        </div>
    </div>
</div>

<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Создать') : Yii::t('app', 'Редактировать'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

这是我的create.php代码

<?php
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\User */

$this->title = Yii::t('app', 'Создать контакт');
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Контакты'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-create">

<h1><?= Html::encode($this->title) ?></h1>

<?= $this->render('_form', [
'model' => $model,
'modelsPhone'=>$modelsPhone,
]) ?>

Here you can see that i filled all fields.Then when im clicking button, nothing happened

1 个答案:

答案 0 :(得分:0)

  1. 不应该是$ modelsPhone = [new Phonenumber()];

  2. 此外,您还必须创建一个扩展的新MultipleModel类 模型因为createMultiple方法默认不包含在Model中,与loadMultiple和validateMultple不同。

    <?php
    
    namespace common\models;
    
    use Yii;
    use yii\base\Model;
    use yii\helpers\ArrayHelper;
    
    class MultipleModel extends Model
    {
    /**
     * Creates and populates a set of models.
     *
     * @param string  $modelClass
     * @param array   $multipleModels
     * @param  string $pk
     * @return array
     */
        public static function createMultiple($modelClass, $multipleModels = [], $pk = 'id')
        {
        $model    = new $modelClass;
        $formName = $model->formName();
        $post     = Yii::$app->request->post($formName);
        $models   = [];
    
            if (!empty($multipleModels)) {
                $keys           = array_keys(ArrayHelper::map($multipleModels, $pk, $pk));
                $multipleModels = array_combine($keys, $multipleModels);
            }
    
            if ($post && is_array($post)) {
                foreach ($post as $i => $item) {
                    if (isset($item[$pk]) && !empty($item[$pk]) && isset($multipleModels[$item[$pk]])) {
                        $models[] = $multipleModels[$item[$pk]];
                    } else {
                        $models[] = new $modelClass;
                    }
                }
            }
    
            unset($model, $formName, $post);
    
            return $models;
        }
    }