Example #1
0
 public function getView($params, $synchrone)
 {
     $form = new Form($this->fields, $params);
     $title = '';
     if ($form->isSubmitting() && Tools::isEmpty($form->getErrors())) {
         $access_key = isset($params['access_key']) && !empty($params['access_key']) ? Tools::saltHash($params['access_key']) : 'NULL';
         // Create Game
         $game = Game::create(F::i('Session')->getMid(), $params['name'], $access_key);
         Tools::redirect('?action=wait_game&game=' . $game->g_id);
     } else {
         // Generate form
         $view = View::setFile('formular', View::HTML_FILE);
         $errors = $form->getErrors();
         // Errors in the filling
         if (!empty($errors)) {
             $view->setSwitch('form_errors', TRUE);
             foreach ($errors as $field => $error) {
                 $view->setGroupValues('form_errors', array('error' => F::i('Lang')->getKey('error_' . $field . '_' . $error)));
             }
         }
         $view->setValue('form', $form->getHTML(F::i('Lang')->getKey('Create'), '#', 'POST', 'tabbed_form'));
         $title = F::i('Lang')->getKey('title_new_game');
     }
     return parent::setBody($view, $title);
 }
Example #2
0
 public function getView($params, $synchrone)
 {
     $form = new Form(self::getFields(), $params);
     $view = View::setFile('chatbox', View::JSON_FILE);
     $fields = Chatbox::getFields();
     if (F::i('Session')->isConnected()) {
         $fields['name']['disabled'] = TRUE;
     }
     $errors = $form->getErrors();
     if (!Tools::isEmpty($errors)) {
         foreach ($errors as $field => $msg) {
             $view->setGroupValues('error', array('field' => $field, 'errmsg' => $msg));
         }
     }
     // If Submitting
     if ($form->isSubmitting() && Tools::isEmpty($form->getErrors())) {
         // TODO Sauvegarde du pseudo en cookie
         // Enregistrement des données
         if (F::i('Session')->isConnected()) {
             $m_name = '';
         } else {
             $m_name = $params['name'];
             self::setNickname($m_name);
         }
         F::i(_DBMS_SYS)->exec('INSERT INTO !prefix_chatbox_messages (m_id, m_name, mes_content) VALUES (?, ?, ?)', array(F::i('Session')->getMid(), $m_name, $params['content']));
         // Et sortie
         return;
     }
     // Recuperation des derniers messages
     $sql = 'SELECT mes.m_name, m.m_login, mes.m_id, mes_content, UNIX_TIMESTAMP(mes_date) AS mes_date FROM !prefix_chatbox_messages mes, !prefix_members m WHERE m.m_id = mes.m_id';
     $array = array();
     // si une date est donnée, tous les messages depuis cette date
     if (isset($params['since'])) {
         $sql .= ' AND mes_date > FROM_UNIXTIME(?)';
         $array[] = $params['since'];
     }
     // sinon, limiter à _LIMIT_LAST_CHATBOX messages
     $sql .= ' ORDER BY mes_date DESC';
     if (!isset($params['since'])) {
         $sql .= ' LIMIT ?';
         $array[] = _LIMIT_LAST_CHATBOX;
     }
     // Generation d'un pseudo si non connecté et pseudo non fourni
     // Si connecté, verouiller le pseudo
     $result = F::i(_DBMS_SYS)->query($sql, $array);
     // Recover messages and switch the order to get the last _LIMIT_LAST_CHATBOX messages but the last at the end.
     $messages = array();
     for ($i = 0; $i < $result->getNumRows(); $i++) {
         $obj = $result->getObject();
         $messages[] = array('author_mid' => $obj->m_id, 'author_name' => $obj->m_id == _ID_VISITOR ? $obj->m_name : $obj->m_login, 'content' => htmlentities($obj->mes_content, ENT_QUOTES, 'UTF-8', TRUE), 'date' => $obj->mes_date);
     }
     $messages = array_reverse($messages);
     for ($i = 0; $i < count($messages); $i++) {
         $view->setGroupValues('message', $messages[$i]);
     }
     return $view->getContent();
 }
 /**
  * @return ModelAndView
  **/
 public function run(Prototyped $subject, Form $form, HttpRequest $request)
 {
     $form->markGood('id');
     if (!$form->getErrors()) {
         FormUtils::form2object($form, $subject);
         return parent::run($subject, $form, $request);
     }
     return new ModelAndView();
 }
 /**
  * @return ModelAndView
  **/
 public function run(Prototyped $subject, Form $form, HttpRequest $request)
 {
     if (!$form->getErrors()) {
         ClassUtils::copyProperties($form->getValue('id'), $subject);
         FormUtils::form2object($form, $subject, false);
         return parent::run($subject, $form, $request);
     }
     return new ModelAndView();
 }
