sfWidgetFormInputText weird behaviour - forms

Well, I have this form:
class CaracteristicaForm extends sfForm {
public function configure() {
$this->setWidgets(array(
'caracteristica' => new sfWidgetFormInputText(array('default'=>'hola mundo'))
));
$this->setValidators(array(
'caracteristica' => new sfValidatorString(
array(
'max_length' => 150,
'required' => true
)
)
));
$this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
}
}
and then I try to...
$form = new CaracteristicaForm();
$this->embedForm('caracteristica', $form);
but the rendered inputText does not have any value at all.
What am I missing?
Ok, to reproduce this you need to embed this form into another form (mine is a Doctrine child form) so maybe is something about some method changing the value?
Well, passing an array defaults did the trick:
$form = new CaracteristicaForm(array('caracteristica' => $caracteristica));

Why not try to
$form->setDefault('caracteristica', $caracteristica);
in action?

Related

Injecting variables into Forms __construct function Zend 2

I am trying to prepopulate a form's drop down options via data stored statically in the module.config.php in Zend 2 and am running into a problem which entails:
I try to get the Servicemanager in the __construct() function but it is unavailable.
I move the element declarations to another function within the form class so I can pass variables into it but the view controller cannot find the elements.
I currently call the form via a Servicemanager Invokable. How can I pass these arrays into the form's __construct() function?
Here is the code:
class ILLForm extends Form
{
public function __construct($fieldsetName, $campuses, $ILLTypes, $getFromOptions)
{
parent::__construct('create_ill');
$this
->setAttribute('method', 'post')
->setHydrator(new ClassMethodsHydrator(false))
->setInputFilter(new InputFilter())
;
$ill = new ILLFieldset('ill', $campuses, $ILLTypes, $getFromOptions);
$ill->setName('ill')
->setOptions(array(
'use_as_base_fieldset' => true,
));
$captcha = new Element\Captcha('captcha');
$captchaAdapter = new Captcha\Dumb();
$captchaAdapter->setWordlen(5);
$captcha->setCaptcha($captchaAdapter)
->setLabelAttributes(array('class' => 'sq-form-question-title'))
->setAttribute('class', 'sq-form-field required')
->setLabel("* Captcha")
->setAttribute('title', 'Help to prevent SPAM');
$submit = new Element\Submit('submit');
$submit->setAttribute('value', 'Submit ILL')
->setAttribute('class', 'sq-form-submit')
->setAttribute('title', 'Submit ILL');
$this->add($ill)
->add($captcha)
->add($submit);
}
}
The Indexcontroller Factory that calls the Form:
class IndexControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $controllers)
{
$allServices = $controllers->getServiceLocator();
$sm = $allServices->get('ServiceManager');
$smConfig = $allServices->get('config');
$campuses = $smConfig['campuses'];
$illCategories = $smConfig['ILLCategories'];
$getFromOptions = $smConfig['getFromOptions'];
$controller = new IndexController();
$controller->setCampuses($campuses);
$controller->setILLCategories($illCategories);
$controller->setGetFromOptions($getFromOptions);
$controller->setILLForm($sm->get('ILL-form'));
$controller->setILLFormFilter($sm->get('ILL-form-filter'));
//$controller->setParams($sm->get('params'));
return $controller;
}
}
and the relevant module.config.php excerpt:
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
'Zend\Log\LoggerAbstractServiceFactory',
),
'invokables' => array(
'ILL-form-filter' => 'ILL\Form\ILLFormFilter',
'ILL-form' => 'ILL\Form\ILLForm',
),
I ended up taking the form out of the service manager invokables in module.config.php (removed line for 'ILL-form') and call it from the indexControllerFactory.php instead
$create_ill = new Form\ILLForm('create_ill', $campuses, $illCategories, $getFromOptions);
$controller->setILLForm($create_ill);
instead of
$controller->setILLForm($sm->get('ILL-form'));

Yii2 remember sort option after submit the searchForm

I use an ActiveForm in Yii2 for my SearchModel. After click on search button the form fields remember previous values but SorterDropdown is refreshed.
<?php echo SorterDropdown::widget(['sort' => $dataProvider->sort,
'label' => $model->sortedBy($dataProvider->sort->attributes),])
?>
SorterDropdown is just a wrapper of ButtonDropdown.
How can I forse the SorterDropdown to remember sort order (and show it) after the form submition?
class SorterDropdown extends LinkSorter
{
public $label;
protected function renderSortLinks()
{
$attributes = empty($this->attributes) ? array_keys($this->sort->attributes) : $this->attributes;
$links = [];
foreach ($attributes as $name) {
$links[] = Html::tag('li', $this->sort->link($name, ['tabindex' => '-1']));
}
if (empty($this->label))
$this->label = 'Sort';
return \yii\bootstrap\ButtonDropdown::widget([
'encodeLabel' => false,
'label' => $this->label,
'dropdown' => [
'items' => $links,
],
]);
}
You should add some class to li element, which indicate active state of it and special style in CSS file.

symfony 2 Add values in a collection form in

I'm trying to add values into each element of a collection from a multiple form, but I got this :
Call to a member function getQuestions() on a non-object
What is the correct syntax?
This is my code:
$repository = $this->getDoctrine()->getManager()
->getRepository('***Bundle:Projet');
$projet = $repository->find($projetid);
$formBuilder = $this->createFormBuilder($projet);
$formBuilder->add('questions','collection',array(
'type' => new QuestionType(),
'allow_add' => true,
'allow_delete' => true
));
$form = $formBuilder->getForm();
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$membreid = $this->getUser()->getId();
$questions = $projet->getQuestions();
//I'm gonna do a loop here
$questions[0]->setMembreId($membreid);
$projet->addQuestion($questions[0]);
$em->persist($projet);
$em->flush();
return $this->redirect($this->generateUrl('***_nouveau_projet',array('etape' => 3, 'id' => $projet->getId() )));
}
}
return $this->render('***:nouveau_projet.html.twig',array(
'form' => $form->createView(),
'etape' => $etape,
'projet' => $projetid,
));
The error message you got provides relevant clues about what's going wrong.
getQuestions() is called on a non object.
Make sure $project is an instance of ***Bundle:Projet and that
$repository->find($projetid); is returning a valid object.
Probably that the given $projetid doesn't match any record in your date source.

