Page 3 of 4

Posted: Fri Sep 07, 2007 11:53 am
by Luke
I sure can. :)

forms.py

Code: Select all

from django import newforms as formsfrom django.contrib.localflavor.usa import forms as usforms#from pulse.lib.localflavor.usa.forms as pulseforms class RegisterForm(forms.Form):    username =          forms.CharField(max_length=15)    password =          forms.CharField(widget=forms.PasswordInput())    verify_password =   forms.CharField(widget=forms.PasswordInput())    first_name =        forms.CharField(max_length=25)    last_name =         forms.CharField(max_length=35)    business_name =     forms.CharField(max_length=45)    business_phone =    usforms.USPhoneNumberField()    business_phone2 =   usforms.USPhoneNumberField(label='Alternate Phone', required=None)    business_fax =      usforms.USPhoneNumberField(required=None)    email =             forms.EmailField()    business_address =  forms.CharField(max_length=100)    business_city =     forms.CharField(max_length=30, label='City')    business_state =    forms.CharField(label='State', widget=usforms.USStateSelect())    business_zip =      forms.CharField(max_length=10, label='Zip')    business_type =     forms.CharField(max_length=200)    website =           forms.URLField(required=None)    billing_address =   forms.CharField(max_length=100)    billing_city =      forms.CharField(max_length=30, label='City')    billing_state =     forms.CharField(label='State', widget=usforms.USStateSelect())    billing_zip =       forms.CharField(max_length=10, label='Zip')
views.py (controller)

Code: Select all

def register(request):    from pulse.forms import RegisterForm     if request.method == 'POST':        data = request.POST.copy()        form = RegisterForm(data)                if not form.is_valid():            form.data['password'] = None            form.data['verify_password'] = None        else:            # do something cool with the data                else:        form = RegisterForm()        return render_to_response('register.html', {'registerform':form,}) 
register.html

Code: Select all

{% extends "base.html" %} {% block content %}        <form method="post" action="{{ base_href }}/django/pulse/register/">      <fieldset id="member-info">          <legend>Company Information</legend>         <div class="meta">                  <p class="header">Contact Information</p>                <p>Please fill out your contact information. We need this information for some cool purpose.</p>              </div>                      <dl>              {% for element in registerform %}                  <dt>{{ element.label_tag }}</dt>                  {% if element.errors %}                    <dd class="error">                        <div class="message">                            <p>{{ element.errors }}</p>                              {{ element }}                            </div>                        </dd>                      {% else %}                    <dd>{{ element }}</dd>                      {% endif %}                  {% endfor %}                </dl>                <div class="buttons"><input type="submit" value="Save"></div>            </fieldset>      </form> {% endblock %}

Posted: Fri Sep 07, 2007 12:05 pm
by John Cartwright
Neat :)

Posted: Fri Sep 07, 2007 12:13 pm
by Christopher
Yes ... nice.

How would you do it if you did some of the for elements as HTML in the template (e.g., hidden, text and textarea) rather than generating everything?

Posted: Fri Sep 07, 2007 12:33 pm
by Luke
Umm I guess something like this if you want some generated and some not... this is just a quick stab at it. Also, the syntax may not be 100% but I know it goes something like this

Code: Select all

{% extends "base.html" %} {% block content %}       <form method="post" action="{{ base_href }}/django/pulse/register/">     <fieldset id="member-info">         <legend>Company Information</legend>         <div class="meta">                 <p class="header">Contact Information</p>               <p>Please fill out your contact information. We need this information for some cool purpose.</p>             </div>                     <dl>         <dt>{{ registerform['some_element'].label_tag }}</dt>           {% if registerform['some_element'].errors %}                   <dd class="error">                       <div class="message">                           <p>{{ registerform['some_element'].errors }}</p>                             <input type="text" name="{{ registerform['some_element'].name }}" value="{{ registerform['some_element'].value }}" />                           </div>                       </dd>                     {% else %}                   <dd><input type="text" name="{{ registerform['some_element'].name }}" value="{{ registerform['some_element'].value }}" /></dd>                     {% endif %}             {% for element in registerform %}         {% if element not in spec_elem %} <!-- spec_elem would be a dictionary defined in the view populated with elements names you want to display manually (django calls the controller the view and the view the template (whacky fellas)) -->                 <dt>{{ element.label_tag }}</dt>                 {% if element.errors %}                   <dd class="error">                       <div class="message">                           <p>{{ element.errors }}</p>                             {{ element }}                           </div>                       </dd>                     {% else %}                   <dd>{{ element }}</dd>                     {% endif %}         {% endif %}                 {% endfor %}               </dl>               <div class="buttons"><input type="submit" value="Save"></div>           </fieldset>     </form> {% endblock %}
To see better demonstration, (django seems to be pretty damn well documented) check out the newforms docs: http://www.djangoproject.com/documentation/newforms/

