Example #1
0
 /**
  * Test adding an element to a form
  */
 public function testAdd_Element()
 {
     $element = $this->getMockBuilder('Jasny\\FormBuilder\\Element')->getMockForAbstractClass();
     $form = $this->form->add($element);
     $this->assertSame($this->form, $form);
     $this->assertContains($element, $this->form->getElements());
     $this->assertSame($this->form, $element->getParent());
 }
Example #2
0
 public static function setColumnCount(Form $form)
 {
     $elements = $form->getElements();
     foreach ($elements as $element) {
         if (method_exists($element, 'getColumnsCount') && method_exists($element, 'setColumnCount')) {
             if ($element->getColumnsCount() > 2) {
                 $element->setColumnCount(2);
             }
         }
     }
 }
Example #3
0
 /**
  * @covers Xoops\Form\Form::getElements
  */
 public function testGetElements()
 {
     $button = new Button('button_caption', 'button_name');
     $this->object->addElement($button, true);
     $value = $this->object->getElements();
     $this->assertTrue(is_array($value));
     $this->assertInstanceOf('Xoops\\Form\\Button', $value[0]);
     $value = $this->object->getElementNames();
     $this->assertTrue(is_array($value));
     $this->assertSame('button_name', $value[0]);
     $value = $this->object->getElementByName('button_name');
     $this->assertInstanceOf('Xoops\\Form\\Button', $value);
     $value = $this->object->getElementByName('button_doesnt_exist');
     $this->assertSame(null, $value);
 }
 public static function ConfigureSave(Form $form)
 {
     foreach ($form->getElements() as $el) {
         /** @var $el FormElement */
         $n = $el->get('name');
         // I only want config options here.
         if (strpos($n, 'config[') !== 0) {
             continue;
         }
         // Trim off the "config[]" wrapper.
         $k = substr($n, 7, -1);
         ConfigHandler::Set($k, $el->get('value'));
     }
     \Core\set_message('Saved configuration options', 'success');
     return true;
 }
 public static function SpamKeywordsSave(Form $form)
 {
     ConfigHandler::Set('/security/spam_threshold', $form->getElementValue('threshold'));
     foreach ($form->getElements() as $el) {
         /** @var FormElement $el */
         $n = $el->get('name');
         if (strpos($n, 'score[') === 0) {
             $n = substr($n, 6, -1);
             $s = $el->get('value');
             if ($s == '') {
                 $s = 1;
             }
             $model = SpamHamKeywordModel::Construct($n);
             $model->set('score', $s);
             $model->save();
         }
     }
     if ($form->getElementValue('new_keyword')) {
         $n = $form->getElementValue('new_keyword');
         $s = $form->getElementValue('new_score');
         if ($s == '') {
             $s = 1;
         }
         $model = SpamHamKeywordModel::Construct($n);
         $model->set('score', $s);
         $model->save();
     }
     return true;
 }