Example #5
0
 public function scanCodeLoginAction()
 {
     $form = new Form(['scanCode' => null]);
     if ($form->wasSent()) {
         $form->scanCode->hasValue('Bitte scannen Sie einen validen Code ein')->validate($this->db->hasUserByScanCode($form->scanCode->getString()), 'Der übergebene Scan Code ist keinem Benutzer zugeordnet');
         if (!$form->hasErrors()) {
             $user = $this->db->getUserByScanCode($form->scanCode->getString());
             $_SESSION['userId'] = intval($user->id);
             return ['success' => true, 'user' => ['name' => $user->name, 'scanCode' => $user->scan_code], 'errors' => []];
         }
     }
     return ['success' => false, 'errors' => $form->getErrors(true)];
 }
Example #6
0
 public function getView($params, $synchrone)
 {
     $form = new Form($this->fields, $params);
     if ($form->isSubmitting() && Tools::isEmpty($form->getErrors())) {
         // Register
         $salt = Tools::generateSalt();
         $password = Tools::saltHash($params['password'], $salt);
         $error = FALSE;
         try {
             F::i(_DBMS_SYS)->exec('INSERT INTO !prefix_members (m_login, m_password, m_email, m_salt, m_auth) VALUES (?, ?, ?, ?, ?)', array($params['login'], $password, $params['email'], $salt, _AUTH_MEMBER));
         } catch (DBMSError $e) {
             // Login already given
             $error = TRUE;
         }
         if (!$error) {
             $view = View::setFile('info', View::HTML_FILE);
             $view->setValue('L_message', F::i('Lang')->getKey('register_successful'));
             $view->setValue('U_ok', '?');
             F::i('Session')->connect($params['login'], $params['password']);
         } else {
             $view = View::setFile('error', View::HTML_FILE);
             $view->setValue('l_message', F::i('Lang')->getKey('login_taken'));
             $view->setValue('u_ok', '?');
         }
     } else {
         $view = View::setFile('formular', View::HTML_FILE);
         $errors = $form->getErrors();
         // Errors in the filling
         if (!empty($errors)) {
             $view->setSwitch('form_errors', TRUE);
             foreach ($errors as $field => $error) {
                 $view->setGroupValues('form_errors', array('error' => F::i('Lang')->getKey('error_' . $field . '_' . $error)));
             }
         }
         $view->setValue('form', $form->getHTML(F::i('Lang')->getKey('register'), '#', 'POST', 'tabbed_form'));
     }
     return parent::setBody($view);
 }
 static function dumpErrors(Form $form)
 {
     if (!$form->hasErrors()) {
         return '';
     }
     $s = '<ul>';
     foreach ($form->getErrors() as $id => $error) {
         $s .= '<li>' . $id . ': ' . $error . '</li>';
     }
     foreach ($form->getControls() as $control) {
         $s .= self::dumpControlError($control);
     }
     $s .= '</ul>';
     return $s;
 }
Example #8
0
 /**
  * Renders validation errors (per form or per control).
  * @param  IFormControl
  * @return string
  */
 public function renderErrors(IFormControl $control = NULL)
 {
     $errors = $control === NULL ? $this->form->getErrors() : $control->getErrors();
     if (count($errors)) {
         $ul = $this->getWrapper('error container');
         $li = $this->getWrapper('error item');
         foreach ($errors as $error) {
             $item = clone $li;
             if ($error instanceof Html) {
                 $item->add($error);
             } else {
                 $item->setText($error);
             }
             $ul->add($item);
         }
         return "\n" . $ul->render(0);
     }
 }
