Symfony: Hide/Show form element dependent on dropdown selection with database entries - forms

I hope my title is proper: I have a dropdown, that comes from a form as an EntityType and the values are from an entity class. Code:
->add('type', EntityType::class, array(
'class' => 'DocumentBundle:DocumentType',
'label' => 'label.type',
'property' => 'translationKey',
'required' => true,
'multiple' => false,
'expanded' => false,
'empty_value' => 'label.select_type',
'choice_translation_domain' => 'Documents'
))
->add('vka_number', 'text', array(
'label' => 'label.vka_number',
'required' => false,
'translation_domain' => 'Documents'))
the second one is a text field (vka_number) that I only want to be shown when a specific value from that dropdown is selected
in my twig template I render the elements:
<div class="row">
<div class="col-md-6" id="documentDropdown">
{{ form_row(form.type) }}
</div>
<div class="col-md-6" id="vka">
{{ form_row(form.vka_number) }}
</div>
</div>
I was thinking about a javascript function like that:
<script>
$(document).ready(function(){
$('#documentDropdown').on('change', function(){
if (this.value == 'Contract')
{
$('#vka').show();
}
else {
$('#vka').hide();
}
});
});
</script>
but it's not working and I think this is because it can't access the values from the dropdown since they are not hard coded but database entries.
'Contract' would be the entry (id=1) that "makes" the vka_number text field appear.

I copied the html code from your previous question Sonja, and you seem to be continuing to ask the same question. I used that code in this jsfiddle:
https://jsfiddle.net/alvinbunk/to9qodwx/
You can use jsfiddle to experiment with your jQuery code to figure out what is wrong. As you can see the code does work and does hide the vka id division. it really has nothing to do with the fact that values are from the database. Make sure you don't have duplicate ids in various elements in your html code. Use "view source" in your browser to see the rendered code.
By the way I spent at least 15 minutes on this answer, and also 15 - 30 minutes on the other one. be aware that people on StackOverflow are very busy, and it's good to ask your questions very clearly.
EDIT #2 - Based on comments
Use this jQuery code:
<script>
$(document).ready(function(){
$('#documentDropdown').on('change', function(){
if (this.value == '1')
{
$('#vka').show();
}
else {
$('#vka').hide();
}
});
});
</script>
That should work.

Here's my javascript function that eventually solved my problem.
$(document).ready(function () {
$('#type ').change(function() {
if ($('select[id$="_type"]>option:selected').text() == "Contract") {
$('#vka_number ').show();
}
else {
$('#vka_number').hide();
}
});
});

Related

Laravel form validation wrong when using checkbox to hide/show fields causes

I have a form in Laravel 6 that uses a checkbox to hide/show additional fields. So the fields are hidden, but when the user checks the box ('attorney') and the fields appear, they are required. Otherwise, when they are hidden (checkbox unchecked) they are not required.
The following are the validation rules for the form:
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required',
'role' => 'required',
'role.*' => 'exists:roles,id',
'attorney' => 'nullable',
'bar_number' => 'nullable|required_if:attorney,1',
'law_firm_email' => 'nullable|required_if:attorney,1',
'law_firm_address' => 'nullable|required_if:attorney,1',
'law_firm_name' => 'nullable|required_if:attorney,1',
];
}
This hide/unhide works fine for users who check the box, and the form works for those that submit that extra info, but for those that don't check the box (those extra fields remain hidden) the form fails with the error "The bar number must be a string" (bar number is first field in list). The hidden fields are still being validated even though the checkbox is unchecked (the condition required_if should be false). I have tried 'checked' and 'on' for the checkbox value, same result.
This is the checkbox in the view:
<div class="col-md-6"></br>
<input id="attorney" type="checkbox" name="attorney" value="{{ old('attorney') }}"> Check if registering a law firm
#if ($errors->has('attorney'))
<span class="help-block">
<strong>{{ $errors->first('attorney') }}</strong>
</span>
#endif
</div>
This is the JavaScript that hides/shoes the DIV with the additional fields:
<script>
$(document).ready(function() {
$('input[name="attorney"]').change(function() {
if(this.checked) {
$('#bar_number_div').fadeIn('fast');
} else {
$('#bar_number_div').fadeOut('fast');
}
});
});
</script>
The JavaScript works fine as expected. The validation config is my issue.
There are no errors in the console.
I thought the required_if condition in the validation rules should work as expected, i.e., when the checkbox "attorney" is unchecked the required validation rule is not applied.
You can try with on in required_if
public function rules() {
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required',
'role' => 'required',
'role.*' => 'exists:roles,id',
'attorney' => 'nullable',
'bar_number' => 'nullable|required_if:attorney,on',
'bar_number' => 'nullable|required_if:attorney,on',
'law_firm_email' => 'nullable|required_if:attorney,on',
'law_firm_address' => 'nullable|required_if:attorney,on',
'law_firm_name' => 'nullable|required_if:attorney,on',
];
}
Remove value from input checkbox
<input id="attorney" type="checkbox" name="attorney">