Example #6
0
	/**
	 * Set properties on this model from a form object, optionally with a specific prefix.
	 *
	 * @param Form        $form   Form object to pull data from
	 * @param string|null $prefix Prefix that all keys should be matched to, (optional)
	 */
	public function setFromForm(Form $form, $prefix = null){

		// Get every "prefix[...]" element, as they key up 1-to-1.
		$els = $form->getElements(true, false);
		foreach ($els as $e) {
			// If a specific prefix was requested and this element does not match up, skip it!
			if ($prefix){
				if(!preg_match('/^' . $prefix . '\[(.*?)\].*/', $e->get('name'), $matches)) continue;
				$key = $matches[1];
			}
			else{
				$key = $e->get('name');
			}

			$val    = $e->get('value');
			$schema = $this->getKeySchema($key);

			// If there is no schema entry for this key, no reason to try to set it as it doesn't exist in the Model.
			if(!$schema) continue;

			$this->set($key, $val);
		}
	}
 public static function ImagesUpdateSaveHandler(Form $form)
 {
     try {
         /** @var $image GalleryImageModel */
         $image = $form->getModel('image');
     } catch (Exception $e) {
         Core::SetMessage($e->getMessage(), 'error');
         return false;
     }
     $metas = new \Core\Filestore\FileMetaHelper($image->getOriginalFile());
     // Set the meta information from the form.
     foreach ($form->getElements() as $el) {
         /** @var $el FormElement */
         $name = $el->get('name');
         if (strpos($name, 'metas[') !== 0) {
             continue;
         }
         $name = substr($name, 6, -1);
         $metas->setMeta($name, $el->get('value'));
     }
     // If no title was set, I need to pick one by default.
     if (!$metas->getMetaTitle('title')) {
         // Generate a moderately meaningful title from the filename.
         $title = $image->getOriginalFile()->getBasename(true);
         $title = preg_replace('/[^a-zA-Z0-9 ]/', ' ', $title);
         $title = trim(preg_replace('/[ ]+/', ' ', $title));
         $title = ucwords($title);
         $metas->setMeta('title', $title);
     }
     if (!$image->exists()) {
         // Figure out the largest weight of this album.
         // Note, this is NOT the size of the images, as one or more may have been deleted after uploading.
         $last = GalleryImageModel::Find(array('albumid' => $image->get('albumid')), 1, 'weight DESC');
         $weight = $last ? $last->get('weight') : 0;
         $image->set('weight', $weight);
     }
     // Don't forget to keep the metatags in sync!
     $image->set('title', $metas->getMetaTitle('title'));
     $action = $image->exists() ? 'Updated' : 'Added';
     $image->save();
     Core::SetMessage($action . ' image successfully!', 'success');
     return true;
 }
 public static function SaveSiteSkins(Form $form)
 {
     foreach ($form->getElements() as $el) {
         /** @var FormElement $el */
         $n = $el->get('name');
         $v = $el->get('value');
         if (strpos($n, 'config[') === 0) {
             $k = substr($n, 7, -1);
             ConfigHandler::Set($k, $v);
         }
     }
     return true;
 }
	public static function _i18nSaveHandler(Form $form) {
		
		// NEW IDEA!
		// Instead of setting the override for keys, (possibly useful, just somewhere else)...
		// Set the enabled languages for this site.
		// This allows site administrators to NOT have every language under the sun appear if they're running SuSE.
		$selected = $form->getElement('languages[]')->get('value');
		
		// Implode them into a single string.
		$enabled = implode('|', $selected);
		// Strip out any invalid character.
		$enabled = preg_replace('/[^a-zA-Z_|]/', '', $enabled);
		
		// And save!
		ConfigHandler::Set('/core/language/languages_enabled', $enabled);
		return true;
		
		// Create a custom ini for just these options.
		// This will allow the site admin to change a string without worrying about it getting overridden from an update.

		$lang = $form->getElementValue('lang');
		$ini = "[$lang]\n; Custom locale strings set by the site manager!\n\n";

		foreach($form->getElements() as $el){
			/** @var FormElement $el */

			$name = $el->get('name');
			$val  = $el->get('value');

			if(strpos($name, 'MESSAGE') === 0 || strpos($name, 'FORMAT') === 0 || strpos($name, 'STRING') === 0){
				$ini .= $name . ' = "' . str_replace('"', '\\"', $val) . '";' . "\n";
			}
		}

		// Save this ini out to a custom i18n file.
		$fileout = \Core\Filestore\Factory::File(ROOT_PDIR . 'themes/custom/i18n/' . $lang . '.ini');
		$fileout->putContents($ini);

		\Core\set_message('t:MESSAGE_SUCCESS_UPDATED_TRANSLATION_STRINGS');
		return true;
	}
