Form text diappears and comeing ab up again - forms

How do I do that in symfony?
http://dorward.me.uk/tmp/label-work/example.html
When I click into the input field username. The text disappears. If I don't enter nothing and click somewhere else the text is comeing up again. How do I do that in symofny in lib/forms/.
Thanks for an advice!
Craphunter

This isnt symfony - its javascript ... just take a look at the source (uses jQuery)
HTML:
<div class="slim-control">
<label for="username"> Username </label>
<input name="username" id="username">
</div>
<div class="slim-control">
<label for="password"> Password </label>
<input name="password" id="password" type="password">
</div>
JavaScript:
(function () {
var nonEmpty = "non-empty";
var inputs = jQuery('.slim-control input');
var setLabelStyle = function setLabelStyle () {
var label = jQuery(this);
if (label.val().length) {
label.addClass(nonEmpty);
} else {
label.removeClass(nonEmpty);
}
};
inputs.focus(function () {
jQuery(this).addClass(nonEmpty);
});
inputs.blur(setLabelStyle);
inputs.each(setLabelStyle);
}());
So if you want to do this - you would need to add the javascript to the template (indexSuccess.php) for example - you would probably need to modify the ids / classes to meet your local needs
Updated
You could create the following form - this would match the above form (untested):
$this->form = new sfForm();
$this->form->setWidgets(array(
'username' => new sfWidgetFormInputText(),
'password' => new sfWidgetFormInputPassword()
));
Creating forms (indeed all of Symfony) is very well documented here -> http://www.symfony-project.org/gentle-introduction/1_4/en/10-Forms

'input' => new sfWidgetFormInputText(array(), array('size' => '100', 'maxlength' => '255', 'value' => 'Some text', 'onblur' =>"if(this.value == '') { this.value='Some text'}", 'onfocus' =>"if (this.value == 'Some text') {this.value=''}")),
This is much shorter! Be careful that "Some text" is identical!
If you need to pass more, take a look to SetWidgetsHtml in Symfony form: (slide down)
http://www.symfony-project.org/forms/1_4/en/01-Form-Creation

Related

How to update Form options after submitting using useReducer

