1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21:
22:
23: namespace picon;
24:
25: 26: 27: 28: 29: 30: 31:
32: class AjaxFormSubmitBehavior extends AjaxEventBehaviour implements FormSubmitter
33: {
34: private $form;
35: private $onSubmit;
36: private $onError;
37: private $target;
38:
39: public function __construct($event, $onSubmit = null, $onError = null, $form = null)
40: {
41: $self = $this;
42: parent::__construct($event, function($target) use ($self)
43: {
44: $self->setAjaxRequestTarget($target);
45: $self->getForm()->process($self);
46: });
47:
48: if($onSubmit!=null)
49: {
50: Args::callBackArgs($onSubmit, 1, 'onSubmit');
51: }
52: if($onError!=null)
53: {
54: Args::callBackArgs($onError, 1, 'onError');
55: }
56:
57: $this->onSubmit = $onSubmit;
58: $this->onError = $onError;
59:
60: if($form!=null)
61: {
62: if($form instanceof Form)
63: {
64: $this->form = $form;
65: }
66: else
67: {
68: throw new \InvalidArgumentException('$form must be an instance of Form');
69: }
70: }
71: }
72:
73: public function setAjaxRequestTarget(AjaxRequestTarget $target)
74: {
75: $this->target = $target;
76: }
77:
78: public function getForm()
79: {
80: $form = $this->form;
81: $component = $this->getComponent();
82: if($component instanceof FormComponent)
83: {
84: $form = $component->getForm();
85: }
86:
87: if($form==null)
88: {
89: throw new \IllegalStateException(sprintf('Unable to locate form for ajax submit behaviour on component %s', $component->getId()));
90: }
91: return $form;
92: }
93:
94: public function bind(Component &$component)
95: {
96: parent::bind($component);
97: $this->getForm()->setOutputMarkupId(true);
98: }
99:
100: private function getSubmitForm()
101: {
102: $usingComponent = $this->form;
103: $form = $this->form;
104: if($usingComponent==null)
105: {
106: $usingComponent = $this->getComponent();
107: }
108:
109: $callback = function(&$component) use (&$form)
110: {
111: if($component instanceof Form)
112: {
113: $form = $component;
114: }
115: if($component instanceof ModalWindow)
116: {
117: return Component::VISITOR_STOP_TRAVERSAL;
118: }
119:
120: return Component::VISITOR_CONTINUE_TRAVERSAL;
121: };
122: $usingComponent->visitParents(Component::getIdentifier(), $callback);
123: return $form;
124: }
125:
126: protected function generateCallScript($url)
127: {
128: return sprintf("piconAjaxSubmit('%s', '%s'", $this->getSubmitForm()->getMarkupId(), $url);
129: }
130:
131: public function onError()
132: {
133: $callable = $this->onError;
134: if($callable!=null)
135: {
136: $callable($this->target);
137: }
138: }
139:
140: public function onSubmit()
141: {
142: $callable = $this->onSubmit;
143: if($callable!=null)
144: {
145: $callable($this->target);
146: }
147: }
148: }
149:
150: ?>
151: