yiisoft/yii2 — pull request #244 by resurtm (2013-05-12 04:29:42+00:00)
Title: Fixes #226 (second approach).

Fixes #226 (second approach). Usage example:

---

### Controller:

```php
populate($_POST, $user) && $user->save()) {
Yii::$app->response->redirect($user->getProfileUrl());
} else {
echo $this->render('signUp', array(
'user' => $user,
));
}
}

public function actionEditProfile()
{
$user = new User('editProfile');
if ($this->populate($_POST, $user) && $user->save()) {
Yii::$app->response->redirect($user->getProfileUrl());
} else {
echo $this->render('editProfile', array(
'user' => $user,
));
}
}
}
```

---

### Model:

```php
array('username', 'password', 'email'),
'editProfile' => array('password', 'email', 'contact_phone', 'postIds'),
);
}

public static function atomicScenarios()
{
return array('editProfile');
}

public function rules()
{
return array(
// signUp scenario rules
// ...

// editProfile scenario rules
// ...
);
}

public function afterSave($insert)
{
parent::afterSave($insert);

if ($this->isAttributeSafe('postIds')) {
foreach ($this->posts as $post) {
$this->unlink('posts', $post);
}
if (is_array($this->getPostIds())) {
foreach ($this->getPostIds() as $postId) {
$post = Post::find()
->where(array('id' => $postId))
->one();
$this->link('posts', $post);
}
}
}
}

/**
*
*/
public function getPosts()
{
return $this->hasMany('Post', array('author_id' => 'id'));
}

/**
* @var integer[]
*/
private $_postIds;

/**
* @return integer[]
*/
public function getPostIds()
{
if ($this->_postIds === null) {
$this->_postIds = array();
foreach ($this->posts as $post) {
$this->_postIds[] = $post->id;
}
}
return $this->_postIds;
}

/**
* @param integer[] $postIds
*/
public function setPostIds($postIds)
{
if (is_array($postIds)) {
$this->_postIds = $postIds;
}
}
}
```