The only issue with django is that you pretty much have to have a dedicated box for it to be worth using. Or so it seems.

Posted: Sun Sep 09, 2007 3:58 pm
by Christopher
I was looking back at my Skeleton Form Controller to see how it compares to Djanjo. The Skeleton code used a building block approach to almost everything which is a different basic design strategy. That sometimes makes it handy for comparison. I think you could do the same things, not as neatly as Django and you would have to code some of the widgets, but it may be more easily customizable.

Form field definitions in the controller:

Code: Select all

// create parameter handler bound to 'field1'
$field1= new A_Controller_FormParameter('field1');
// add filter for this parameter
$field1->addFilter(new A_Filter_Regexp('/[^a-zA-Z]/', ''));
// add required rule
$field1->addRule(new A_Rule_NotNull('field1', 'Please enter Field 1'));
// set to load/create a helper class that builds a <select> with name and value set automatically
$field1->setType(array(
            'renderer'=>'A_Html_Form_Select', 
            'values'=>array('Y', 'N', 'M'), 
            'labels'=>array('Yes', 'No', 'Maybe')
            ));
// attach to form
$this->addParameter($field1);
        
$field2= new A_Controller_FormParameter('field2');
$field2->addFilter(new A_Filter_Regexp('/[^0-9]/', ''));
$field2->addRule(new A_Rule_NotNull('field2', 'Please enter Field 2'));
$field2->setType(array(
            'renderer'=>'A_Html_Form_Text',
            'size'=>'10'
            ));
$this->addParameter($field2);   
 
And the view template would be like:

Code: Select all

<div>Field 1:
      <?php $p1 = $this->getParameter('field1'); $p1->render(); ?>
      <span class="error"><?php echo implode(', ', $p1->error_msg); ?></span>
</div>
<div>Field 2:
      <?php $p2 = $this->getParameter('field1'); echo $p2->render(); ?>
      <span class="error"><?php echo implode(', ', $p2->error_msg); ?></span>
</div>
 
It is interesting how much many of these system look similar. The main conceptual difference is that Django (and things like QuickForm) take the approach of defining for form specific things -- like Django's field defining arguments. Django looks nicer. I never liked QuickForm, preferring the building block approach of adding rules and filters to create behavior. And I prefer to treat forms controller-wise like any other request -- rather than having a black box handle them. Some of the custom field types are nice, though I am not sure I would use them over just doing something in Javascript.

Posted: Mon Sep 10, 2007 10:09 am
by Luke
The thing I like about django is that although you can use it to render almost the entire form, you don't have to, and if you don't want to, it is still quite simple to render bits and pieces of it as you see fit. This is not really the case as far as QuickForms is concerned. QuickForms is what I've been using for over a year now and I really don't like its approach.

Posted: Mon Sep 10, 2007 12:52 pm
by Christopher
I like being able to do some or all, although I rarely do much HTML building in code -- mainly because my sites mostly need to editable via a web interface. I am still on the fence between form specific solutions and building it out of generic classes. I do the latter, but I can see the advantages of speed and readability of the former. But for me forms are much more about request processing that HTML building.

Can the Django new forms manager do multi-form wizards? (Application Controller)

Posted: Mon Sep 10, 2007 1:43 pm
by Luke
To my knowledge it can, but I am not sure of the exact process. I think we have similar opinions as far as form handling. For me to use a forms library, it must be able to process the request (validate & filter) and then also be able to return errors correctly. The only portion of the form I care for a library to generate are the elements and labels since, when generated, you can be sure that the ids line up with the labels properly (ids must match the for attrib on the label), and also things like selects and radios are made more simple.

