symfony2 + bootstrap 3 readonly select dropdown still editable - php

I am using symfony2 and bootstrap 3 and when I set the readonly attribute to a form field, it gets greyed and I have the forbidden cursor but the field is still editable (in my case a select dropdown).
The readonly attribute would work great for a simple text field, but not for a select.
How can I make sure users can't click a select and change its value ?
I can't use "disabled" as I need the value to be passed to the form.
Using jquery to rewrite the readonly attribute also did not work.
my form:
->add('product', 'entity', array(
'label' => 'Produit',
'class' => 'AppBundle:MarketPlace\Product',
'read_only' => true,
))

Create a data transformer ProductToTextTransformer for your entity as explained in the doc, and then use it in your formbuilder, adding a select or a readonly text according to the condition for the select to be disabled or not :
//...
// this assumes that the entity manager was passed in as an option
$entityManager = $options['em'];
$transformer = new ProductToTextTransformer($entityManager);
if ($condition_to_disabled_the_select){
$builder->add('product', 'entity', array(
'label' => 'Produit',
'class' => 'AppBundle:MarketPlace\Product',
));
}
else{
$builder->add(
$builder->create('product', 'text', array('label' => 'Produit', 'read_only' => true))
->addModelTransformer($transformer)
);
}

The following is working but I don't liek it that much, I feel it's not clean like it should be:
<script>
$(function(){
$(':input[readonly]').each(function(){
$(this)
.hide()
.parent().append('<p>' + $(this).find(":selected").text() + '</p>')
})
;
})
</script>

Related

How to set an initial selection for an AJAX driven Select2 box with CakePHP?

I'm using select2 to let user choose stuff from list from ajax.
In adding to db it's working great, but I want to edit stuff. So I can still select stuff from my select2, but user should see what is the current value of select2.
I've tried to do something with InitSelect, but it didn't work, even after I've just passed data from php.
This is my Select2:
$(".personid").select2({
ajax: {
type: "post",
url: '/' + APP_PATH + '/Projects/find_person.json',
datatype: 'json',
quietMillis: '100',
data: function (term, page) {
return {
q: term.toUpperCase(), // wprowadzony ciag znakow - zawsze na uppercase
page_limit: 10,
};
},
results: function (data, page) {
var dane = {results: []};
$.each(data['data'], function (i, item) {
dane.results.push({
id: item['Person']['id'],
text: item['Person']['displayName']
});
});
return dane;
}
}
});
And this is my cake form input:
echo $this->Form->input('person_id', array(
'type' => 'text',
'value' => $projectcontact['Person']['id'],
'Placeholder' => 'Wybierz osobę',
'empty' => 'Wybierz osobę ',
'class' => 'form-control personid',
'label' => array(
'class' => 'col-md-4 control-label',
'text' => 'Osoba'
)
));
Can anyone help to make Select.js display current Persona name data from database in this?
With Select2 4.x
With Select2 4.x you're not supposed to use a text input element anymore, but a select element. Quote from the docs:
When using Select2 with remote data, the HTML required for the select is the same as any other Select2. If you need to provide default selections, you just need to include an option for each selection that contains the value and text that should be displayed.
<select class="js-data-example-ajax">
<option value="3620194" selected="selected">select2/select2</option>
</select>
https://select2.github.io/examples.html#data-ajax
So, as described, create a proper select input with a single selected option element, something along the lines of:
echo $this->Form->input('person_id', array(
'type' => 'select',
'options' => array(
$projectcontact['Person']['id'] => $projectcontact['Person']['displayName']
),
'selected' => $projectcontact['Person']['id'],
'class' => 'form-control personid',
'label' => array(
'class' => 'col-md-4 control-label',
'text' => 'Osoba'
)
));
Additionally you'll have to ensure that $projectcontact is being filled with the person according to the possible submitted person_id value, otherwise the selected value will not remain when rendering the form after submit.
Normally when creating a select element, you'd use a complete list of options, so that the form helper could pick the appropriate option automatically, based on the submitted value. Without such a list, you'll have to read and supply the specific person instead.
Here's some dummy code that demonstrates the priniciple:
$personId = $defaultPersonId;
if($this->request->is(array('post', 'put'))) {
$personId = $this->request->data('ModelName.person_id');
// ...
}
$projectcontact = $this->Person->findById($personId);
$this->set('projectcontact', $projectcontact);
See also
Cookbook > Core Libraries > Helpers > Form > Options for select, checkbox and radio inputs
Cookbook > Core Libraries > Helpers > Form > Creating form elements
Cookbook > Models > Retrieving Your Data > find(‘list’)