Example #9
0
 /**
  * Returns a string representation of all form errors (including children errors).
  *
  * This method should only be used in ajax calls.
  *
  * @param Form $form         The form to parse
  * @param bool $withChildren Do we parse the embedded forms
  *
  * @return string A string representation of all errors
  */
 public function getRecursiveReadableErrors($form, $withChildren = true, $translationDomain = null, $level = 0)
 {
     $errors = '';
     $translationDomain = $translationDomain ? $translationDomain : $form->getConfig()->getOption('translation_domain');
     //the errors of the fields
     foreach ($form->getErrors() as $error) {
         //the view contains the label identifier
         $view = $form->createView();
         $labelId = $view->vars['label'];
         //get the translated label
         if ($labelId !== null) {
             $label = $this->translator->trans($labelId, [], $translationDomain) . ' : ';
         } else {
             $label = '';
         }
         //in case of dev mode, we display the item that is a problem
         //getCause cames in Symfony 2.5 version, this is just a fallback to avoid BC with previous versions
         if ($this->debug && method_exists($error, 'getCause')) {
             $cause = $error->getCause();
             if ($cause !== null) {
                 $causePropertyPath = $cause->getPropertyPath();
                 $errors .= ' ' . $causePropertyPath;
             }
         }
         //add the error
         $errors .= $label . $this->translator->trans($error->getMessage(), [], $translationDomain) . "\n";
     }
     //do we parse the children
     if ($withChildren) {
         //we parse the children
         foreach ($form->getIterator() as $child) {
             $level++;
             if ($err = $this->getRecursiveReadableErrors($child, $withChildren, $translationDomain, $level)) {
                 $errors .= $err;
             }
         }
     }
     return $errors;
 }
Example #10
0
 /**
  * Performs the form validation workflow.
  *
  * @param string $submit_button
  * @param string $form_config
  * @param array $default_fields
  * @return null if no submit sent. True if validated correctly, false otherwise.
  */
 protected function getValidatedForm($submit_button, $form_config, $default_fields = array())
 {
     $post = FilterPost::getInstance();
     $form = new Form($post, $this->view);
     if ($post->isSent($submit_button)) {
         $return = $form->validateElements($form_config);
         if ($return) {
             $return = $form;
         }
     } else {
         $form->addFields($default_fields);
         $return = null;
     }
     $this->assign('form_values', $form->getFields());
     $this->assign('requirements', $form->getRequirements($form_config));
     $this->assign('error', $form->getErrors());
     return $return;
 }
Example #11
0
    public function getView($params, $synchrone)
    {
        $search_form = new Form($this->search_fields, $params);
        $access_form = new Form($this->access_fields, $params);
        $title = '';
        $insert = TRUE;
        try {
            if (!isset($params['game'])) {
                throw new Exception('No Game given');
            }
            $game = new Game($params['game']);
            if ($game->isIn(F::i('Session')->getMid())) {
                throw new Exception('Already In');
            }
        } catch (Exception $e) {
            $insert = FALSE;
        }
        if ($insert) {
            if ($game->g_access_key == 'NULL' || $access_form->isSubmitting() && Tools::isEmpty($access_form->getErrors()) && $game->g_access_key == Tools::saltHash($params['access_key'])) {
                $game->insert(F::i('Session')->getMid());
                Tools::redirect('?action=wait_game&game=' . $game->g_id);
            } else {
                // CHECK
                if ($access_form->isSubmitting()) {
                    // Error
                    die('bad access key');
                } else {
                    $view = View::setFile('formular', View::HTML_FILE);
                    $errors = $access_form->getErrors();
                    // Errors in the filling
                    if (!empty($errors)) {
                        $view->setSwitch('form_errors', TRUE);
                        foreach ($errors as $field => $error) {
                            $view->setGroupValues('form_errors', array('error' => F::i('Lang')->getKey('error_' . $field . '_' . $error)));
                        }
                    }
                    $view->setValue('form', $access_form->getHTML(F::i('Lang')->getKey('access_key'), '#', 'POST', 'tabbed_form'));
                }
            }
        } else {
            $sql = 'SELECT g.g_id, g_name, TIMESTAMPDIFF(HOUR, g_start, NOW()) AS lifetime, COUNT(*) AS g_total_players, m_login AS g_owner 
					FROM !prefix_members m, !prefix_games AS g, !prefix_players AS p 
					WHERE g.m_id = m.m_id 
						AND p.g_id = g.g_id 
						AND g.g_id NOT IN (
							SELECT g_id FROM !prefix_players WHERE m_id = ?
						)';
            $array = array(F::i('Session')->getMid());
            // If search is defined, add condition
            if (isset($params['search'])) {
                $sql .= ' AND g_name LIKE ?';
                $array[] = '%' . $params['search'] . '%';
            }
            $sql .= ' GROUP BY g.g_id ORDER BY g_start DESC';
            // Get all the games
            $result = F::i(_DBMS_SYS)->query($sql, $array);
            $view = View::setFile('list_games', View::HTML_FILE);
            $view->setValue('form', $search_form->getHTML('', '#', 'POST', 'inline'));
            if ($result->getNumRows() == 0) {
                $view->setSwitch('no_games', TRUE);
            }
            for ($i = 0; $i < $result->getNumRows(); $i++) {
                $obj = $result->getObject();
                $view->setGroupValues('games', array('link' => '?action=join_game&game=' . $obj->g_id, 'name' => stripslashes($obj->g_name), 'total_players' => $obj->g_total_players, 'owner' => $obj->g_owner, 'lifetime' => $obj->lifetime));
            }
            $title = F::i('Lang')->getKey('title_join_game');
        }
        return parent::setBody($view);
    }