cakephp 3: change class input error

I build my form template according the documentation. It seemed everything was fine until I get fields errors. Now I have two problems:
How can I change the class name of the forms fields when they get error?
Solution:
$this->loadHelper('Form', [
'templates' => 'your_template_file',
'errorClass' => 'your-class',
]);
How can I set escape => false in the error-message from cakephp, when the field get error? Because I have icon within that div, such as
<div class="error-message"><i class="fa fa-times"></i> My error</div>
Well, I got part of th solution. To escape HTML I could put $this->Form->error('field', null, ['escape' => false]); in all fields, but it´s a hard manually task. I´d like to keep escape with default of all fields errors. I could edit the FormHelper.php class. However, I think that is not good idea.
My form template is:
'formStart' => '<form {{attrs}} class="form-horizontal" novalidate>',
'inputContainer' => '{{content}}',
'input' => '<input type="{{type}}" name="{{name}}" {{attrs}} class="form-control"/>',
'checkbox' => '<input type="checkbox" value="{{value}}" name="{{name}}" {{attrs}}/>',
'textareaContainerError' => '{{content}}',
'textarea' => '<textarea name="{{name}}" {{attrs}} class="form-control"></textarea>',
'select' => '<select name="{{name}}" {{attrs}} class="form-control">{{content}}</select>',
'button' => '<button {{attrs}} class="btn btn-primary">{{text}}</button>',
'nestingLabel' => '{{input}}',
'formGroup' => '{{input}}',
to the second part of the question: you can extend FormHelper like in code below, so that escape will be set to false by default
// extended FormHelper, this goes in src/View/Helper
namespace App\View\Helper;
use Cake\View\Helper;
class MyFormHelper extends Helper\FormHelper
{
public function error($field, $text = null, array $options = [])
{
if (!isset($options['escape'])) {
$options['escape'] = false;
}
return parent::error($field, $text, $options);
}
}
next create alias for this helper in AppController.php
public $helpers = [
'Form' => ['className' => 'MyForm']
];
this also allows you to add more customization of your own and at any time, you can go back to default implementation of FormHelper, just remove that alias from AppController.php.
For those who wants an 'easy solution' to escape error message on some fields, you cant simply set escape options to false :
<?= $this->Form->input('email', [
"label" => "Email",
"error" => [
"escape" => false
]
]) ?>

Phalcon use Phalcon\Tag OR Phalcon\Forms for creating forms