Zend_Form renders all fields as text

I have a Zend_Form form, with some custom decorators, like this:
$decorators = array();
$decorators[] = new Zend_Form_Decorator_ViewHelper(array());
$decorators[] = new Zend_Form_Decorator_Errors;
$decorators[] = new Zend_Form_Decorator_HtmlTag(array('tag' => 'div', 'class' => 'form-item'));
$decorators[] = new Zend_Form_Decorator_Label(array('class' => 'form-label'));
$decorators[] = new Zend_Form_Decorator_Callback(array(
'callback' => function($content, $element, $options) {
return sprintf('<div class="form-row">%s</div>', $content);
},
'placement' => false
));
$this->setElementDecorators($decorators);
The problem is, that all of the fields are rendered as text inputs. Why does it happen?
EDIT: I discovered, that it doesn't render all the inputs necessarily as text inputs, but renders them with type of the first input in form. Here is example of a form that i use(the decorators are set int parent's init):
<?php
class Form_Users_Add extends Form_Base {
protected $pbxs = array(1 => 'Element 1', 2 => 'Element 2');
public function init() {
$monitors = new Zend_Form_Element_Checkbox('prefered_screen_count');
$monitors->setCheckedValue(2);
$monitors->setUncheckedValue(1);
$monitors->setLabel('two_monitors');
$this->addElement($monitors);
$pbx = new Zend_Form_Element_Select('asterisk_id');
$pbx->setMultiOptions($this->pbxs);
$pbx->setLabel('users_asterisk_id');
$this->addElement($pbx);
parent::init();
}
}
Yay! I have solved the issue! The cause was that I used INSTANCES of classes, not the names. This way every element was using the same instance of the decorator.

Zend Form Text value stays null

I've created a simple upload-form and got a little problem when submitting the data.
The file is uploaded correctly, but my little description field stays null.
Here's my form:
class Upload_Form_Uploadvideo extends Zend_Form{
public function init()
{
$this->setName('video')
->setAction('interface/videoupload')
->setMethod('post');
#id
$id = new Zend_Form_Element_Hidden('id');
$id->addFilter('Int');
#Textfield "Videofile"
$video = new Zend_Form_Element_File('videofile', array(
'label' => 'Videofile')
);
$video->setDestination(APPLICATION_PATH.'/upload/video/toConvert/');
#Textfield "Videofile"
$desc = new Zend_Form_Element_Text('videodescription', array(
'label' => 'Description')
);
$desc->setAttrib('value','The description is not optional!');
$desc->setAttrib('size','25');
#Submit
$submit = new Zend_Form_Element_Submit('submit', array('label' => 'Upload Video'));
$submit->setAttrib('id', 'submitbutton');
#bringing everything together
$this->addElements(array($id,$video,$desc,$submit));
}
}
the controller, giving it to the view:
public function videouploadAction()
{
#in production this code goes to the index()
if(!$this->getRequest()->isPost()){
return $this->_forward('index');
}
$form = $this->getForm();
$this->view->via_getpost = var_dump($this->_request->getPost());
$this->view->via_getvalues= var_dump($form->getValues());
}
Now, I var_dump $this->_request->getPost() and $form->getValues().
The output is the following:
array[$this->_request->getPost()]
'id' => string '0' (length=1)
'MAX_FILE_SIZE' => string '134217728' (length=9)
'videodescription' => string 'This is a test-video' (length=20)
'submit' => string 'Upload Video' (length=12)
array [$form->getValues()]
'id' => int 0
'videofile' => string 'swipeall.avi' (length=12)
'videodescription' => null
In addition, I set the "value"-attrib, without any effect. I intended to write something in the box, when the user loads the site.
I'm new to Zend, so I guess I'm just overseeing something stupid, though I can't find it.
Update:
I really had to get the $_POST-Data via
$formdata = $this->getRequest()->getPost();
use
$desc->setValue('The description is not optional!');
instead of
$desc->setAttrib('value','The description is not optional!');