Example #12
0
 public function testValidationFail()
 {
     $this->object->submit(array('test_check' => null, 'test_textarea' => null));
     $this->assertFalse($this->object->validate());
     $this->assertEquals(2, count($this->object->getErrors()));
 }
Example #13
0
 public function testEach()
 {
     $form = new Form(array('list' => array('each' => array('min_length' => 1, 'max_length' => 4))));
     $this->assertTrue($form->validate(array('list' => array('a', 'b', 'c'))));
     $this->assertEquals(array('list' => array('a', 'b', 'c')), $form->getValues());
     $form->setValues(array());
     $this->assertTrue($form->validate(array('garbage' => 'garbage')));
     $this->assertEquals(array('list' => array()), $form->getValues(), 'List is set and casted to array when missing');
     $form->setValues(array());
     $this->assertFalse($form->validate(array('list' => 'garbage')), 'When not an array, auto casted to an array');
     $this->assertEquals(array('max_length' => 4), $form->getErrors('list'));
     $form->setValues(array());
     $this->assertFalse($form->validate(array('list' => array('garbage'))), 'When not an array, does not validate');
     $this->assertEquals(array('max_length' => 4), $form->getErrors('list'));
     // with required = false and allow_empty = false
     $form->setValues(array());
     $this->assertTrue($form->validate(array('list' => array()), array('allow_empty' => false)));
     // with required = true
     $form = new Form(array('list' => array('required' => true, 'each' => array())));
     $this->assertTrue($form->validate(array('list' => 'garbage')));
     $this->assertEquals(array('list' => array('garbage')), $form->getValues(), 'Original value is casted to an array');
     $form->setValues(array());
     $this->assertFalse($form->validate(array('list' => array())), 'Empty array does not pass required = true');
     $form->setValues(array());
     $this->assertFalse($form->validate(array('garbage' => 'garbage')));
     $this->assertEquals(array('list' => array()), $form->getValues(), 'List is set and casted to array, when required and empty');
     // used with is_array
     $form = new Form(array('list' => array('is_array', 'each' => array('min_length' => 1, 'max_length' => 4))));
     $this->assertFalse($form->validate(array('list' => 'garbage')), 'When not an array, does not validate');
     $this->assertEquals(array('is_array' => true), $form->getErrors('list'));
     $this->assertEquals(array('list' => 'garbage'), $form->getValues(), 'Original value is not casted to an array when is_array is used');
     // with required = true inside the each
     $form = new Form(array('list' => array('each' => array('required' => true))));
     $this->assertTrue($form->validate(array('list' => array())), 'Ok for an empty array');
     $form->setValues(array());
     $this->assertFalse($form->validate(array('list' => array(''))), 'Not of for an empty array with a empty string');
     $this->assertEquals(array('required' => true), $form->getErrors('list'));
 }
Example #14
0
		width: 8em;
		text-align: right;
	}
	-->
	</style>
</head>

<body>
	<h1>Nette\Forms example 1</h1>

	<?php 
$form->render('begin');
?>

	<?php 
if ($form->getErrors()) {
    ?>
	<p>Opravte chyby:</p>
	<?php 
    $form->render('errors');
    ?>
	<?php 
}
?>

	<fieldset>
		<legend>Personal data</legend>
		<table>
		<tr class="required">
			<th><?php 
echo $form['name']->label;
Example #15
0
$form->add('Textarea', 'message')->setLabel('Message')->cols('54%')->rows(7)->setMinLength(10);
$form->add('SubmitButton', 'Envoyer')->addClass('button');
/**
*
*   Traitement du formulaire de contact
*
**/
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $form->bound($_POST);
    if ($form->isValid()) {
        echo 'valid form<br />';
        var_dump($_POST);
    } else {
        echo 'erreur !<br />';
        echo '<pre>';
        var_dump($form->getErrors());
        var_dump($_POST);
        echo '</pre>';
    }
}
?>
<html>
<head>
    <title>Page de test</title>
</head>
<body>
<h1>Test</h1>
<p>
    <?php 
