EYui / EYuiForm.php

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
<?php
/**
 * EYuiForm class file. please view readme for details on input arguments.
 *
 * Present a form filled by users.
 * @author Christian Salazar <christiansalazarh@gmail.com>
 * @link https://bitbucket.org/christiansalazarh/eyui
 * @license http://opensource.org/licenses/bsd-license.php
 */
class EYuiForm extends EYuiWidget implements EYuiActionRunnable {
	
	public $id;
	public $label;
	public $model;
	public $fielddefs;
	public $pages;
	public $submitButtonLabel='Submit Form';
	public $showErrorResume;
	public $submitErrorText='Cannot submit. Please fix errors.';
	public $showErrorsLabel='Show Errors';
	public $formSubmittedOkLabel='The form has been submitted.';
	public $jQueryUiEnabled=true;
	public $jQueryControl='tabs'; // tabs or accordion
	public $jQueryGroupControl=''; // use 'accordion' or leave blank
	public $descriptionLocation; // valid values: 'title'(default) or 'visible'
	
	public $cssClassname='eyuiform';
	public $debug;
	public $action=null;
	
	public function init(){
		//$this->setDebug();
		parent::init();
	}
	
	public function run(){
	
		$id=($this->id != null) ? $this->id : "ejuiform0";
		$tabId = $id."_tabs";
		$cssClassName = ($this->cssClassname != null) ? "class='".$this->cssClassname."'" : '';
		$loadingImgTag = CHtml::image($this->getResource('loading.gif'));
		
		// this->pages can be one of:
		//	a) an array of page entries
		//	b) an instance who implements EYuiFormEditorIStorage,
		//		if so, it will get it page entries from EYuiFormEditor database
		if(isset($this->pages) && (!is_array($this->pages)))
			if($impl = class_implements($this->pages))
				if(isset($impl['EYuiFormEditorIStorage']))
					$this->pages = $this->pages->eyuiformeditordb_getpages();
		
		// will convert each fielddefs into instances of EYuiFormFieldDef
		// and each pages into instances of: EYuiFormPage
		$this->parseModel(array('EYuiFormFieldDef'=>$this->fielddefs,'EYuiFormPage'=>$this->pages));
		
		// build page navigator
		$pageHeader="";
		if($this->jQueryControl == 'tabs'){
		$pageHeader = "<ul>";
		if(isset($this->pages))
		foreach($this->pages as $page)
			{
				$tit = $page->descr;
				$pageHeader .= 
"
	<li alt='{$page->id}' title='$tit'>
		<a href='#{$page->id}'>$page->label</a>
	</li>
";
			}
		$pageHeader .= "</ul>";
		}
		
		$groups_divs = array(); // used when jQueryGroupControl is accordion.
		
		// build each page layout
		$pageDiv="\n";
		if(isset($this->pages))
		foreach($this->pages as $page){
			if($this->jQueryControl == 'accordion')
				$pageDiv .= "\n\n<h3><a href='#'>{$page->label}</a></h3>\n";
			$pageDiv .= "<div class='page' id='{$page->id}'>\n";
				$h1PageTitle="";
				if($this->jQueryUiEnabled == false)
					$h1PageTitle = "<h1>{$page->label}</h1>";
				$pageDiv .= "<div class='info'>{$h1PageTitle}<p>{$page->descr}</p></div>";
				
				$groupsDivId = "{$page->id}_groups";
				$groups_divs[] = $groupsDivId;
				$pageDiv .= "<div class='groups' id='{$groupsDivId}'>";
				if(isset($page->groups))
				foreach($page->groups as $group){
					$fieldsDiv = "";
					foreach($group->fields as $f){
						if(!is_string($f)){
							// each input field here must have 'ALT' signature equal to: 'input'
							//
							$f->setValue($this->model->eyuiform_getFieldValue(
								$this->id,$f->id,$f->getName())
							);
							$fieldsDiv .= $this->preProcessField($f);
						}else{
							$fieldsDiv .= $f;
						}
					}
					$groupTitle = ($group->label != '') ? "<h1>{$group->label}</h1>" : "";
					$groupDescr = ($group->descr != '') ? "<p class='info'>{$group->descr}</p>" : "";
				
					$groupTitleForAccordionControl = "";
					$fix="";
					if($this->jQueryGroupControl == 'accordion'){
						$groupTitleForAccordionControl = "<h6>{$group->label}</h6>";
						$groupTitle='';
						$fix="style='min-height: 150px;'";
					}
				
					
				
					$pageDiv .= 
"
{$groupTitleForAccordionControl}
<div class='group' $fix>
	{$groupTitle}
	{$groupDescr}
	<ul class='fields'>
		{$fieldsDiv}
	</ul>
	<hr/>
</div>
";
				}
				$pageDiv .= "</div>\n";
			$pageDiv .= "</div>\n\n";
		}
		
		// prepares the action to be passed into js component
		$action = $this->action != null ? $this->action : $this->defaultAction;
		$action .= "&classname=".__CLASS__;
		$action .= "&formid=".$this->id;
		
		// creates a submit button
		$form_submit_button_id = $this->id."_submit";
		$submitButton = CHtml::button(self::t($this->submitButtonLabel)
			,array('id'=>$form_submit_button_id));
				
		// creates the layout
		$layout = 
"\n<!-- {$id} begins-->\n<div id='{$id}' {$cssClassName}>\n
		<h1>{$this->label}</h1>
		<div id='{$tabId}' class='pages'>
			{$pageHeader}
			{$pageDiv}
		</div>
		<br/>
		<hr/>
		{$submitButton}<span id='{$id}_saving'></span>
		<div id='{$id}_logger'></div>
</div>\n<!-- {$id} ends-->\n\n"
		;
		echo $layout;
		
		// save valuable information in session to be used later in future action calls:
		$s = new CHttpSession();
		$s->open();
		$s['eyuiform_'.$id] = array(
			'model'=>$this->model,'pages'=>$this->pages);	
		$s->close();
		// prepares options to be passed to js component
		$options = CJavaScript::encode(array(
				'formid'=>$id,
				'action'=>$action,
				'formsubmitbuttonid'=>$form_submit_button_id,
				'loadingUrl'=>$this->getResource('loading.gif'),
				'showErrorResume'=>$this->showErrorResume,
				'submitErrorText'=>self::t($this->submitErrorText),
				'showErrorsLabel'=>self::t($this->showErrorsLabel),
				'formSubmittedOkLabel'=>self::t($this->formSubmittedOkLabel),
		));
		// jquery-ui activation
		if($this->jQueryUiEnabled==true){
			
			$scriptForGroup="";
			if($this->jQueryGroupControl == 'accordion')
				foreach($groups_divs as $groupId)
					$scriptForGroup .= "$(function(){ $('#{$groupId}').{$this->jQueryGroupControl}(); });\n";
			
			Yii::app()->getClientScript()->registerScript(
				$tabId."_corescript",
				 "$(function(){ $('#{$tabId}').{$this->jQueryControl}(); });\n"
				."$(function() { $( '#{$form_submit_button_id}' ).button(); });\n"
				.$scriptForGroup."\n\n"
				, 
				CClientScript::POS_BEGIN
			);
		}
		// invokes the js component who will perform future action calls
		Yii::app()->getClientScript()->registerScript(
			$id,
			"new EYuiForm({$options});", 
			CClientScript::POS_LOAD
		);
	}
	
