php - ZF2 forms - insert and update forms -
this more of question of approach/best practice, specific technical question, come bit of guidance.
my question surrounds zend framework 2 forms, , if should implementing different form insetting entities , updating entities.
to outline simplified use case. let's have product table in database. each product has id (product_id
) primary key , name (name
). let's products storing come supplier provide me unique product id want use primary key in database.
now, let's i've implemented product_fieldset
, product_form
, both of working nicely. form allow me specify product id , name , store in database. however, when user uses form update product name, rather insert new product, don't want them able edit product id database primary key.
i can see how present form in update scenario 1 less field (the product id) implementing 2 forms , 2 fieldsets.
how approach this? when using service manager/form manager pull forms, can't quite head around how/where or if should implement logic within form deal such situations.
:wq
first of all:
let's products storing come supplier provide me unique product id want use primary key in database.
that sku number. keep primary keys database's management. if there external identifier, store separately.
then reuse form both insert , update. becomes quite trivial when sku different property primary key. example in code, see model:
<?php class product { protected $id; protected $sku; protected $name; // getters & setters here } class form extends \zend\form\form { public function __construct() { $this->add(array( 'name' => 'sku', )); $this->add(array( 'name' => 'name', )); } } class controller extends \zend\mvc\controller\abstractactioncontroller { public function createaction() { $form = new form; $product = new product; $form->bind($product); if ($this->getrequest()->ispost()) { $data = $this->getrequest()->getpost(); $form->setdata($data); if ($form->isvalid()) { // service update $service->create($product); // redirect view } } return new viewmodel(array( 'form' => $form, )); } public function updateaction() { $form = new form; // load product based on id $form->bind($product); if ($this->getrequest()->ispost()) { $data = $this->getrequest()->getpost(); $form->setdata($data); if ($form->isvalid()) { // service update $service->update($product); // redirect view } } return new viewmodel(array( 'form' => $form, 'product' => $product, )); } }
this means model keeps id "for itself" , sku can updated anytime. update uses id request (e.g. have url admin/product/edit/123
) , sku number differently , can updated.
by means, form can kept same both update , create methods. use service layer persist object, should way prefer.
Comments
Post a Comment