i´m new at programming..
I'm coding a form that has a Select list of Options, which come from an array of objects (i named it initialState for useReducer use).
Now i have to use the useReducer hook to update those options when the form is submitted. The submitted option has to be eliminated after submitting.
I just started coding the hook, but i really don´t know what to do...
The app is rendering OK, and the "placeholder" initial state is showing the first option value. I'm okay with that.
Can you help me plase? Thanks!
import { useState, useReducer } from "react";
const handleSubmit = (e) => {
e.preventDefault();
}
const BookingForm = () => {
const initialState = [
{value: "17:00"},
{value: "17:30"},
{value: "18:00"},
{value: "18:30"},
{value: "19:00"},
{value: "19:30"}]
const reducer = (state, action) => {
?????? }
const [state, dispatch] = useReducer(reducer, initialState);
const [option, setOption] = useState({initialState});
return(
<div className="form_div">
<form className="form" onSubmit={handleSubmit}>
<label htmlFor="res-time" className="label">Choose time
<select id="res-time " className="input"
value={option}
onChange={(e) => setOption(e.target.value)}>
{initialState.map(item => {
return (<option key={item.value} value={item.value}>{item.value}</option>);
})}
</select>
</label>
<input type="submit" value="Make Your reservation" className="button" onClick={() => dispatch({type: "selected option"})}/>
</form>
export default BookingForm;

Form Framework: Render and send "headless" with JSON transfer

I want to use the form framework with vue.js. Instead of rendering with fluid, I prepare and assign the form elements as a json object, which vue loads async from my API controller.
My basic implementation of a single text field works so far, but "formstate->getFormValues()" remains empty. So I guess, the binding between my form and the request fails.
The following example is just the basic principle:
Controller: Prepare form fields as array and return json to the requesting frontend application
class FormFrontendApiController extends FormFrontendController
{
public function renderAction(): ResponseInterface
{
$persistenceIdentifier = 'EXT:test/Resources/Private/FormDefinitions/test.form.yaml';
$formConfiguration = $this->formPersistenceManager->load($persistenceIdentifier);
$factory = GeneralUtility::makeInstance(ArrayFormFactory::class);
$formDefinition = $factory->build($formConfiguration);
$formDefinition->setIdentifier($formDefinition->getIdentifier());
$formRuntime = GeneralUtility::makeInstance(HeadlessFormRuntime::class);
$formRuntime->setFormDefinition($formDefinition);
$formRuntime->setRequest($this->request);
$formRuntime->initialize();
$formState = $formRuntime->getFormState();
$finisherResponse = $formRuntime->run();
$elements = $formRuntime->getFormDefinition()->getElements();
$hashService = GeneralUtility::makeInstance(HashService::class);
$stateHash = $hashService->appendHmac(base64_encode(serialize($formState)));
$currentPageIndex = $formRuntime->getCurrentPage() ? $formRuntime->getCurrentPage()->getIndex() : 0;
$currentPageId = $currentPageIndex + 1;
$elements = $formDefinition->getPageByIndex($currentPageIndex)->getElements();
$requestHash = $this->mvcPropertyMappingConfigurationService->generateTrustedPropertiesToken(
['tx_form_formframework[test][text-1]', 'tx_form_formframework[test][__currentPage]'],
'tx_form_formframework'
);
$formFields = [
[
'type' => 'Hidden',
'name' => sprintf('tx_form_formframework[%s][__state]', $formDefinition->getIdentifier()),
'defaultValue' => $stateHash
],
[
'type' => 'Hidden',
'name' => 'tx_form_formframework[__trustedProperties]',
'defaultValue' => $requestHash
],
[
'type' => 'Hidden',
'name' => sprintf('tx_form_formframework[%s][__currentPage]', $formDefinition->getIdentifier()),
'defaultValue' => $currentPageId
]
];
$formDefinition->setRenderingOption('controllerAction', 'perform');
return $this->jsonResponse(json_encode($formFields));
}
}
The rendered frontend contains the following necessary form fields:
<input type="hidden"
name="tx_form_formframework[test][__state]"
value="TzozOToiVFlQTzNcQ01TXEZvcm1cRG9tYWluXFJ1bnRpbWVcRm9ybVN0YXRlIjoyOntzOjI1OiIAKgBsYXN0RGlzcGxheWVkUGFnZUluZGV4IjtpOjA7czoxMzoiACoAZm9ybVZhbHVlcyI7YTowOnt9fQ==aa9f11798f986845c2e54234794c5197446d74dc" />
<input type="hidden"
name="tx_form_formframework[__trustedProperties]"
value="{"test":{"text-1":1,"__currentPage":1}}6a81fd31dfb7f29c51873b39ff18544e45c4d7ba" />
<input class=" o-form-field__input"
id="aPIFormular-101-text-1"
type="text"
name="tx_form_formframework[test][text-1]" value="" />
<input type="hidden" name="tx_form_formframework[test][__currentPage]" value="1" />
To test, I just submit the form back to the controller, as a basic post request (no JavaScript fetch).
debug($formState->isFormSubmitted()) returns true
debug($formState->getFormValues()) remains empty
Question:
Is it possible to use the form framework in this way or will I run into huge problems / efforts?

How to use checkboxes with Phalcon forms?

I am creating a form using Phalcon that has a checkbox on it. I use this code to create the checkbox in my PagesForm.php file
$this->add(new Check('usesLayout'));
and then in my view I have
{{ form.render("usesLayout") }}
However, if the checkbox is unchecked then Phalcon complains about usesLayout is required.
The html code produced by the view is
<input type="checkbox" id="usesLayout" name="usesLayout" value="1" checked="checked" />
What is the correct way to create a Phalcon form with a checkbox so that it accepts it both checked and unchecked?
Desired outcome
After looking back at a form made when using CakePHP the html output is
<input type="hidden" name="usesLayout" id="usesLayout_" value="0" />
<input type="checkbox" name="usesLayout" id="usesLayout" value="1" checked="checked" />
This works fine, so I am looking for something similar to this.
Current Workaround
After modifying the code in the final response to this question I have this workaround currently (I use this instead of Phalcon\Forms\Element\Check)
namespace Armaware\InBrowserDev\Forms\Element;
use Phalcon\Forms\Element\Check as PhalconCheck;
class Check extends PhalconCheck
{
/**
* Renders the element widget returning html
*
* #param array|null $attributes Element attributes
*
* #return string
*/
public function render($attributes = null)
{
$attrs = array();
if (!is_null($attributes)) {
foreach ($attributes as $attrName => $attrVal) {
if (is_numeric($attrName) || in_array($attrName, array('id', 'name', 'placeholder'))) {
continue;
}
$attrs[] = $attrName .'="'. $attrVal .'"';
}
}
$attrs = ' '. implode(' ', $attrs);
$id = $this->getAttribute('id', $this->getName());
$name = $this->getName();
$checked = '';
if ($this->getValue()) {
$checked = ' checked';
}
return <<<HTML
<input type="hidden" id="{$id}_" name="{$name}" value="0" />
<input type="checkbox" id="{$id}" name="{$name}" value="1"{$attrs}{$checked} />
HTML;
}
}
public Phalcon\Forms\ElementInterface setDefault (unknown $value) inherited from Phalcon\Forms\Element
Sets a default value in case the form does not use an entity or there is no value available for the element in _POST
Source.
Looks like your declaration of form can look like this:
$controls[] = (new Check('usesLayout', ['value' => '1']))
->setLabel('Should I use layout?')
->setDefault('0') // or `false` in case it's not filtered
->addFilter('bool'); // filtering to boolean value
Not tested, but probably will do. You can always try to make this trick with handling this in beforeValidation() method of form, but have no space to test it right now and am not risking on failurable solution here.

Keep Search Parameters Through Pagination

Somewhat new to Laravel(4.2) and I'm having issues with pagination on my search function. So far I've been able to successfully carry out a search, though in the rare cases it actually goes over onto a second page it resets to simply "?page=2"
Below is the code for the form.
{{ Form::open(array('method' => 'post', 'name' => 'all', 'novalidate' => 'novalidate')) }}
<input type="text" name="srch_lname" class="input-large" value="{{ Input::old('srch_lname', Session::get('srch_lname')) }}" />
<input type="text" name="srch_fname" class="input-large" value="{{ Input::old('srch_fname', Session::get('srch_fname')) }}" />
.
.
.
<?php echo $employees->links(); ?>
And the controller handling the search.
public function getIndex() {
$srch_lname = Session::get('srch_lname');
$srch_fname = Session::get('srch_fname');
$employees = vEmployees::co()->restrictions()
->where('lastname', 'LIKE', $srch_lname . '%')
->where('firstname', 'LIKE', $srch_fname . '%')
->orderBy('lastname')
->orderBy('firstname')
->paginate(10);
return View::make('index')
->with('employees', $employees)
->with('title', 'Users')
->with('pagetitle', 'Employees')
->with('pagedescription', '')
}
public function postIndex() {
if (Input::has('btnSearch')) {
return Redirect::to('/employees')->with('search', 1)
->with('srch_lname', Input::get('srch_lname'))
->with('srch_fname', Input::get('srch_fname'))
I've been trying some other solutions found throughout SO though it either ends up causing issues or bringing me back to the same problem.
Any sort of push in the right direction would be awesome!
Append the search data to the pagination links()
<?php echo $employees->appends(array("srch_lname" => ...))->links(); ?>
http://laravel.com/docs/4.2/pagination#appending-to-pagination-links

How to wrap radio button group in label zend form

I want the following html with two radio button groups in zend form
<label class="inline">
<input type="radio" name="form-field-radio">
<span class="lbl"> Male</span>
</label>
<label class="inline">
<input type="radio" name="form-field-radio">
<span class="lbl"> Female</span>
</label>
and i'm using the following code to make this button in Zend Form
$gender = $this->CreateElement('radio','gender')
->addFilter(new Zend_Filter_StringTrim())
->setMultiOptions(array('M'=>'Male', 'F'=>'Female'))
->setDecorators(array( array('ViewHelper') ));
But I don't know where to set the lable and span classes in this code.
Please help.
Thanks.
I am not sure whether its the perfect method to do this its the first time i am using zend framework, But still here are the steps that i did, if you may find useful:
First I created a custom decorator which extends Zend_Form_Decorator_Abstract and saved it in the location 'decorator/My_Form_Decorator.php'. decorator is a directory created by me in root.
.
/decorator
/application
etc...
Then i included it in a controller. I have read that there are certain methods for adding the decorator like addPrefixPath() but for time sake i just included the decorator file in top with 'include "../decorator/My_Form_Decorator.php";'. Then instead of using the CreateElement method i used Zend_Form_Element.
The following is the code of custom radio decorator
My_Form_Decorator.php
class My_Decorator_RadioInput extends Zend_Form_Decorator_Abstract
{
public function render($content)
{
$element = $this->getElement();
$label = htmlentities($element->getLabel());
$type = $element->type;
$name = $element->elemName;
$multiOptions = $element->multiOptions;
$labelClass = $element->labelClass;
$spanClass = $element->spanClass;
$markup='';
if(!empty($type) && !empty($name) && !empty($multiOptions) && is_array($multiOptions)){
foreach($multiOptions as $key=>$value){
$markup .='<label class="'.$labelClass.'"><input type="radio" name="'.$name.'" value="'.$key.'"> <span class="'.$spanClass.'">'.$value.'</span></label>';
}
}
return $markup;
}
}
and this is the code in my controller function
IndexController.php
$decorator = new My_Decorator_RadioInput();
$form = new Zend_Form();
$form->setAttrib('id', 'test');
$element = new Zend_Form_Element('foo', array(
'elemName'=>'gender',
'type' =>'radio',
'multiOptions' => array('M'=>'Male', 'F'=>'Female'),
'labelClass'=>'inline',
'spanClass'=>'lbl',
'decorators' => array($decorator),
));
$form->addElement($element);
$this->view->form = $form;
And in view index.phtml
echo $this->form
Hope this is helpful to you..