The most frequent question is "how to deal with HABTM?".
Actually, it’s not hard at all.
First of all, we create our relation (example from docs):
class Order extends \yii\db\ActiveRecord
{
public function getOrderItems()
{
return $this->hasMany(OrderItem::className(), ['order_id' => 'id']);
}
public function getItems()
{
return $this->hasMany(Item::className(), ['id' => 'item_id'])
->via('orderItems');
}
}
As you can see, we already have separate relation for pivot table here (orderItems).
So the only thing you need to do is to get the values.
First, we create a property to hold these values, like this:
class Order extends \yii\db\ActiveRecord
{
public $order_item_ids = [];
...
}
Then we fill it with actual stored values:
$record = Order::find($id);
$record->order_item_ids = \yii\helpers\ArrayHelper::getColumn(
$record->getOrderItems()->asArray()->all(),
'item_id'
);
(as you can see, I’ve used getColumn() from ArrayHelper class, to get rid of boring stuff)
Now we have selected ids in our order_item_ids property.
Let’s create the form field:
<?= $form->field($record, 'order_item_ids')->checkboxList($optionsList); ?>
Now we need to get list of options for our checkboxes. It’s pretty simple, too:
$list = Item::find()
->select(['id', 'name'])
->asArray()
->all();
$optionsList = \yii\helpers\ArrayHelper::map($list, 'id', 'name');
I’ve limited selected fields to [id, name] only and used asArray() to disable unnecessary DB->ActiveRecord conversion here.
Then I’ve called ArrayHelper::map() to convert result to required format.
ArrayHelper::map() is the new CHtml::listData() ![]()
Now we have checkbox list displaying correctly. What about saving?
Well, it’s up to you. It can be done in model’s afterSave:
foreach ($this->order_item_ids as $id) {
$r = new OrderItem; // probably should be replaced with direct DAO call
$r->order_id = $this->id;
$r->item_id = $id;
$r->save();
}
I’m pretty sure you can use link/unlink for that, but I’m against any magic, sorry ![]()
Notice that order_item_ids must be declared in validation rules (there’s a rule ‘safe’ for that, for example) if you’re planning to use mass-assignment.