Кастомизация getCreateForm и getEditForm для гибкой верстки полей — различия между версиями

Материал из Umicms
Перейти к:навигация, поиск
(Новая страница: «По умолчанию, методы '''getCreateForm''' и '''getEditForm''' настроены таким образом, что для каждого типа п…»)
(нет различий)

Версия 05:51, 25 февраля 2011

По умолчанию, методы getCreateForm и getEditForm настроены таким образом, что для каждого типа полей используется один и тот же блок в TPL-шаблоне, из-за этого бывает сложно оформить верстку нужным образом, когда необходимо каждое поле оформить особым образом. Также не всегда необходимо выводить все поля из группы. Оригинальные методы getCreateForm и getEditForm можно вынести в кастом и настроить таким образом, таким образом что в макрос будут передаваться идентифкаторы полей, вместо групп, а сам код, в TPL-шаблоне будет сначала искать блок у которого префикс с нужным идентфикатором поля, допустим: reflection_field_string_h1

Добавим в папку classes/modules/data/ файл permissions.custom.php следующего содержания:

<?php
    $permissions = Array('main' => Array('getCreateFormCustom' , 'getEditFormCustom'));
?>

а в файл classes/modules/data/__custom.php добавим новые методы:

    public function getCreateFormCustom($object_type_id, $template = "default", $fields_names = "", $parent_id) {
      if(!permissionsCollection::getInstance()->isAuth() || !$parent_id) return false;
      
			if(!$template) $template = "default";
			
			list($template_block) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_fields");
			
			$fields_names = trim($fields_names);

			$fields_arr = strlen($fields_names) ? explode(" ", $fields_names) : array();

			
			if(!is_array($fields_arr)) {
				return "";
			}

			$line_arr = Array();
        
				$fields = Array();
				$type = umiObjectTypesCollection::getInstance()->getType($object_type_id);
				      					
				foreach($fields_arr as $field_name) {				
				  $field_id = $type->getFieldId($field_name);	
					$field = umiFieldsCollection::getInstance()->getField($field_id);
				
					if(!$field->getIsVisible() && !$all) continue;
					if($field->getIsSystem()) continue;
					
					$fields[] = $this->renderEditFieldCustom($template, $field);
				}
				
				if(empty($fields)) continue;

			$line_arr['nodes:field'] = $line_arr['void:fields'] = $fields;
			$line_arr['parent_id'] = $parent_id;
			$line_arr['object_type_id'] = $object_type_id;
			$line_arr['template'] = $template;
			$line_arr['fields_arr'] = $fields_names;
			return def_module::parseTemplate($template_block, $line_arr);
		}
		  
   	public function getEditFormCustom($template = "editpage", $fields_names = "", $all = false, $ignorePermissions = false) {
			 if(!$page_id = htmlspecialchars(getRequest('id'))) return false; 
       $hierarchy = umiHierarchy::getInstance();
       $element = $hierarchy->getElement($page_id);
 
       if($element instanceof umiHierarchyElement) {
            $object_id = $element->getObjectId();
            $permissions = permissionsCollection::getInstance();
            if(!$permissions->isOwnerOfObject($object_id)) return false;
      }else return false;
            
      if(!$template) $template = "default";

			$b_allow = false;
			$inst_users = cmsController::getInstance()->getModule("users");

			if($permissions->isSv()) {
				$ignorePermissions = true;
			}
			
			if($permissions->isSv()) {
				$ignorePermissions = true;
			}
			
			if(!$ignorePermissions) {
				$b_allow = $permissions->isOwnerOfObject($object_id);

				$arr_helements = $hierarchy->getObjectInstances($object_id);
				foreach ($arr_helements as $i_element_id) {
					$arr_allow = $inst_users->isAllowedObject($inst_users->user_id, $i_element_id);
					if (is_array($arr_allow) && count($arr_allow) > 1) {
						$b_allow = intval($arr_allow[1]);
						if ($b_allow) break;
					}
				}

				if (!$b_allow) {
					return templater::getInstance()->putLangs("%data_edit_foregin_object%");
				}
			}
	  
			list($template_block) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_fields");
			
      if(!($object = umiObjectsCollection::getInstance()->getObject($object_id))) {
				return $template_block_empty;
			}
			$fields_names = trim($fields_names);

			$fields_arr = strlen($fields_names) ? explode(" ", $fields_names) : array();

			
			if(!is_array($fields_arr)) {
				return "";
			}
       
			$line_arr = Array();
        $object_type_id = $object->getTypeId();
				$fields = Array();
				$type = umiObjectTypesCollection::getInstance()->getType($object_type_id);
				      					
				foreach($fields_arr as $field_name) {				
				  $field_id = $type->getFieldId($field_name);	
					$field = umiFieldsCollection::getInstance()->getField($field_id);
				
					if(!$field->getIsVisible() && !$all) continue;
					if($field->getIsSystem()) continue;
					
					$fields[] = $this->renderEditFieldCustom($template, $field, $object);
				}
				
			$line_arr['nodes:field'] = $line_arr['void:fields'] = $fields;
			$line_arr['object_id'] = $object_id;
			$line_arr['page_link'] = $hierarchy->getPathById($page_id);
			$line_arr['template'] = $template;

			return def_module::parseTemplate($template_block, $line_arr, false, $object_id);
		}
		
        
    public function renderEditFieldCustom($template, umiField $field, $object = false) {
			$field_type_id = $field->getFieldTypeId();
			$field_type = umiFieldTypesCollection::getInstance()->getFieldType($field_type_id);
			$is_multiple = $field_type->getIsMultiple();

			$data_type = $field_type->getDataType();

			$xsl = xslTemplater::getInstance()->getIsInited();

			switch($data_type) {
				case "counter":
				case "int": {
					$res = $this->renderEditFieldIntCustom($field, $is_multiple, $object, $template);
					break;
				}


				case "price":
				case "float": {
					$res = $this->renderEditFieldIntCustom($field, $is_multiple, $object, $template);
					break;
				}


				case "string": {
					$res = $this->renderEditFieldStringCustom($field, $is_multiple, $object, $template);
					break;
				}

				case "date": {
					$res = $this->renderEditFieldDateCustom($field, $is_multiple, $object, $template);
					break;
				}

				case "password": {
					$res = $this->renderEditFieldPasswordCustom($field, $is_multiple, $object, $template);
					break;
				}

				case "relation": {
					$res = $this->renderEditFieldRelationCustom($field, $is_multiple, $object, $template);
					break;
				}


				case "symlink": {
					$res = $this->renderEditFieldSymlinkCustom($field, $is_multiple, $object, $template);
					break;
				}

				case "img_file": {
					$res = $this->renderEditFieldImageFileCustom($field, $is_multiple, $object, $template);
					break;
				}

				case "video_file" :
				case "swf_file": {
					$res = $this->renderEditFieldFileCustom($field, $is_multiple, $object, $template);
					break;
				}

				case "file": {
					$res = $this->renderEditFieldFileCustom($field, $is_multiple, $object, $template);
					break;
				}

				case "text": {
					$res = $this->renderEditFieldTextCustom($field, $is_multiple, $object, $template);
					break;
				}

				case "wysiwyg": {
					$res = $this->renderEditFieldWYSIWYGCustom($field, $is_multiple, $object, $template);
					break;
				}

				case "boolean": {
					$res = $this->renderEditFieldBooleanCustom($field, $is_multiple, $object, $template);
					break;
				}
				
				
				case "tags": {
					$res = $this->renderEditFieldTagsCustom($field, $is_multiple, $object, $template);
					break;
				}
				
				case "optioned": {
					$res = $this->renderEditFieldOptionedCustom($field, $is_multiple, $object, $template);
					break;
				}


				default: {
					$res = $xsl ? NULL : "";
					break;
				}
			}
			
			if($res === false) {
				return NULL;
			}
			
			if($xsl) {
				if($data_type == 'counter') $data_type = 'int';

				$res['attribute:type'] = $data_type;
				$res['attribute:id'] = $field->getId();
				
				if($field->getIsRequired()) {
					$res['attribute:required'] = 'required';
				}
				if($tip = $field->getTip()) {
					$res['attribute:tip'] = $tip;
				}
			} else {
				$required = $field->getIsRequired();
				$res = def_module::parseTemplate($res, array(
					'required' => ($required ? 'required' : ''),
					'required_asteriks' => ($required ? '*' : '')
				));
			}
			
			return $res;
		}


		public function renderEditFieldStringCustom($field, $is_multiple, $object, $template) {
		  $field_name = $field->getName();
		  list($template_block) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_field_string_" . $field_name);
		  if(!$template_block){
			list($template_block) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_field_string");
      }
      
			$block_arr = Array();

			if($is_multiple) {
			
			} else {				
				$block_arr['attribute:name'] = $field_name;
				$block_arr['attribute:title'] = $field->getTitle();
				$block_arr['attribute:tip'] = $field->getTip();

				$block_arr['node:value'] = ($object) ? $object->getValue($field->getName()) : "";

				if($object) {
					$block_arr['void:object_id'] = $object->getId();
				}


				$block_arr['attribute:input_name'] = ($object) ? "data[" . $object->getId() . "][{$field_name}]" : "data[new][{$field_name}]";
			}

			return def_module::parseTemplate($template_block, $block_arr);
		}

		public function renderEditFieldTextCustom($field, $is_multiple, $object, $template) {
		  		  $field_name = $field->getName();
		  list($template_block) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_field_text_" . $field_name);
		  if(!$template_block){
			list($template_block) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_field_text");
       }
			$block_arr = Array();

			if($is_multiple) {
				
			} else {

				$block_arr['attribute:name'] = $field_name;
				$block_arr['attribute:title'] = $field->getTitle();
				$block_arr['attribute:tip'] = $field->getTip();

				$block_arr['node:value'] = ($object) ? $object->getValue($field->getName()) : "";

				if($object) {
					$block_arr['void:object_id'] = $object->getId();
				}


				$block_arr['attribute:input_name'] = ($object) ? "data[" . $object->getId() . "][{$field_name}]" : "data[new][{$field_name}]";
			}

			return def_module::parseTemplate($template_block, $block_arr);
		}

		public function renderEditFieldIntCustom($field, $is_multiple, $object, $template) {
				  $field_name = $field->getName();
		  list($template_block) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_field_int_" . $field_name);
		  if(!$template_block){
			list($template_block) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_field_int");
       }
			$block_arr = Array();

			if($is_multiple) {
				
			} else {

				$block_arr['attribute:name'] = $field_name;
				$block_arr['attribute:title'] = $field->getTitle();
				$block_arr['attribute:tip'] = $field->getTip();

				$block_arr['node:value'] = ($object) ? $object->getValue($field->getName()) : "";

				if($object) {
					$block_arr['void:object_id'] = $object->getId();
				}


				$block_arr['attribute:input_name'] = ($object) ? "data[" . $object->getId() . "][{$field_name}]" : "data[new][{$field_name}]";
			}

			return def_module::parseTemplate($template_block, $block_arr);
		}

		public function renderEditFieldBooleanCustom($field, $is_multiple, $object, $template) {
				  $field_name = $field->getName();
		  list($template_block) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_field_boolean_" . $field_name);
		  if(!$template_block){
			list($template_block) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_field_boolean");
      }
			$block_arr = Array();

			if ($is_multiple) {
				
			} else {

				$block_arr['attribute:name'] = $field_name;
				$block_arr['attribute:title'] = $field->getTitle();
				$block_arr['attribute:tip'] = $field->getTip();

				$block_arr['attribute:checked'] = "";
				$block_arr['node:value'] = 0;
				if ($object) {
					$block_arr['node:value'] = (int) $object->getValue($field->getName());
					$block_arr['attribute:checked'] = (bool) $object->getValue($field->getName())? "checked" : "";
					$block_arr['void:object_id'] = $object->getId();
				}


				$block_arr['attribute:input_name'] = ($object) ? "data[" . $object->getId() . "][{$field_name}]" : "data[new][{$field_name}]";
			}

			return def_module::parseTemplate($template_block, $block_arr);
		}

        
		public function renderEditFieldRelationCustom($field, $is_multiple, $object, $template) {
			if(!($field instanceof umiField)) return;
			
			if($guide_id = $field->getGuideId()) {
				if(cmsController::getInstance()->getCurrentMode() != "admin") {
					$guide_items = umiObjectsCollection::getInstance()->getGuidedItems($guide_id);
				} else {
					try {
						$sel = new selector('objects');
						$sel->types('object-type')->id($guide_id);
						$total = $sel->length;
					} catch (selectorException $e) {
						$total = 16;
					}
					
					
					if($total <= 15) {
						$guide_items = umiObjectsCollection::getInstance()->getGuidedItems($guide_id);
					} else {
						$fieldName = $field->getName();
						$guide_items = Array();
		
						if($object instanceof iUmiObject) {
							$val = $object->getValue($fieldName);
						} else {
							$val = false;
						}
	
						if($val && !is_array($val)) {
							$val = Array($val);
						}
	
						if(is_array($val)) {
								$objects = umiObjectsCollection::getInstance();
								foreach($val as $item_id) {
										$item = $objects->getObject($item_id);
										if($item instanceof iUmiObject) {
												$guide_items[$item_id] = $item->getName();
										}
										unset($item_id);
										unset($item);
								}
								unset($val);
						}
					}
				}
			} else {
				$guide_items = array();
			}
			
			if(sizeof($guide_items) == 0) {
				if($object instanceof iUmiObject) {
					$val = $object->getValue($field->getName());
					if($val && !is_array($val)) $val = array($val);
					if(sizeof($val)) {
						foreach($val as $itemId) {
							if($item = selector::get('object')->id($itemId)) {
								$guide_items[$itemId] = $item->name;
							}
						}
					}
				}
			}
			
			$xsl = xslTemplater::getInstance()->getIsInited();

		  $field_name = $field->getName();

		  list($template_block, $template_block_line, $template_block_line_a) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_field_relation_" . $field_name, "reflection_field_relation_option_" . $field_name, "reflection_field_relation_option_a_" . $field_name);
		  if(!$template_block){      
        list($template_block, $template_block_line, $template_block_line_a, $template_mul_block, $template_mul_block_line, $template_mul_block_line_a) = def_module::loadTemplates("tpls/data/reflection/{$template}.tpl", "reflection_field_relation", "reflection_field_relation_option", "reflection_field_relation_option_a", "reflection_field_multiple_relation", "reflection_field_multiple_relation_option", "reflection_field_multiple_relation_option_a");
      }
      
      
			$block_arr = Array();

			if($object) {
				$value = $object->getValue($field->getName());
			} else {
				$value = Array();
			}
			$fieldName = $field->getName();
			if ($fieldName == 'publish_status' && cmsController::getInstance()->getCurrentMode() != "admin") {	
				return "";
			}
			if($is_multiple) {
				$block_arr['attribute:name'] = $field_name;
				$block_arr['attribute:title'] = $field->getTitle();
				$block_arr['attribute:tip'] = $field->getTip();
				$block_arr['attribute:multiple'] = "multiple";
				
				if($guide_id = $field->getGuideId()) {
					$block_arr['attribute:type-id'] = $guide_id;
					
					$guide = umiObjectTypesCollection::getInstance()->getType($guide_id);
					if($guide instanceof umiObjectType) {
						if($guide->getIsPublic()) {
							$block_arr['attribute:public-guide'] = true;
						}
					}
				}


				$options = Array();
				foreach($guide_items as $item_id => $item_name) {
					$selected = (in_array($item_id, $value)) ? " selected" : "";
					
					$item_object = umiObjectsCollection::getInstance()->getObject($item_id);
					if(!is_object($item_object)) {
						continue;
					}

					if($item_object->getValue("is_hidden") && !$selected) {
						continue;
					}

					if($template_block_line || $xsl) {
						$line = ($selected) ? $template_mul_block_line_a : $template_mul_block_line;
						$line_arr = Array();
						$line_arr['attribute:id'] = $item_id;
						$line_arr['xlink:href'] = "uobject://" . $item_id;
						$line_arr['node:name'] = $item_name;

						if($selected) {
							$line_arr['attribute:selected'] = "selected";
						}

						$options[] = def_module::parseTemplate($line, $line_arr, false, $item_id);
					} else {
						$options .= "<option value=\"{$item_id}\"{$selected}>{$item_name}</option>\n";
					}
				}

				if($object) {
					$block_arr['void:object_id'] = $object->getId();
				}


				$block_arr['subnodes:values'] = $block_arr['void:options'] = $options;
				$block_arr['attribute:input_name'] = ($object) ? "data[" . $object->getId() . "][{$field_name}][]" : "data[new][{$field_name}][]";

				return def_module::parseTemplate($template_mul_block, $block_arr);
			} else {
				$field_name = $field->getName();
				$block_arr['attribute:name'] = $field_name;
				$block_arr['attribute:title'] = $field->getTitle();
				$block_arr['attribute:tip'] = $field->getTip();
				
				if($guide_id = $field->getGuideId()) {
					$block_arr['attribute:type-id'] = $guide_id;
					
					$guide = umiObjectTypesCollection::getInstance()->getType($guide_id);
					if($guide instanceof umiObjectType) {
						if($guide->getIsPublic()) {
							$block_arr['attribute:public-guide'] = true;
						}
					}
				}

				$options = "";
				foreach($guide_items as $item_id => $item_name) {
					$selected = ($item_id == $value) ? " selected" : "";

					$item_object = umiObjectsCollection::getInstance()->getObject($item_id);
					if(!is_object($item_object)) {
						continue;
					}

					if($item_object->getValue("is_hidden") && !$selected) {
						continue;
					}


					if($template_block_line || $xsl) {
						$line = ($selected) ? $template_block_line_a : $template_block_line;
						$line_arr = Array();
						$line_arr['attribute:id'] = $item_id;
						$line_arr['xlink:href'] = "uobject://" . $item_id;
						$line_arr['node:name'] = $item_name;
						if($selected) {
							$line_arr['attribute:selected'] = "selected";
						}

						$options[] = def_module::parseTemplate($line, $line_arr, false, $item_id);
					} else {
						$options .= "<option value=\"{$item_id}\"{$selected}>{$item_name}</option>\n";
					}
				}

				if($object) {
					$block_arr['void:object_id'] = $object->getId();
				}


				$block_arr['subnodes:values'] = $block_arr['void:options'] = $options;
				$block_arr['attribute:input_name'] = ($object) ? "data[" . $object->getId() . "][{$field_name}]" : "data[new][{$field_name}]";

				return def_module::parseTemplate($template_block, $block_arr);
			}
		}