Example #10
0
	/**
	 * Handler to actually perform the import.
	 *
	 * @param \Form $form
	 * @return bool
	 */
	public static function FormHandler2(\Form $form) {
		$filename = Session::Get('user-import/file');
		$file = Factory::File($filename);
		/** @var $contents \Core\Filestore\Contents\ContentCSV */
		$contents = $file->getContentsObject();

		// If the user checked that it has a header... do that.
		$contents->_hasheader = $form->getElement('has_header')->get('checked');

		// Merge
		$merge = $form->getElement('merge_duplicates')->get('checked');

		// Handle the map-to directives.
		$maptos = array();
		foreach($form->getElements() as $el){
			if(strpos($el->get('name'), 'mapto[') === 0 && $el->get('value')){
				$k = substr($el->get('name'), 6, -1);
				$maptos[$k] = $el->get('value');
			}
		}

		// Handle the group mappings
		$groups = $form->getElement('groups[]')->get('value');

		// And keep a log of the bad transfers and some other data.
		$counts = ['created' => 0, 'updated' => 0, 'failed' => 0, 'skipped' => 0];
		Session::Set('user-import/fails', []);

		$incoming = $contents->parse();
		foreach($incoming as $record){
			try{
				// Create a data map of this record for fields to actually map over.
				$dat = array();
				foreach($maptos as $recordkey => $userkey){
					$dat[$userkey] = $record[$recordkey];
				}

				// No email, NO IMPORT!
				if(!$dat['email']){
					$counts['skipped']++;
					continue;
				}

				// Try to find this record by email, since that's a primary key.
				$existing = \UserModel::Find(['email = ' . $dat['email'] ], 1);
				if($existing && !$merge){
					// Skip existing records.
					$counts['skipped']++;
				}
				elseif($existing){
					// Update!
					$existing->setFromArray($dat);
					$existing->setGroups($groups);

					if($existing->save()){
						$counts['updated']++;
					}
					else{
						$counts['skipped']++;
					}
				}
				else{
					$new = new \UserModel();
					$new->setFromArray($dat);
					$new->setGroups($groups);
					$new->save();
					$counts['created']++;
				}
			}
			catch(\Exception $e){
				// @todo Handle this
				die($e->getMessage());
			}
			//
		}

		Session::Set('user-import/counts', $counts);

		return true;
	}
 /**
  * Save handler for the form_metadata page.
  *
  * @param Form $form
  */
 public static function FileMetadataSaveHandler(Form $form)
 {
     $filename = $form->getElement('file')->get('value');
     $file = \Core\Filestore\Factory::File($filename);
     $helper = new \Core\Filestore\FileMetaHelper($file);
     // Run through each element and save its metadata to the table.
     foreach ($form->getElements() as $el) {
         /** @var $el FormElement */
         $name = $el->get('name');
         if ($name == 'file') {
             continue;
         }
         if ($name == '___formid') {
             continue;
         }
         if ($name == 'submit') {
             continue;
         }
         $helper->setMeta($name, $el->get('value'));
     }
     return true;
 }
	public static function _CreateUpdateHandler(Form $form){
		$baseurl = $form->getElement('baseurl')->get('value');

		$model = new WidgetModel($baseurl);
		$model->set('editurl', '/admin/widget/update?baseurl=' . $baseurl);
		$model->set('deleteurl', '/admin/widget/delete?baseurl=' . $baseurl);
		$model->set('title', $form->getElement('title')->get('value'));

		$elements = $form->getElements();
		foreach($elements as $el){
			/** @var FormElement $el */
			if(strpos($el->get('name'), 'setting[') === 0){
				$name = substr($el->get('name'), 8, -1);
				$model->setSetting($name, $el->get('value'));
			}
		}
		$model->save();

		return 'back';
	}