	// called before a field is renderized
	// 
	private function preProcessField($field){
		$field->descriptionLocation = $this->descriptionLocation;
		
		return $field;
	}
	
	private function findFieldByName($fieldName){
		foreach($this->pages as $page)
			foreach($page->groups as $group)
				foreach($group->fields as $field){
					if(!is_string($field))
						if($field->getName() === $fieldName)
							return $field;
				}
		return null;
	}
	
	private function validateField(EYuiFormField $field,$newFieldValue){
		// validate using fielddefs (fielddef.pattern and field.required)
		if(($newFieldValue == '') && ($field->required==true))
			return array(
				'result'=>false,
				'message'=>($field->requiredMessage != '' ? $field->requiredMessage 
					: self::t('this field is required').': '.$field->label),
				'help'=>$field->getHelpMessage(),
				'fieldname'=>$field->getName(),
			);
		// regexp validation
		if($field->field->pattern != ''){
			Yii::log(__METHOD__."\n field: {$field->id}\noriginal provided pattern:\n".$field->field->pattern,"info");
			$securePattern = "/".trim($field->field->pattern,'/')."/";
			Yii::log(__METHOD__."\n field: {$field->id}\nsecure pattern:\n".$securePattern,"info");
			if(!preg_match($securePattern,$newFieldValue))
				if($newFieldValue != '')
					return array(
						'result'=>false,
						'message'=>($field->field->patternMessage != '' ? $field->field->patternMessage 
							: self::t('invalid supplied value for field:').': '.$field->label),
						'fieldname'=>$field->getName(),
						'help'=>$field->getHelpMessage(),
					);
		}
		// validates using model
		$validationResult = $this->model->eyuiform_validateField(
				$this->id,$field->id,$field->getName(),$newFieldValue,$field->getValue());
		if(is_array($validationResult)){
			if($validationResult['result'] == false){
				return array(
					'result'=>false,
					'message'=>$validationResult['message'].". [".$field->label."]",
					'fieldname'=>$field->getName(),
					'help'=>$field->getHelpMessage(),
				);
			}else{
				// validation is OK
				return array(
					'result'=>true,
					'message'=>'',
					'fieldname'=>$field->getName(),
					'help'=>'',
				);
			}
		}else
		throw new Exception("eyuiform_validateField must return an array");
	}
	
