DEV Community

Kacper Pruszynski
Kacper Pruszynski

Posted on

Saving form data to multiple records in Yii2

Big mystery

Last time I was write a CMS in Yii2 where user have own profile with personal information and relationships to terms.
Updating user profile is not problem in Yii2 but when I want updating profile and terms relationships it was a mystery.

Simplicity is a key

So I created Yii2 model which represents user edit personal form.
To constructor I was pass User which is ActiveRecord

I want to save all user profile details, remove all terms relationships and create new ones.

class EditPersonalForm extends Model{

    public $user;

    public $name;

    public $events;

    public function __construct(User $user, $config = [])
    {
        parent::__construct($config);

        $this->user = $user;

        // user details
        $this->name = $user->getName();

        // terms details
        $this->events = $user->getEventsList();
    }

    public function save($runValidation = true)
    {
        $userProfileUpdated = $this->updateUserProfile($runValidation);

        $this->updateUserEvents();

        return $userProfileUpdated;
    }

    public function updateUserProfile($runValidation)
    {
        $this->user->scenario = $this->scenario;
        $this->user->load(Yii::$app->request->post(), $this->formName());

        return $this->user->save($runValidation);
    }

    public function updateUserEvents()
    {
        TermRelationship::deleteAllEventsByUserID($this->user->getId());
        $this->createTermRelationships($this->events, 0);
    }

    private function createTermRelationships($termsID, $termType)
    {
        foreach ($termsID as $termID){
            $data = array(
                'termID' => $termID,
                'termType' => $termType,
                'userID' => $this->user->getId()
            );

            (new TermRelationship($data))->save();
        }
    }
}

I complete the form fields by giving property value in __construct().
New instance of edit form model is created in controller action and passed to view.

Also what I gonna do in controller is load data from request by standard Model load() method and save edit form hence saving user details and his relations with terms.

// standard controller action

if ($editForm->load(Yii::$app->request->post()) && $editForm->save()) {
    //success message

    return $this->refresh();
}

That would be enough, greetings plum!

Top comments (0)