echo $form;
?>
Example #16
0
 protected function editObject(Model $oObject, $template = '')
 {
     $form = new Form();
     if ($_POST) {
         $this->save($oObject);
         $this->assign('updates', $this->updates);
         $this->assign('errors', $form->getErrors());
     }
     $fields = $oObject->getTableStructure();
     $isSetting = false;
     if ($oObject instanceof Setting) {
         $isSetting = true;
         $this->readOnlyFields[] = 'name';
         $this->readOnlyFields[] = 'info';
     }
     foreach ($fields as $fieldName => $field) {
         if ($isSetting && $fieldName == 'value') {
             $settingType = str_replace('BOOLEAN', 'tinyint(1)', $settingType);
             $settingType = str_replace('INTEGER', 'VARCHAR', $settingType);
             $settingType = str_replace('FLOAT', 'VARCHAR', $settingType);
             $field['Type'] = strtolower($settingType);
         }
         if (!is_numeric($fieldName) && !in_array($fieldName, $this->hideFields)) {
             $value = $oObject->{$fieldName};
             $fieldTable = convertDbFieldToTable($fieldName);
             if ($fieldName != 'nefub_id' && substr($fieldName, -3, 3) == '_id') {
                 // left join
                 if (substr($fieldName, -9, 9) == '_nefub_id') {
                     // left join on nefub_id
                     $split = explode('_nefub_id', $fieldName);
                     $valueField = 'nefub_id';
                 } else {
                     // left join on id
                     $split = explode('_id', $fieldName);
                     $valueField = 'id';
                 }
                 $fieldTable = convertDbFieldToTable($fieldName);
                 if ($fieldTable == 'Game') {
                     $input = new GameDropdown($fieldName, $value, $oObject->getGame());
                 } elseif ($fieldTable == 'Team') {
                     $input = new TeamDropdown($fieldName, $value);
                 } elseif ($fieldTable == 'Location') {
                     $input = new LocationDropdown($fieldName, $value);
                 } else {
                     $input = new ModelDropdown($fieldName, $value, $fieldTable, $valueField);
                 }
             } else {
                 if (substr(strtolower($field['Type']), 0, 4) == 'enum') {
                     $input = new EnumDropdown($fieldName, $value, $field['Type']);
                     if ($isSetting) {
                         $settingType = $value;
                     }
                 } else {
                     if ($fieldName != 'nefub_id' && substr($field['Type'], 0, 3) == 'int') {
                         $length = substr($field['Type'], 4, strlen($field['Type']) - 2);
                         if ($length >= 5) {
                             $input = new InputText($fieldName, $value);
                             $input->addValidator(new IntegerValidator(true, 0, pow(10, $length)));
                         } else {
                             $input = new NumericDropdown($fieldName, $value, 0, pow(10, $length) - 1);
                         }
                     } else {
                         if ($fieldName == 'Period') {
                             $values = array(1 => 1, 2 => 2, 3 => 3);
                             $input = new RadioButton($fieldName, $values, $value);
                         } else {
                             if ($field['Type'] == 'int(1)' || $field['Type'] == 'tinyint(1)') {
                                 $input = new RadioBoolean($fieldName, $value);
                             } else {
                                 if ($field['Type'] == 'time' && $oObject->getTable() != 'GameAction') {
                                     $input = new Dropdown($fieldName, $value);
                                     for ($i = 0; $i < 24; $i++) {
                                         $hour = $i;
                                         if ($hour < 10) {
                                             $hour = '0' . $hour;
                                         }
                                         for ($j = 0; $j < 60; $j += 10) {
                                             $minute = $j;
                                             if ($minute < 10) {
                                                 $minute = '0' . $minute;
                                             }
                                             $time = $hour . ':' . $minute;
                                             $input->addOption($time, $time . ':00');
                                         }
                                     }
                                 } elseif ($field['Type'] == 'text') {
                                     $input = new TextArea($fieldName, $value);
                                 } else {
                                     $input = new InputText($fieldName, $value);
                                 }
                             }
                         }
                     }
                 }
             }
             // read-only fields
             if (in_array($fieldName, $this->readOnlyFields)) {
                 $input->setExtraAttribute('disabled', 'disabled');
             }
             if ($field['Null'] == 'NO') {
                 $input->addValidator(new Validator());
             }
             $form->addElement($input, $fieldName);
         }
     }
     $this->assign('form', $form);
     $this->assign('subject', $this->subject);
     $this->assign('backUrl', '/' . $this->subject);
     $this->assign('o' . get_class($oObject), $oObject);
     $this->showObjectView($oObject, $template);
 }
Example #17
0
 /**
  * @covers Form::getErrors
  */
 public function testGetErrors()
 {
     $this->myForm->addError('fail');
     $this->myForm->setErrorCode('fail', 'This field is required');
     $this->assertNotEmpty($this->myForm->getErrors());
 }