	/**
	* Method called whenever an EYui widget is invoked from an action int order to start a query.
	* invoked via jquery-ajax, by: eyuisearch.js
	* @see
	*	EYuiActionRunnable
	*	EYuiAction
	* @returns an array or any object. it will be converted in EYuiAction to a JSON representation.
	*/
	public function runAction($action,$data){
		$this->id = $_GET['formid'];
		// recovery session information saved before when widget was built
		$s = new CHttpSession();
		$s->open();
		$data = $s['eyuiform_'.$this->id]; //array('model'=>$this->model,'pages'=>$this->pages);	
		$s->close();
		$this->model = $data['model'];
		$this->pages = $data['pages'];

		if($action == 'submit'){
			// get the post. it will be an array formed in js component as: 
			// { id: input.id , val: input.value }
			$rawPost = trim(file_get_contents('php://input'));
			$post = CJSON::decode($rawPost);
			Yii::log(__METHOD__.".submit:\n".$rawPost,"info");
			// validates each provided field in post
			$errorFields = array();
			foreach($post as $fieldentry){
				if(($field = $this->findFieldByName(trim($fieldentry['id']))) != null){
					// query the model for current field value
					$field->setValue($this->model->eyuiform_getFieldValue(
						$this->id,$field->id,$field->getName()));
					// the new field value readed from post
					$result = $this->validateField($field,$fieldentry['val']);
					// array entry definition for each error passed to jquery:
					if($result['result']==false)
						$errorFields[] = array(
							'fieldname'=>$field->getName(),
							'message'=>$result['message'],
							'help'=>$result['help'],
							'id'=>$field->id,
							'label'=>$field->label,
							'page'=>$field->getPage()->label,
							'group'=>$field->getGroup()->label,
							);
				}
				else
					throw new Exception("the field provided in your form is not recognized by EYuiForm config.");
			}
			if(count($errorFields) > 0){
				return array(
					'result'=>false,
					'message'=>'', // it will show options.submitErrorText
					'errors'=>$errorFields,
				);
			}
			
			// all fields pass validation, now massive saving for each field:
			// notify begintrans
			$transaction_handler = $this->model->eyuiform_transaction('begin');
			
			foreach($post as $fieldentry){
				Yii::log(__METHOD__."\nsaving field:\n".$fieldentry['id'],"info");
				if(($field = $this->findFieldByName(trim($fieldentry['id']))) != null){
				$field->setValue(trim($fieldentry['val']));
				if(!$this->model->eyuiform_saveFieldValue(
					$this->id,$field->id,$field->getName(),$field->getValue())){
						// abort saving
						Yii::log(__METHOD__."\nsaving field ABORT.\n","info");
						$this->model->eyuiform_transaction('rollback',$transaction_handler);
						return array(
							'result'=>false,
							'message'=>'Error saving field',
							'fieldname'=>$field->getName(),
						);
						break;
					}
			}}
			Yii::log(__METHOD__."\nsaving field end.\n","info");
			// notify commit
			$this->model->eyuiform_transaction('commit',$transaction_handler);
			return array(
				'result'=>true,
				'message'=>'FORM SUBMITTED',
			);
		}
		else
		if($action == 'fieldchange'){
			// a specific field has a change and need to be validated in model
			//
			$post = CJSON::decode(trim(file_get_contents('php://input')));
			if(($field = $this->findFieldByName(trim($post['id']))) != null){
				// query the model for current field value
				$field->setValue($this->model->eyuiform_getFieldValue(
					$this->id,$field->id,$field->getName()));
				// the new field value readed from post
				return $this->validateField($field,trim($post['val']));
			}
			else
			throw new Exception("the field provided in your form is not recognized by EYuiForm config.");
		}
	}
	
