Symfony set hidden value after submit - symfony1

I have a form with 2 input fields email and password(hidden) . I'm trying to generate a random value as below but failed to bind password(hidden) value after submit.
$password = substr(md5(rand(100000, 999999)), 0, 6);
$this->form->bind($request->setParameter('password',$password));
Form has the setNameformat with:
$this->widgetSchema->setNameFormat('user[%s]');

If a doctrine (or propel) form, I would do this by setting the values on the object before passing to the form constructor, and completely removing the widget from the form.
eg:
$o = new DoctrineOrPropelObject;
$o->setPassword($myrandomstring);
$f = new DoctrineOrPropelObjectForm($o);
Then display/save the form as usual - the password value will be passed right through the form process to the database when saved.

if you use this:
$this->widgetSchema->setNameFormat('user[%s]');
then your form input fields can be retrieved in single variable:
$request->getParameter('user');
and the value that you want to assign need to be set with something like:
$request->setParameter('user[password]', $password);
Reference can be found here.
Regards.

You can override the save method of your form and add $this->values[$field] = $value;
Something like this:
public function save($con = null)
{
$this->values['owner_id'] = $this->values['owners_ids'][2];`
return parent::save($con);
}

Related

React-Final-Form -> Dynamically created from based on data from server

EDIT: THE IDEA BELLOW WORKS
I just noticed that the problem was in . notation of values I used. The path must be correctly converted to the same object structure as in case of tools changeValue).
Also, this code
...
const initialValues = form.getState().initialValues;
initialValues[fieldName] = fieldValue;
form.setConfig("initialValues", initialValues);
...
had to be changed to
...
const initialValues = form.getState().values;
initialValues[fieldName] = fieldValue;
form.setConfig("initialValues", initialValues);
...
as I wanted current values to be kept in the form instead of the form has to be "reinitialized".
I am using final-form for presenting a form partly generated dynamically based on the data templates and the data itself loaded from the server.
In order to generate the form and populate it with the values loaded from the server I am using custom mutator, which just sets the correct values once the form is generated and the data is loaded from the server.
Mutator works well, but I also need to set initialValues once the part of the form (based i.e. on initial value or user selected value of the combo box) is loaded and generated in order to prevent dirty state before the form is touched by the user.
Question: Is it possible to set initialValues dynamically, once the template/data is loaded in order to prevent pristine/dirty state, but also, without touching other form values and initialValues?
Please note, this is just example of children component used within the form declared in parent component (including the custom mutator). My original code is way too complex to pass it here. Maybe this code is not fully syntactically correct, maybe it would not work with checkbox, don't care too much about it - it is just an example and the question is about something else. Mutator works actually well, so please focus on initalValues.
interface Props {
fieldName: string;
fieldType: "checkbox" | "text";
fieldValue: string | boolean;
}
function DynamicFormField({
fieldName,
fieldType,
fieldValue
}: Props) {
const form = useForm();
useEffect(
() => {
// *** this is what I tried, but does not work ***
const initialValues = form.getState().initialValues;
initialValues[fieldName] = fieldValue;
form.setConfig("initialValues", initialValues);
// ***
// *** also tried ***
const initialValues = { ...form.getState().initialValues };
initialValues[fieldName] = fieldValue;
form.setConfig("initialValues", initialValues);
// ***
form.mutators.setValue(fieldName, fieldValue);
},
[fieldName, fieldValue]
)
}
return (
<Field name={fieldName}>
{({ input }) => (
{
fieldType === "checkbox" ?
(<input {...input} type="checkbox")
:
(<input {...input} type="text")
}
)}
</Field>
)
It works, please see edit.
The initialValues object must just have same structure as the values object.

BeanItemContainer unique property values

I am using BeanItemContainer for my Grid. I want to get a unique list of one of the properties. For instance, let's say my beans are as follows:
class Fun {
String game;
String rules;
String winner;
}
This would display as 3 columns in my Grid. I want to get a list of all the unique values for the game property. How would I do this? I have the same property id in multiple different bean classes, so it would be nice to get the values directly from the BeanItemContainer. I am trying to avoid building this unique list before loading the data into the Grid, since doing it that way would require me to handle it on a case by case basis.
My ultimate goal is to create a dropdown in a filter based on those unique values.
There isn't any helper for directly doing what you ask for. Instead, you'd have to do it "manually" by iterating through all items and collecting the property values to a Set which would then at the end contain all unique values.
Alternatively, if the data originates from a database, then you could maybe retrieve the unique values from there by using e.g. the DISTINCT keyword in SQL.
In case anyone is curious, this is how I applied Leif's suggestion. When they enter the dropdown, I cycle through all the item ids for the property id of the column I care about, and then fill values based on that property id. Since the same Grid can be loaded with new data, I also have to "clear" this list of item ids.
filterField.addFocusListener(focus->{
if(!(filterField.getItemIds() instanceof Collection) ||
filterField.getItemIds().isEmpty())
{
BeanItemContainer<T> container = getGridContainer();
if( container instanceof BeanItemContainer && getFilterPropertyId() instanceof Object )
{
List<T> itemIds = container.getItemIds();
Set<String> distinctValues = new HashSet<String>();
for(T itemId : itemIds)
{
Property<?> prop = container.getContainerProperty(itemId, getFilterPropertyId());
String value = null;
if( prop.getValue() instanceof String )
{
value = (String) prop.getValue();
}
if(value instanceof String && !value.trim().isEmpty())
distinctValues.add(value);
}
filterField.addItems(distinctValues);
}
}
});
Minor point: the filterField variable is using the ComboBoxMultiselect add-on for Vaadin 7. Hopefully, when I finally have time to convert to Vaadin 14+, I can do something similar there.

Django Admin shows "(nothing)"

I want to show in the app/model admin the columns of the model but with some customization. These 3 'tar', 'per_hor','per_tar' have choices in their modelfield.
First I wrote this code:
class ValoresAdmin(admin.ModelAdmin):
list_display = ('fecha', 'tar', 'per_hor','per_tar')
list_filter = ('fecha','tar','per_tar','per_hor')
date_hierarchy = 'fecha'
fieldsets = (
(None, {
'fields': ('fecha',('tar', 'per_hor', 'per_tar'))
}),
(None, {
'fields': ('feu', 'coef_perf','sah', 'pmh','carg_cap')
}),
)
I shows the verbose name of the column but the values is always "(nothing)" on the filter page but if I enter the change form they display correctly their value (their choide).
I read some and decided to create methods like these ones and call them in the list_display:
def get_tar(Self):
return self.get_tar_display()
def get_per_hor(Self):
return self.get_per_hor_display()
def get_per_tar(Self):
return self.get_per_tar_display()
get_tar_display.short_description = 'Tarifa'
get_per_hor_display.short_description = 'Periodo horario'
get_per_tar_display.short_description = 'Periodo tarifario'
Now the filter page will display columns named as the short description BUT with the real value of the field instead of theirs "choice value".
Addiotionally if I mark 'per_tar' as non editable it will show also "(nothing)" in the change from instead of it´s stored value.
What am I doing wrong?
Diving in internet I found the answer here:
http://thinkingnectar.com/2009/django-get_foo_display-behaviour-with-characters-and-integer-fields/
The post comment that when the field is char type, the choice key should be a string but when it´s an integer field it should be an interger!
Here was my problem! Changing strings to integer made it work.

How to display previous value on Min Miles text field

I want to display a previous value on Min Miles and that should not be editable. I want like
Default value of Min Miles is 0.
When I click on Add More Range then In the new form - Min Value should be Max Value of Previous Form.
I am using semantic form for. Please Help Me. How can I do this...
Regarding your second question, and assuming that the new form appears through javascript, without page reloading, you can grab the
field value with javascript and use it as the default value for the
new field. The "add new range"
Something Like
function getvalue(){
var inputTypes_max = [],inputTypes_min = [],inputTypes_amount = [];
$('input[id$="max_miles"]').each(function(){
inputTypes_max.push($(this).prop('value'));
});
$('input[id$="amount"]').each(function(){
inputTypes_amount.push($(this).prop('value'));
});
var max_value_of_last_partition = inputTypes_max[inputTypes_max.length - 2]
var amount_of_last_partition = inputTypes_amount[inputTypes_amount.length - 2]
if (max_value_of_last_partition == "" || amount_of_last_partition == "" ){
alert("Please Fill Above Details First");
}else{
$("#add_more_range_link").click();
$('input[id$="min_miles"]').each(function(){
inputTypes_min.push($(this).prop('id'));
});
var min_id_of_last_partition=inputTypes_min[inputTypes_min.length - 2]
$("#"+min_id_of_last_partition).attr("disabled", true);
$("#"+min_id_of_last_partition).val(parseInt(max_value_of_last_partition) + 1)
}
}
I have Used Jquery's End Selector In a loop to get all value of max and amount field as per your form and get the ids of your min_miles field and then setting that value of your min_miles as per max_miles
It worked For me hope It works For You.
Default value of a field can just be passed in the form builder as a second parameter:
...
f.input :min_miles, "My default value"
Of course I do not know your model structure but you get the idea.
Regarding your second question, and assuming that the new form appears through javascript, without page reloading, you can grab the field value with javascript and use it as the default value for the new field. The "add new range" click will be the triggerer for the value capture.
Something like (with jQuery):
var temp_value = '';
$('#add_more_range').click(function(){
temp_value = $('#my_form1 #min_miles').value();
$('#my_form2 #max_miles').value(temp_value);
});
Again I am just guessing the name of the selectors, but the overall approach should work.
If you are also adding dinamically to the page the "Add new range" buttons/links, then you should delegate the function in order to be inherited also for the so new added buttons:
$('body').on('click', '#add_more_range', function(){...});

How would I find the text of a node that has a specific value for an attribute in groovy?

I'm using XMLSlurper. My code is below (but does not work). The problem is that it fails when it hits a node that does not have the attribute "id". How do I account for this?
//Parse XML
def page = new XmlSlurper(false,false).parseText(xml)
//Now save the value of the proper node to a property (this fails)
properties[ "finalValue" ] = page.find {
it.attributes().find { it.key.equalsIgnoreCase( 'id' ) }.value == "myNode"
};
I just need to account for nodes without "id" attribute so it doesn't fail. How do I do that?
You could alternatively use the GPath notation, and check if "#id" is empty first.
The following code snippet finds the last element (since the id attribute is "B" and the value is also "bizz", it prints out "bizz" and "B").
def xml = new XmlSlurper().parseText("<foo><bar>bizz</bar><bar id='A'>bazz</bar><bar id='B'>bizz</bar></foo>")
def x = xml.children().find{!it.#id.isEmpty() && it.text()=="bizz"}
println x
println x.#id
Apprently I can get it to work when I simply use depthFirst. So:
properties[ "finalValue" ] = page.depthFirst().find {
it.attributes().find { it.key.equalsIgnoreCase( 'id' ) }.value == "myNode"
};

Resources