Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

url - Symfony2.1 using form with method GET

I need help on using Symfony2.1 forms with method=GET and a clean URL space.

I am creating a "filter" which I'd like to set in the URL so that people can bookmark their links.

So, very simply the code:

$form = $this->createFormBuilder($defaultData)
    ->add('from', 'date', array('required' => false, 'widget' => 'single_text', 'format' => 'dd.MM.yyyy'))

I render the form widget and all is fine.

However when I submit the form, it produces very ugly GET parameters:

/app_dev.php/de/event?form%5Bfrom%5D=17.11.2012

This is because the input name is of course form[from]

So to clean the URL space, I made myself a theme:

{% block widget_attributes %}
{% spaceless %}
    id="{{ id }}" name="{{ id }}"{% if read_only %} disabled="disabled"{% endif %}{% if required %} required="required"{% endif %}{% if max_length %} maxlength="{{ max_length }}"{% endif %}{% if pattern %} pattern="{{ pattern }}"{% endif %}
    {% for attrname,attrvalue in attr %}{{attrname}}="{{attrvalue}}" {% endfor %}
{% endspaceless %}
{% endblock widget_attributes %}

where I replaced name="{{ full_name }}" with name="{{ id }}".

This works well - my URL space is cleaner:

/app_dev.php/de/event?form_from=17.11.2012

I guess I could live with that - although ideally from=xxx would be better. That is the first and more minor problem.


The second problem is that I can't get the form to bind anymore - this is obvious because the parameter "form" is no longer set - "form_from" has replaced it, but when you do a bind it is still expecting form[].

I tried to fix that like this:

$fromDate = $this->get('request')->query->get('form_from', null);
$request->query->set('form', array('from' => $fromDate);

But that doesn't work. I also suspect that I am digging a huge hole of hacks at the moment.

So, the question is: should I just live with the form%5Bfrom%5D url, or is there a better way to do all of this (without using POST obviously)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set the name of the root form to empty, then your field name will be just form. Do so via

// the first argument to createNamedBuilder() is the name
$form = $this->get('form.factory')->createNamedBuilder(null, 'form', $defaultData)
    ->add('from', 'date', array(
        'required' => false,
        'widget' => 'single_text',
        'format' => 'dd.MM.yyyy'
    ));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...