	/**
		it will convert every fielddef into instances of EYuiFormFieldDef
		and every page into instances of EYuiFormPage
		
		as result:  
			$this->fielddefs will be an array of EYuiFormFieldDef instances.
			$this->pages will be an array of EYuiFormPage instances.
	*/
	private function parseModel($entryDefs) {
		foreach($entryDefs as $className=>$_array){
			if(isset($_array)){
				$models = array();
				foreach($_array as $_id=>$attrs){
					$_model = new $className;
					$_model->id = $_id;
					$_model->setAttributes($attrs);
					$models[] = $_model;
				}
				if($className == 'EYuiFormFieldDef')
					$this->fielddefs = $models;
				if($className == 'EYuiFormPage')
					$this->pages = $models;
			}
		}
		if(isset($this->pages)){
		foreach($this->pages as $page){
			$models = array();
			if(isset($page->groups))
			foreach($page->groups as $_id=>$attrs){
				$_model = new EYuiFormGroup;
				$_model->id = $_id;
				$_model->parent = $page;
				$_model->setAttributes($attrs);
				$models[] = $_model;
			}
			$page->groups = $models;
		}
		foreach($this->pages as $page)
			if(isset($page->groups))
			foreach($page->groups as $group)
				{
					$models = array();
					foreach($group->fields as $_id=>$attrs){
						if(!strstr($_id,'separator')){
							$_model = new EYuiFormField;
							$_model->id = $_id;
							$_model->parent = $group;
							$_model->setAttributes($attrs);
							$models[] = $_model;
						}else{	
							$models[] = $attrs;
						}
					}
					$group->fields = $models;
				}
		foreach($this->pages as $page)
			if(isset($page->groups))
			foreach($page->groups as $group)
				foreach($group->fields as $field) {
						if(isset($this->fielddefs)){
							foreach($this->fielddefs as $fd){
								if(!is_string($field) && ($fd->id == $field->field)){
									// link every declared field with a fielddef
									$field->field = $fd;
									// now every field must be in passed model
									$field->modelName = get_class($this->model);
									break;
								}
							}
						}else{
							// no provided fieldset, maybe an array containing object definition:
							// {"uicomponent":"textarea","pattern":"4","patternMessage":"5","options":"2"}
							if(is_array($field->field)){
								$fd = new EYuiFormFieldDef();
								$fd->setAttributes($field->field);
								$field->field = $fd;
							}
						}
					}
		}
	}
	
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.