1 <?php
2
3 namespace Balance\Mvc\Controller;
4
5 use Balance\Model\ModelException;
6 use Exception;
7 use Zend\Mvc\Controller\AbstractActionController;
8 use Zend\Stdlib\Parameters;
9 use Zend\View\Model\ViewModel;
10
11 12 13
14 trait EditActionTrait
15 {
16 17 18 19 20
21 public function editAction()
22 {
23
24 if (! $this instanceof AbstractActionController) {
25
26 throw new Exception('Invalid Controller');
27 }
28
29 if (! $this instanceof ModelAwareInterface) {
30
31 throw new Exception('Invalid Controller');
32 }
33
34 if (! $this instanceof RedirectRouteNameAwareInterface) {
35
36 throw new Exception('Invalid Controller');
37 }
38
39 $model = $this->getModel();
40
41 $params = $this->params()->fromRoute();
42
43 $params = array_diff_key($params, array_flip(array('controller', 'action')));
44
45 if ($this->getRequest()->isPost()) {
46
47 $data = $this->getRequest()->getPost();
48
49 try {
50
51 $model->save($data);
52
53 $this->flashMessenger()->addSuccessMessage('Os dados foram salvos com sucesso.');
54
55 return $this->redirect()->toRoute($this->getRedirectRouteName());
56 } catch (ModelException $e) {
57
58 $this->flashMessenger()->addWarningMessage('Verifique o preenchimento dos campos em destaque.');
59 }
60 } else {
61
62 if ($params) {
63
64 try {
65
66 $model->load(new Parameters($params));
67 } catch (ModelException $e) {
68
69 $this->flashMessenger()->addErrorMessage('Impossível carregar os dados solicitados.');
70
71 return $this->redirect()->toRoute($this->getRedirectRouteName());
72 }
73 }
74 }
75
76 $this->getServiceLocator()->get('ViewManager')
77 ->getInjectTemplateListener()->setPreferRouteMatchController(true);
78
79 return new ViewModel(array(
80 'type' => ($params ? 'edit' : 'add'),
81 'form' => $model->getForm(),
82 ));
83 }
84 }
85