同一个ActiveForm上的多个模型yii2

Mik*_*oss 6 javascript php yii2 yii2-advanced-app

在同一个表单上有多个模型我不想在两个模型上保存数据,但我只想在视图文件上显示一个变量

我有2个表 OrganiserEvent Organiser将登录和Create Event 现在有几个字段这是常见的用户点击登录,所以当两个表中的Create Event按钮,我想显示addressOrganiser表的形式

这是我到目前为止所做的,这可能不是正确的方法,所以让我知道是否可以通过任何其他更简单的方式实现

public function actionCreate()
{
    $model = new Event();

    $model2 = $this->findModel2(Yii::$app->user->id);


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

        if($_POST['User']['address'] == null)
        {
            $model->location = $model2->address;
        }
        else{
            $model->location = $_POST['User']['address'];
        }

        $model->is_active = 1 ;

        $model->save();


        return $this->redirect(['view', 'id' => $model->id]);
    } else {

        return $this->render('create', [
            'model' => $model,
            'model2' => $model2
        ]);
    }
}
protected function findModel2($id)
{
    if (($model2 = User::findOne($id)) !== null) {
        return $model2;
    } else {
        throw new NotFoundHttpException('The requested page does not     exist.');
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的_form.php代码

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


 <?= $form->field($model, 'interest_id')->dropDownList(
    ArrayHelper::map(Areaintrest::find()->all(),'id','area_intrest'),
    ['prompt'=> 'Select Event Category']
) ?>

<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
   <?php
      if ($model->isNewRecord){
        echo $form->field($model2,'address')->textInput(['class' => 'placepicker form-control'])->label('Location');
    }
    else
        echo $form->field($model,'location')->textInput(['class' => 'placepicker form-control']);

?>

<di"form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update',     ['class' => $model->isNewRecord ? 'btn btn-danger' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>
Run Code Online (Sandbox Code Playgroud)

现在问题似乎是,当涉及到保存部分抛出errorunknown property address因为该字段在数据库表中不存在Event 我只是希望该数据显示在我的位置字段上create form

那我该怎么办

这是表结构

Organiser          Event 
organiser_id       event_id
username           organiser_id 
clubname           title
image              location
email
firstname
lastname    
address 
Run Code Online (Sandbox Code Playgroud)

错误页面说的是这样的

Unknown Property – yii\base\UnknownPropertyException

Getting unknown property: common\models\Event::address
Run Code Online (Sandbox Code Playgroud)

这是我的Event模特

class Event extends \yii\db\ActiveRecord
{

    public static function tableName()
    {
      return 'event';
    }


public function rules()
{
    return [
        [['organiser_id', 'interest_id', 'title', 'location'], 'required'],
        [['organiser_id', 'interest_id'], 'integer'],
        [['title', 'location'], 'string', 'max' => 255],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'organiser_id' => 'Organiser ID',
        'interest_id' => 'Event Type',
        'title' => 'Event Title',
        'location' => 'Location'

    ];
}


public function getOrganiser()
{
    return $this->hasOne(User::className(), ['organiser_id' => 'organiser_id']);
}
Run Code Online (Sandbox Code Playgroud)

}

这是我的User模型表示Organiser前端模型中的表和模型名称SignUp.php

   class SignupForm extends Model
{
public $username;
public $address;
public $password;
public $password_repeat;



public function rules()
{
    return [
        ['username', 'filter', 'filter' => 'trim'],
        ['username', 'required'], 
        ['address', 'required'],
        ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
        ['username', 'string', 'min' => 2, 'max' => 255],


        [['file'], 'file', 'extensions'=>'jpg, gif, png'],



        ['password', 'required'],
        ['password', 'string', 'min' => 6],

        ['password_repeat', 'compare', 'compareAttribute' => 'password'],
    ];
}

public function attributeLabels()
{
    return [
        'password_repeat' => 'Confirm Password',
        'address' => 'Address',
        'username' => 'Username',
    ];
}



public function signup()
{
    if ($this->validate()) {
        $user = new User();
        $model = new SignupForm();
        $user->address = $this->address;
        $user->username = $this->username;

        $user->setPassword($this->password);
        $user->generateAuthKey();
        if ($user->save()) {
            return $user;
        }
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

}

所以我想在显示organiser.addressCreate event在该领域的形式location 希望你能理解,现在谢谢

小智 3

可能你的函数应该是这样的

public function actionCreate()
{
    $event= new Event();

    $user= $this->findModel2(Yii::$app->user->id);
    $event->location = $user->address;

    if ($event->load(Yii::$app->request->post()) && $event->save()) {//active can set by default validator
        return $this->redirect(['view', 'id' => $event->id]);
    }
    return $this->render('create', [
        'event' => $event
    ]);

}
Run Code Online (Sandbox Code Playgroud)

并且在形式中您始终显示位置。然后您也可以在更新和创建中使用它,而无需查看 ifs。希望对你有帮助。