TPL-шаблон в папке tpls/data/reflection/ должен быть примерно следующим:

<?php

$FORMS = Array();

$FORMS['reflection_fields'] = <<<END

<form method="post" action="%pre_lang%/data/addNewObject/%object_type_id%/" enctype="multipart/form-data" >

<table border="0" width="500">
	%fields%
</table>
<input type="hidden" name="parent" value="%parent_id%" />
<input type="hidden" name="active" value="0" />
<input type="hidden" name="system_template" value="%template%" />
<input type="hidden" name="fields" value="%fields_arr%" />
<input type="submit" />

</form>

END;

$FORMS['reflection_field_string_h1'] = <<<END
  
	<tr>
		<td>
			%title%:
		</td>

		<td>
			<input type="text" name="%input_name%" value="%value%" size="50" />
		</td>
	</tr>

END;

$FORMS['reflection_field_string'] = <<<END
  
	<tr>
		<td>
			%title%:
		</td>

		<td>
			<input type="text" name="%input_name%" value="%value%" size="50" />
		</td>
	</tr>

END;

$FORMS['reflection_field_string_title'] = <<<END
	<tr>
		<td>
			%title%:
		</td>

		<td>
			<input type="text" name="%input_name%" value="%value%" size="50" />
		</td>
	</tr>

END;

?>

Примеры вызовов макросов:

%data getEditFormCustom('editpage', 'h1 photo vid menu_pic_ua')%
%data getCreateFormCustom(827, 'newpage', 'title h1 druzhelyubnost photo menu_pic_ua', 45)%