Example #13
0
File: Form.php Project: itav/form
 /**
  * @param Form | FieldSet $obj
  */
 private function deleteSubmits($obj)
 {
     $elements = $obj->getElements();
     if (!is_array($elements)) {
         return;
     }
     if (count($elements) <= 0) {
         return;
     }
     foreach ($elements as $key => $element) {
         if ($element instanceof Input && $element->getType() === Input::TYPE_SUBMIT) {
             $obj->delElement($key);
         }
         if (isset($element) && $element instanceof Button && $element->getType() === Button::TYPE_SUBMIT) {
             $obj->delElement($key);
         }
         if (isset($element) && $element instanceof FieldSet) {
             $this->deleteSubmits($element);
         }
     }
     $obj->reindexElements();
 }
Example #14
0
 public static function forming(Form $form)
 {
     $output = "";
     $output .= "<" . $form->getBalise();
     foreach ($form->getAttributes() as $k => $v) {
         $output .= " {$k}=\"{$v}\"";
     }
     $output .= ">";
     foreach ($form->getElements() as $v) {
         $output .= static::process_form_elements($v);
     }
     $output .= "</" . $form->getBalise() . ">";
     return $output;
 }
Example #15
0
	/**
	 * Populate this user object from a form
	 *
	 * @param Form $form
	 * @param null $prefix
	 *
	 * @return bool
	 * @throws ModelValidationException
	 */
	public function setFromForm(Form $form, $prefix = null) {
		foreach($form->getElements() as $el) {
			/** @var $el FormElement */

			$name  = $el->get('name');
			$value = $el->get('value');

			// If a prefix was requested and it doesn't match, skip this element.
			if($prefix && strpos($name, $prefix . '[') !== 0){
				continue;
			}

			// Otherwise if there is a prefix, trim it off from the name.
			if($prefix) {
				// Some of the options may be nested arrays, they'll need to be treated differently since the format is different,
				// prefix[option][phone] vs prefix[email]
				if(strpos($name, '][')) {
					$name = str_replace('][', '[', substr($name, strlen($prefix) + 1));
				}
				else {
					$name = substr($name, strlen($prefix) + 1, -1);
				}
			}


			if($name == 'groups[]') {
				$this->setGroups($value);
			}
			elseif($name == 'contextgroup[]') {
				// This is a two-part system with data pulling from contextgroup and contextgroupcontext.
				$gids       = $value;
				$contextpks = $form->getElement('contextgroupcontext[]')->get('value');
				$groups     = [];

				foreach($gids as $key => $gid) {
					// Skip blank group selections.
					if(!$gid) continue;

					// Pull the group information for this gid since that will contain the context.
					$group = UserGroupModel::Construct($gid);

					$context   = $group->get('context');
					$contextpk = $contextpks[ $key ];

					$groups[] = [
						'group_id'   => $gid,
						'context'    => $context,
						'context_pk' => $contextpk,
					];
				}

				$this->setContextGroups($groups);
			}
			elseif($name == 'active'){
				$current = $this->get('active');
				// The incoming value will probably be 'on' or NULL.
				// This is because the form displays as a BOOL even though the backend field is an ENUM.
				$new = ($value) ? '1' : '0';
				
				// -1 => 0 = -1 (Disabled to unchecked, no change)
				// -1 => 1 =  1 (Disabled to checked, activate)
				//  0 => 0 =  0 (New to unchecked, wot?)
				//  0 => 1 =  1 (New to checked, activate... still shouldn't happen though)
				//  1 => 0 = -1 (Enabled to unchecked, disable)
				//  1 => 1 =  1 (Enabled to checked, no change)
				
				if($current == '1' && $new == '0'){
					// User was set from active to inactive.
					// Instead of setting to a new account, set to deactivated.
					$this->set('active', '-1');
				}
				elseif($current == '-1' && $new == '0'){
					// No change!
				}
				else{
					// Otherwise, allow the change to go through.
					$this->set('active', $new);
				}
			}
			elseif($name != 'user'){
				// Skip the user record,
				// otherwise Default behaviour
				$this->set($name, $value);
			}
		} // foreach(elements)
	}