I searched up and down but couldn't find which one is better Phalcon\Tag OR Phalcon\Forms for creating forms.
Both classes have functionality to create form elements. But I found there are some handy tags in the Phalcon\Tag, for example Phalcon\Tag::emailField() or Phalcon\Tag::dateField(array())
Phalcon documentation says:
"Phalcon\Forms is a component that aid the developer in the creation
and maintenance of forms in web applications."
"Phalcon\Tag is designed to simplify building of HTML tags. It
provides a set of helpers to generate HTML in a dynamic way."
Can anybody help me with the pros and cons of using both the methods.
Thanks
In simple meaning Phalcon\Tag are used to design only html (users view). but for validation && adding rules to the form you need to use phalcon\forms i will show you an example of phalcon\forums below
NEW FORM CLASS:
use Phalcon\Forms\Form,
Phalcon\Forms\Element\Password,
Phalcon\Forms\Element\Email as Emailfield,
Phalcon\Forms\Element\Check,
Phalcon\Forms\Element\Hidden,
Phalcon\Validation\Validator\PresenceOf,
Phalcon\Validation\Validator\Identical,
Phalcon\Validation\Validator\Email;
class LoginForm extends Form
{
public function initialize()
{
$email = new Emailfield('email', array(
'placeholder' => 'Type your Email'
));
$email->setLabel('E-Mail');
$email->setFilters('email');
$email->addValidators(array(
new PresenceOf(array(
'message' => 'E-mail is required'
)),
new Email(array(
'message' => 'E-mail is not valid'
))
));
$this->add($email);
$password = new Password('password', array(
'placeholder' => 'Type your Password'
));
$password->setLabel('Password');
$password->setFilters(array('striptags', 'string'));
$password->addValidators(array(
new PresenceOf(array(
'message' => 'Password required'
))
));
$this->add($password);
//Remember
$long_login = new Check('long_login', array(
'value' => 'yes'
));
$long_login->setLabel('Keep me logged in');
$this->add($long_login);
// CSRF
$csrf = new Hidden('csrf');
$csrf->addValidator(new Identical(array(
'value' => $this->security->getSessionToken(),
'message' => 'CSRF validation failed'
)));
// $this->add($csrf);
}
}
In Controller:
$form = new LoginForm();
if (!empty($_POST)) {
if (!$form->isValid($_POST)) {
$errors = array();
foreach ($form->getMessages() as $message) {
$errors[] = $message;
}
if (!empty($errors))
$this->flash->error(join('<br/>', $errors));
} else {
//Login Continues
}
}
$this->view->setVar('form', $form);
To convert this form to html below is the code:
<div class="form-group">
{{ form.label('email',['class': 'control-label']) }}
{{ form.render('email', ['class': 'form-control input-md']) }}
</div>
<div class="form-group">
{{ form.label('password',['class': 'control-label']) }}
{{ form.render('password', ['class': 'form-control input-md']) }}
</div>
<div class="checkbox">
{{ form.render('long_login') }}
{{ form.label('long_login') }}
</div>
Really great example in general but I'm struggling with the flash message. After a quick google search I was more confused after reading the documentation. Some say that $this->flash->output() should be placed to the view to see the flash messages. Though this causes errors and I believe it's something from the past. Can somebody tell me what flash method should I place to view to see the flash messages or Where I'm going wrong?
EDIT: Well I managed to get \Phalcon\Flash\Session to work and I believe it's event more suitable for me than Direct. For that you need to register flash service in Dependency Injector in config/services.php. I also replaces classes with bootstrap classes.
$di->set('flash', function() {
return new Phalcon\Flash\Session(array(
'error'=>'text-danger',
'warning'=>'text-warning',
'notice'=>'text-info',
'success'=>'text-success'
));
});
It depends on which you are working.
If we say, you need to insert lots of data with lots of validations and it may change during progress then its far better to use "Phalcon\Forms"
As they are very dynamic.
Means you can change text-box with select box very easily without touching template.
You can add validations without worrying about template and other stuff.
And for-most reusable you can reuse form if you need.
so if there is less data then you are free to use anyone of that but more suggestible is "Phalcon\Forms" its very dynamic and structural.

Form Type Default Value for empty value in rendered form

