I have developed Zend 2 application. There is form to edit existing data. Some fields in table is not included in the form. Thus, when editing those records, fields not in form are saved as NULL. How to fix it ?
Model -
namespace Employee\Model;
class Employee
{
public $id;
public $active;
public $type;
public $mailing_address;
public $permanent_address;
...
public function exchangeArray($data)
{
$this->id = (isset($data['id'])) ? $data['id'] : 0;
$this->active = (isset($data['active'])) ? $data['active'] : 0;
$this->type = (isset($data['type'])) ? $data['type'] : null;
$this->mailing_address = (isset($data['mailing_address'])) ? $data['mailing_address'] : null;
$this->permanent_address = (isset($data['permanent_address'])) ? $data['permanent_address'] : null;
...
Table -
public function saveEmployee(Employee $employee) {
$data = array(
'active' => $employee->active,
'type' => $employee->type,
'mailing_address' => $employee->mailing_address,
'permanent_address' => $employee->permanent_address,
...
$id = (int) $employee->id;
if ($id == 0) {
$inserted = $this->tableGateway->insert($data);
$inserted_id = $this->tableGateway->lastInsertValue;
} else {
if ($this->getEmployee($id)) {
$this->tableGateway->update($data, array('id' => $id));
$inserted_id = $id;
} else {
throw new \Exception('Employee does not exist');
}
}
return $inserted_id;
//\Zend\Debug\Debug::dump($inserted_ids);
}
Controller -
$employeeForm = new EmployeeForm();
$employeeForm->bind($employee);
$request = $this->getRequest();
if ($request->isPost()) {
$employeeForm->setData($request->getPost());
if ($employeeForm->isValid()) {
$this->getEmployeeTable()->saveEmployee($employee);
}
}
Assume type
dosn't have form filed defined. So, it shouldn't get NULL when save.
How to fix it ?
If you are editing an existing record then you would need to first load all the data for that entity and then update the fields that have changed. In ZF2 this is achieved via a form hydrator; as you bind the 'populated' object to the form.
Therefore your controller code would need to change.
EmpolyeeController.php
You will also need to register a form factory to inject the hydrator (an other dependancies).
Module.php