To create check box in symfony using widgets and also validate it? - php

the code in symfony that i am using,
$this->setWidgets(array(
'mobile' =>new sfWidgetFormInput(),
'subscribetosms' =>new sfWidgetFormInputCheckbox(),
));
i want to validate the checkbox, and also code to take values from check box

to validate form fields in symfony u need to set validators like this (assuming you are in a form class):
$this->setValidators(array(
'mobile' => new sfValidatorString(array(...)),
'subscribetosms' => new sfValidatorInteger(array(...))
));
Question is, what do you want to validate? If you want some kind of value send to your php script if the checkbox is selected you need to set this value in the widget.
new sfWidgetFormInputCheckbox(array('value_attribute_value'=>'your_value' )
Now you could configure your validator to validate this value (sfValidatorString for a string, of sfValidatorInteger for an integer).
To get the value in your action after the validation:
if ($this->form->isValid()) {
$myValue = $this->form->getValue('subscribetosms');
}

Related

Symfony6 - add iput field after submitting form

i have an ChoiceType::class input field in my form with, now just as an example, two choices:
'choices' => ['type1' => '1', 'type2' => '2']
now when the user select type2 i want to add an exta TextType::class inputfield to the form.
But i dont want to show the input field before and i want it to be required if selected type2 and not if selected type1.
I hope it make sense, i try it to to with javascript and set the attribute to hidden or not, but
then the form is not been send because of the required attribute.
I tried it with form events but did not get it to work in that way.
Thanks
You were on the right way, you have to do it in Javascript. You just need to manage the attr required in Javascript so that the form does not block you with something like this:
Remove the required attribute from a field: document.getElementById("id").required = false;
Make a field required : document.getElementById("id").required = true;
And you can check if the form can be sumitted with : document.getElementById("idForm").reportValidity();.
I using implementation of conditional fields with data-attributes, e.g.:
->add('typeField', EnumType::class, [
'label' => 'Type',
'class' => MyTypeEnum::Class,
])
->add('someField', TextField::class, [
'data-controller' => 'depends-on',
'data-depends-on' => 'my_form_typeField',
'data-depends-value' => MyTypeEnum::OTHER->value,
])
On frontend JS stimulus controller show/hide someField depend on typeField value.
And validation() function in object ('data_class' in formType) make custom validation, e.g.:
/**
* #Assert\Callback
*/
public function validate(ExecutionContextInterface $context)
{
if ($this->typeField !== MyTypeEnum::OTHER) {
$context->buildViolation('message')->atPath('typeField')->addViolation();
}
}

Symfony 3 pre-fill FileType field

I have a FileType field in my form :
$builder->add('letter', FileType::class,[
'label'=>'DEMANDE_STATUS',
'required'=>false,
]);
And I would like to pre fill this 'letter' field when I create the form in the controller.
I've tried this so far, to no avail :
$letter = null;
if (file_exists($path.'/letter.pdf'))
$letter = new File($path.'/letter.pdf');
$demandeForm = $this->createForm('AppBundle\Form\DemandePaiementType', null, ['data'=>[
'letter' => $letter,
]]);
This method usually works when I want to pre-fill a Text field but not in this case sadly.
Any idea on how I could do that?
Don't think you can pre fill a HTML file input field. You can however display some message to the user that they already filled in this field. You can handle this in your twig template.

Pre Fill Symfony Form Text Field with Data From the Database

How can I pre fill a text field in symfony with data from the database. I have a field in the host table called hostFee and when I create the form I want that data to pre fill this text field.
I am creating a form for new BookingSpecsType()...
Here is my form builder element.
$builder->add('hostFee', 'text', array(
'required'=>false,
'error_bubbling'=>true,
'label'=>'Do you charge a hosting fee?',
'data' => '??????? (How do I fill this text field dynamically with the Host table hostFee column data) ?????',
'attr'=>array(
'placeholder'=>'If yes, enter dollar amount $0.00',
'class'=>'form-control'
)
));
Thanks.
The documentation provide many examples.
When you use $this->createForm in your Controller action, the second parameter, allow you to hydrate the form with an object.
For example:
public function editAction()
{
$user = $this->getDoctrine()->getRepository('User')->find(1); // YOUR OBJECT RETRIEVED FROM THE DB FOR EXAMPLE
$form = $this->createForm(new EditType(), $user, array(
'action' => $this->generateUrl('account_edit'),
));
return $this->render(
'AcmeAccountBundle:Account:edit.html.twig',
array('form' => $form->createView())
);
}
You do not need to define manally the data. If you just init the form from an hydrated entity, then all data are init into all fields.

Keep checked value of Yii radiobuttonlist after submit

I'm using a radioButtonList like this one:
$form->radioButtonList(Store::model(), 'product',
array(CODE1 => TEXT1,
CODE2 => TEXT2,
CODE3 => TEXT3)
);
This radioButtonList is part of a form with more fields. After submiting, if any field is incorrect, I show some error message and populate the correct fields using $_POST.
All the fields get its previous values except this radioButtonList. I need to set checked the value of the radioButtonList which was selected before submit, but I can't find how to do it.
Create $model = new Store(); in your action, pass it to view and use $model variable instead Store::model(). This should help.
UPD: You need to use the same $model after validation.
You can use
CHtml::radioButtonList(string $name, string $select, array $data, array $htmlOptions=array ( ));
In Your case it will be
CHtml::radioButtonList('product',$_POST[product],array(CODE1 => TEXT1,CODE2 => TEXT2,CODE3 => TEXT3));
Finally, I got a solution. (not an elegant one, but it works)
From the view:
Store::model()->product = $_POST["Store"]["product"];
Right before display the radioButtonList

Codeigniter - How to populate form from database?

I have a small site which allows a user to enter values in a form and then either submit it directly or store the field values in a template to later submit it. To submit the form later, he can load the previously saved template. For that there are three buttons Load Template / Save Template / Submit form.
Because i am using the form validation built-in functionality from Codeigniter i run into problems when i want to populate the form with a template, which had been previously stored.
The form fields are all set up like
$name = array(
'name' => 'name',
'id' => 'name',
'value' => set_value('name', $form_field_values['name'])
);
The variable $form_field_values holds the values from either a loaded template in the case when a template has been loaded or the default values when the form is first loaded.
Initially the form is loaded with the default values. When i click on Load Template the values from the template are not chosen by set_value() because there were the default values in there before. What i want is to replace the values of the form fields with the ones from the template.
Do you have any idea how to do that in a clean approach? What i have done is to introduce a variable to skip the call to set_value() completely like:
$name= array(
'name' => 'name',
'id' => 'name',
'value' => $skip_form_validation ? $form_field_values['name'] : set_value('name', $form_field_values['name'])
);
Where $skip_form_validation is a variable set in the controller, based on what button was pressed. Form validation is skipped for saving/loading a template.
Codeigniter's set_value() function is a simple function which finds value in $_POST if value found then return else returns second argument, you can remove set_value() and write your own code for it. you can write $_POST['field_name'] if you want to populate value of POST data or add whatever value you want to add
Just use like this
$name = array(
'name' => 'name',
'id' => 'name',
'value' => $valueFromYourTemplate
);
You don't need to use set_value() function if you don't want to set POST values in the form
Assuming you retrieve the database fields and pass them to a data array in your controller.
$record = $this->data_model->get_record(array('uid' => $user_id), 'users');
if (!is_null($record)) {
$data['uname'] = $record->username;
$data['loc'] = $record->location;
}
where 'users' is the database table, and the uid is the id field of the table users.
In your form, do something like this
Hope it helps!

Categories