I found some weird behavior with a rendered controller with displays a edit form for my entity.
But first things first:
I'm rendering a template with displays a entity. If the logged in user is the same user as the owner of that entity i also render another controller hidden with contains the edit form for this entity. The User can access this via a button which fires a jQuery toggle.
The entity has 2 textfields which can be empty, description and situation.
So if one of the two or both are empty the edit form will display in the textfield (null) by default. I do not want that! How can i fix this so that the textfields are empty like the value of the field (so that my placeholder will be shown).
Here's an image to visualize this:
But further: This entity (Poi) belongs to another Entity (Turn), so 1 Turn -> many Pois. You can navigate through the pois in my website.
But if the owner navigtes through them (keep in mind, the edit form will be rendered, but not displayed until the button was klicked) all description and situation fields now display (null), even he did not saved the edit. It just happen by itself.
Here an image which shows it
Why does this happen? What can i do against it? Is there maybe something like an empty value option in the form type?
I searched for a solution, but i couldn't find anything that is nearly simliar with my situation.
The form build from my Form Type:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array(
'required' => false
))
->add('situation', 'textarea', array(
'required' => false
))
->add('description', 'textarea', array(
'required' => false
))
->add('isPrivateText', 'checkbox', array(
'required' => false
))
->add('isPrivateImage', 'checkbox', array(
'required' => false
))
;
}
The relevant part of my edit.html.twig
<p class="edit_form"><span class="edit_left">{{ form_label(edit_form.situation, 'Situation') }} </span>
<span class="edit_right">{{ form_widget(edit_form.situation, { attr: {'placeholder': 'Törn Situation'} }) }}</span></p>
<p class="edit_form"><span class="edit_left">{{ form_label(edit_form.description, 'Beschreibung') }} </span>
<span class="edit_right">{{ form_widget(edit_form.description, { attr: {'placeholder': 'Törn Beschreibung'} }) }}</span></p>
Where my showPoi.html.twig renderes the form controller:
<div class="col-md-6 col-sm-6 toggle_edit" style="display: none;">
<div>
{% render controller('MysailinglogMysailinglogBundle:Poi:edit', { id: poi[0].id , poi: poi}) %}
<!-- Don't worry about the 2 divs, i just shortened up the code -->
</div>
</div>
After lots of more research i found a solution that is working fine
I'm adding a listener to my formType which leads to the following function:
function onPreSetData(FormEvent $event) {
$data = $event->getData();
if($data->getDescription() == "(null)"){
$data->setDescription('');
}
if($data->getSituation() == "(null)"){
$data->setSituation('');
}
return $event->setData($data);
}
It just takes the data from the event which will build the form and is nothing more then the Poi Entity. There i simply check if the value is (null) and if it is i set it to a empty string.
Registering the listener is also easy, it`s done with this simple line of code:
$builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
This must be done with a instance of the FormBuilder, the "onPreSetData" must be the same name as the function above which will be triggered by the event.
It's important to mention that the Event must be the PRE_SET_DATA event in this situation because i wanted to manipulate the data before they're written into the form!
You can set up an empty data attribute in the Form type:
Symfony documentation
$builder->add('description', 'textarea', array(
'required' => false,
'empty_value' => 'Choose your gender',
'empty_data' => null
));

$this->request->data EMPTY - When I have disabled Fields CakePHP 2

I have a form which has some disabled fields, when the form is submitted both $this->request->data and $_POST is empty, removing the disabled fields and it is fine again. I would have though it would still pass though the non-disabled fields. I've even tried to remove the disabled field attribute when the submit button is pushed but this still returns an empty array.
Is there something cake related that might be causing this?
Thanks
// SNIPPET FROM THE VIEW CODE:
$this->Form->create('Card', array('class' => 'GeneralValidate'));
$this->Form->input('Card.property_id', array('type'=>'select', 'empty'=>true , 'class' => 'required adminOnlyField', 'div' => array('class' => 'required')));
$this->Form->input('Card.building_id', array('type'=>'select', 'empty'=>true, 'id' => 'BuildingSelector', 'class' => 'adminOnlyField', 'label' => 'Building (If Applicable)'));
$this->Form->input('Prospect.waiting_list_details', array('value' => $prospect['Prospect']['waiting_list_details']));
$this->Form->input('SaleDetail.property_sold', array('class' => 'checkbox', 'checked' => $ps_checked));
$this->Form->input('SaleDetail.date_conditions_met', array('type'=>'text', 'class' => 'text date_picker adminOnlyField', 'value' => $this->Date->format($saledetail['SaleDetail']['date_conditions_met'])));
$this->Form->button('Save & Continue', array('type'=>'submit', 'label' => 'Save', 'name' => 'quicksave' , 'class' => 'submit long clear_ready_only'));
// JS FROM THE VIEW
$(function () {
var $adminOnly = $('.adminOnlyField');
$adminOnly.prop('disabled',true).prop('readonly',true);
$adminOnly.attr("onclick","return false");
$adminOnly.attr("onkeydown","return false");
$adminOnly.removeClass('required');
$adminOnly.removeClass('date_picker');
$('.clear_ready_only').click(function(e)
{
e.preventDefault();
$adminOnly.prop('disabled',false).prop('readonly',false);
$adminOnly.attr("onclick","return true");
$adminOnly.attr("onkeydown","return true");
$('#CardModifysaleForm').submit();
});
});
That's the way HTML works, disabled don't get posted. CakePHP can't change what is sent from the browser. If you still want the value you can set it as a hidden element.
Update
Some problems I see:
Missing Form::end() in view (always a good idea to insert it).
You never said your form was submitted from JS, first test with a simple form POST then JS.
Your JS code is set to submit a form by ID CardModifysaleForm. There's no such ID in your supplied view code and you're not setting your form to that ID from the snippet you supply.
I ended up removing the disabled option from this, leaving the ready only and added some addition CSS stylings so it looked disabled to the user. This is not the exact answer to the question but works as a different approach.