6

have multiple model on same form I dont want to save data on both model but i just want to display one variable on view file

I have 2 tables Organiser and Event Organiser will log in and Create Event Now there are few fields which are common in both tables so when logged in user click on Create Event button i want to display address from Organiser table on the form

This is what i have done until now which may not be the right approach so let me know if that can be achieved any other simpler way

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.');
    }
}

And here is my _form.php code

 <?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(); ?>

Now the problem here seems is that when it comes to saving part throws error saying unknown property address because that field doesnt exists in the database table Event i just want that data to display it on the location field of my create form

so what should i do here

Here is the table structure

Organiser          Event 
organiser_id       event_id
username           organiser_id 
clubname           title
image              location
email
firstname
lastname    
address 

Error page says something like this

Unknown Property – yii\base\UnknownPropertyException

Getting unknown property: common\models\Event::address

And here is my Event model

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']);
}

}

Here is my User model represent Organiser table and model name in frontend model 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;
}

}

So i want to display the organiser.address on the Create event form in the field location Hope you can understand it now thank you

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75
Mike Ross
  • 2,942
  • 5
  • 49
  • 101
  • i am not getting it exactly. Can you show your table structure? – Insane Skull Sep 10 '15 at 05:43
  • @InsaneSkull i have updated the database structure. All i want to do is display values on a field from another table as default value. – Mike Ross Sep 10 '15 at 05:53
  • You can add **Virtual Attributes** with name `address` in your model check this http://www.yiiframework.com/wiki/167/understanding-virtual-attributes-and-get-set-methods/ – Ganesh Ghalame Sep 10 '15 at 05:55
  • you can create object of `organiser` table and pass with create. For ex. `$model3 = new Organiser();` and `return $this->render('create', [ 'model' => $model, 'model2' => $model2, 'model3' => $model3 ]);` – Insane Skull Sep 10 '15 at 05:55
  • @ganeshGhalame thats exactly what i did.. i have added a attribute `address` in rule section of `event` model – Mike Ross Sep 10 '15 at 06:04
  • @InsaneSkull i did that. You can see that in my `ActionCreate` code i attached in the question. My `Organiser` model is `User` in the project – Mike Ross Sep 10 '15 at 06:05
  • Why do you think it should be here? if($_POST['User']['address'] == null) { $model->location = $model2->address; } It should be $_POST['Event']['address'], check firebug or something like that. – Anton M. Sep 10 '15 at 06:08
  • error screenshot please. – Insane Skull Sep 10 '15 at 06:11
  • @AntonM. Because if the record is new than the name of my form field is `address`. and if its update form than field name is `location`.So if its create form and the value is null than i want to get the value from `Organiser.address` table and store it in database of `event.location` – Mike Ross Sep 10 '15 at 06:12
  • @InsaneSkulll Included the error lines in question – Mike Ross Sep 10 '15 at 06:17
  • @MikeRoss so in that case you can use `$model->isNewRecord` – Ganesh Ghalame Sep 10 '15 at 06:20
  • please remove `address` attribute from `event` model it's not needed there and try. your address will came from `user` model. – Insane Skull Sep 10 '15 at 06:20
  • @InsaneSkull that seems to fix the problem. But how can i make the validation work. Can i import the same validation which was on the `Organiser` model or i have to implement manually for this `view` form. – Mike Ross Sep 10 '15 at 06:24
  • @InsaneSkulll i feel like i am passing unnecessary variables to the view form. I ony need 1 field `organiser.address` and display it on `Event` form but i am passing whole `model` with all unnecessary attribute. Let me know if there is any other way to achieve this. Thank you – Mike Ross Sep 10 '15 at 06:32
  • Sorry names for model make me miss something. Show User model structure please. – Anton M. Sep 10 '15 at 06:36
  • And i can`t understand why you need field address from user, why not location from Event, and before render call if it is new model $model->location = $model2->address; And also you search for user twice. – Anton M. Sep 10 '15 at 06:44
  • @AntonM. I know my code is mess. I want to get the data which is in `organiser.address` and display in the `event` create form field `event.location` so that user dont have fill up the same form again. Thats the main thing i want to do. And `organiser` is the table name but the model name in my project for `organiser` is `User` Hope you got the idea. Thank you – Mike Ross Sep 10 '15 at 07:01
  • it will import validation rules from `user` model. so u pass both models. – Insane Skull Sep 10 '15 at 08:00
  • @InsaneSkulll yeah thats what i thought should happen but its not happening. Because in my `User` model the `address` field is required but when i import it on `Event` create form its not required field anymore. Its just normal input field. Thats why i have to check the `[$_POST]` variable before saving. – Mike Ross Sep 10 '15 at 08:05
  • your `$model2` has all the fields of `organiser` and validation of that. in this case show `User` model also. – Insane Skull Sep 10 '15 at 08:08

1 Answers1

3

May be your function should look like

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
    ]);

}

And in form you show location always. Then you can use it in update and create as well without ifs in view. Hope this will help you.

Anton M.
  • 472
  • 4
  • 14
  • Perfect solution... This way i dont have to pass multiple models to the form and no unnecessary if conditions.. Thank you very much – Mike Ross Sep 10 '15 at 23:22