How to validate HABTM model with extra fields?
My case is: Order HABTM Product. In joining table orders_products I've extra field - quantity.
Now, when editing Order I can add Products and enter quantitiy. Here is what I've done already:
In model Order:
public $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'orders_products',
'foreignKey' => 'order_id',
'associationForeignKey' => 'product_id',
'unique' => true,
'with' => 'OrdersProduct'
)
);
In model Product:
public $hasAndBelongsToMany = array(
'Order' => array(
'className' => 'Order',
'joinTable' => 'orders_products',
'foreignKey' => 'product_id',
'associationForeignKey' => 'order_id',
'unique' => true,
'with' => 'OrdersProduct'
)
);
I've created model for joining table OrdersProduct:
class OrdersProduct extends AppModel {
public $name = 'OrdersProduct';
public $validate = array(
'quantity' => array(
'numeric' => array('rule' => array('notempty'))
)
);
}
In orders editing view I've:
<?php echo $this->Form->input("Product.0.OrdersProduct.product_id", array('label' => false, 'options' => $products)); ?>
<?php echo $this->Form->input("Product.0.OrdersProduct.quantity", array('label' => false, 'class' => 'text')); ?>
Now in Orders controller try to save:
// Form processing
if (!empty($this->data)) {
$this->Order->OrdersProduct->set($this->data);
debug($this->Order->OrdersProduct->validates());
if ($this->Order->saveAll($this->data)) {
// Do some stuff
}
And $this->Order->OrdersProduct->validates() always returns TRUE, no matter if I enter quantity or not. All the data saves perfect, only validation is problem. What I'm missing?
Asked by red, on 9/12/09
1 Answer
This is probably a bug i filed already under http://cakephp.lighthouseapp.com/projects/42648-cakephp-1x/tickets/65
I also supplied an bugfix which worked locally for me. But you should watch the ticket for official updates.
Answered by kleingeiston 10/12/09
Tagged with
Rating
0
Viewed
794 times
Last Activity
on 10/12/09
Did you mean get_class()? The debug(get_class($this->Order->OrdersProduct)); returns 'OrdersProduct' so there is no typo.
red - on 10/12/09