Symfony Sonata project: How to add multiple input texts to block?

I would like to add a collection of input text with same name (i.e. name="blabla[]") filed to admin block with add/delete buttons.
I'm using collection form field type but can't see add/delete buttons
public function buildEditForm(FormMapper $formMapper, BlockInterface $block)
{
$formMapper->add('settings', 'sonata_type_immutable_array', array(
'keys' => array(
array('title', 'collection',
array('type' => 'text' ,
'required' => true,
'allow_add' => true,
'data' => array('First' => 'One')
)
)
)
));
}
I get below result without add/delete buttons!
Any idea how to get it working ?
I think you should use sonata_type_collection or sonata_type_native_collection instead of collection.
Here is an extract of the field doc :
14.1.7. SONATA_TYPE_NATIVE_COLLECTION (PREVIOUSLY COLLECTION)
This bundle handle the native Symfony collection form type by adding:
an add button if you set the allow_add option to true. a delete button
if you set the allow_delete option to true.

FormHelper::input() creates a drop-down select if fielname has the "_id" suffix

I have the following line of code on a CakePHP view:
<?php
echo $this->Form->input(
'person_id',
array(
'label' => false,
'div' => false,
'class' => 'form-control search-person'
)
);
?>
I want to create a text input with this line of code, but if the field name has the suffix _id, the rendered HTML changes from a text field to a drop-down select.
If I change the prefix to anything else, for example person_idd or abc_idd, it renders a text input, but if the field name ends with _id suffix, it renders a drop-down select, which doesn't allow me to write anything.
Is this some CakePHP feature? How can I avoid this behavior and produce a text input with a field ending with the _id suffix?
It's a CakePHP feature:
This method will automatically inspect the model field it has been supplied in order to create an appropriate input for that field.
Taken from Cookbook 2.x: FormHelper: Creating form elements.
To get a text input, add 'type' => 'text' to the options array:
<?php echo $this->Form->input('person_id', array(
'type' => 'text',
'label' => false,
'div' => false,
'class' => 'form-control search-person'
)); ?>

Symfony forms: avoid having submit button

I am using Symfony framework and I want to create a form without the submit button.
I explain myself better: I have a simple form, like the following one:
$form = $this->createFormBuilder($defaultData);
$form->add($fieldname, 'choice', array(
'choices' => array(
'3' => 'label_3',
'2' => 'label_2',
'1' => 'label_1',
'0' => 'label_0',
),
'expanded' => false,
'label' => 'choice',
));
$form->add('send', 'submit', array(
'label' => 'send'
));
Is there a way to avoid having a "submit" button?
The resulting behavior I want to enforce is:
- The User selects the desired choice
- On click, data is immediately submitted and handled by the controller
I searched in the Symfony manual, but I failed finding something that could fit.
Can anyone help me? (Is i even possible to have such a behavior?)
Thanks in advance.
You have to do this via JavaScript:
$('#formFieldId').change(function(){
$(this).closest('form').trigger('submit');
});
you should try with javascript like this :
jQuery().ready( function() {
// for example your fieldname id is "field"
jQuery( "#field").change( function(){
jQuery('form').submit();
});
});
you don t have to put you submit button in your form by the way, the standard way is to include the html for the button within the twig file

Symfony2 Embed form values

I have my own utility CalculatorType for just calculating values for my document(I am using ODM), not reference for another document or sub arrays|object.
It has simple 2 inputs:
$builder
->add('price', 'text', array(
'label' => false,
'data' => isset($options['data']) ? $options['data']->getPrice() : '0.00'
))
->add('count', 'integer', array(
'label' => false,
'data' => isset($options['data']) ? $options['data']->getCount() : '10000'
));
In parent form I have:
$builder->
... // multiple fields
->add('calculator', 'calculator');
So when I am trying to save my form, I have an error:
Neither the property "calculator" nor one of the methods
To skip setting calculator field, I've added mapped => false to options
->add('calculator', 'calculator', array('mapped' => false));
and added eventlistener to transform calculator data
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
$data["price"] = $data["calculator"]["price"];
$data["count"] = $data["calculator"]["count"];
unset($data["calculator"]);
$event->setData($data);
});
Now form submits values but calculator fields not passing to embed form, because of unsetting $data['calculator']
If I comment unset($data["calculator"]); then I have an error
This form should not contain extra fields
So I can't find any way to make this form work. Any ideas?
Found mistake in my form, so there is option for such type of forms: http://symfony.com/doc/current/cookbook/form/inherit_data_option.html

Categories