Posted: Tue Sep 11, 2007 4:44 pm
by Luke
Oh wow... I just took a look at this: http://framework.zend.com/manual/en/zen ... input.html. I am completely blown away by how completely lame that is. Why on earth is it so complicated?? What are those guys smoking over there?? :roll:

Posted: Tue Sep 11, 2007 5:05 pm
by mrkite
I use PEAR::Validate for actually validating email addresses etc.

Then I just use basic if statements to validate the form elements, populating an $errors hash if there are any.

Code: Select all

$errors=array();
if (trim($_POST['username'])=='')  $errors['username']="Username is required";

// and somewhere in the form

<? if (count($errors)) { ?> There were errors <? } ?>

<div>Username: <input type="text" name="username" value="<?=html_special_chars($_POST['username'])?>" /> <?=$errors['username']?></div>
etc etc

Throwing it all into a class would be tidy and nice.. but it's not urgent.

Posted: Tue Sep 11, 2007 5:11 pm
by Christopher
I felt like myself and other had them talked out of that kind of stuff for a while, but they just can't help themselves. Validator and Filter chains are pretty worthless unless you pass them a container (hint: a Request object) that they can act upon. They are still patching things around to make "custom" error message are an easier workaround. Urgh....

I don't know if you noticed, but I gave up giving input to ZF about six months ago. What's the point. The Zend guys can only see how they solve problems (or are learning to). And the community ends up with people like the Zend_Layout guy who kind of steamrollered our Paddy with his zeal.

Think about your controller code to use modules and then think "extreme simplicity" ;)

Posted: Tue Sep 11, 2007 5:32 pm
by Luke
Are there any other proposals that may be able to knock this horrific idea out of the framework, or are they satisfied with this mess?

EDIT: WOW! Do people actually use this stupid thing? It's impossible. It's complete nonsense. What a joke!

Posted: Tue Sep 11, 2007 6:28 pm
by mrkite
The Ninja Space Goat wrote:Are there any other proposals that may be able to knock this horrific idea out of the framework, or are they satisfied with this mess?
I like asp.net's validation framework. Does that make me a heretic here?

I don't know how the concept could be used by php though because of the differences in the way asp.net and php operate.

Posted: Tue Sep 11, 2007 7:04 pm
by Luke
This is seriously unbelievable. I have never been so confused and irritated with a library / framework in my life. This makes no sense. None. Take a look at what I've accomplished in the last 3 hours:

Code: Select all

$validators = array (
            'vendor_name'   => array(
                array('NotEmpty'),
                array('StringLength', 0, 100),
                'messages' => array(
                   array(Zend_Validate_NotEmpty::IS_EMPTY => 'This field is required')
                )
            ),
            'corporate_name'   => array(
                array('StringLength', 0, 200)
            ),
            'code'   => array(
                array('NotEmpty'),
                array('StringLength', 0, 5),
                array('Regex', '#^[a-zA-Z0-9_-]+$#'),
                'messages' => array(
                    //Zend_Validate_NotEmpty::IS_EMPTY => 'This field is required',
                    Zend_Validate_Regex::NOT_MATCH => 'This is an invalid code. It can only contain numbers, letters, dashes, and underscores'
                )
            )
        );
I am still guessing at how to make error messages come up. The manual says that this is how you do it, and yet when I do this it tells me there is no message template that matches the value of "Zend_Validate_Regex::NOT_MATCH". This is easily the WORST validation idea I've ever come across. I am completely blown away that this mess was allowed to slip through the cracks. It seems almost like a cruel joke. Who uses code like this??
Image

Posted: Tue Sep 11, 2007 7:04 pm
by wei
mrkite wrote:
The Ninja Space Goat wrote:Are there any other proposals that may be able to knock this horrific idea out of the framework, or are they satisfied with this mess?
I like asp.net's validation framework. Does that make me a heretic here?

I don't know how the concept could be used by php though because of the differences in the way asp.net and php operate.
can be done and has been done
http://pradosoft.com/demos/quickstart/? ... Validation
source:
http://trac.pradosoft.com/prado/browser ... ebControls