Jump to content

Form class -- more work than it's worth?


nloding

Recommended Posts

I have a Form class.  It has a validation() method that validates the various fields passed to it via POST.  If an error is encountered, Form::hasError is set to true, and Form::errors['fieldname'] is set to the error ("Invalid username", "Not a valid email address", whatever).  The form action is itself, so in the markup and logic for the form creation, I was constantly doing if($form->hasError) and then if(array_key_exists('fieldname)), etc.  I wanted to tighten that up, make some cleaner code.

 

So I'm trying this approach: have a drawRadio method for radio buttons; drawLabel for the <label> fields; etc.  I want people's thoughts on it.  I'm new to OOP, and at first this sounded like a great idea, but now it seems kinda ... well, I'm doubting it's worth the effort.  Thoughts please!!!!

 

<?php
/* USAGE:
* $name = name value for the radio button (name="$name")
* $value = value of the radio button (value="$value")
* $checked = is this the default button? (default = false)
* $keyword = what validation method to use, extracted by $this->validatate()
* $extras = array of additional options (ie, $extras['onClick'] = 'javascript:function(parameter)')
*/

public function drawRadio($name, $value, $checked = false, $keyword = null, $extras = null) {
	//Format: $left_text <input type="radio" name="($keyword)$name" value="$value" if($checked) checked="checked"
	//			[$extras: class=, onClick=, ...] /> $right_text

	if(is_array($extras)) {
		if($extras['position'] == 'left')
			$radio .= $extras['text'] . ' ';
	}

	$radio .= '<input type="radio" name="';
	if($keyword != null) $radio .= '(' . $keyword . ')';
	$radio .= $name . '" value="' . $value . '"';

	if($checked) $radio .= ' checked="checked"';

	$class = false;
	if(is_array($extras)) {
		foreach($extras as $key=>$value) {
			if($key != 'text' && $key != 'position' && $key != 'class')
				$radio .= ' ' . $key . '="' . $value . '"';
			if($key == 'class') $class = $value;
		}
	}

	if($class) $radio .= ' class="' . $class;
	if($this->hasError) {
		if(array_key_exists($name, $this->errors)){
			if(!$class) $radio .= ' class="form-radio-error"';
			else $radio .= ' form-radio-error"';
		} else {
			$radio .= '"';
		}
	} else {
		$radio .= '"';
	}

	$radio .= ' />';

	if(is_array($extras)) {
		if($extras['position'] == 'right')
			$radio .= $extras['text'] . " ";
	}

	echo $radio;
}

 

And in use:

 

<form method="POST" action="form.php">
<?php $form->drawRadio('action', 'action_add', ($post_values['action'] == 'action_add') ? 'true' : 'false', 'Action', array('text'=>'Add', 'position'=>'right')); ?>
<!-- Should output:
	<input type="radio" name="(Action)action" value="action_add" checked="checked" /> Add
 Provided there isn't an error and $post_values['action'] == 'action_add' -->
</form>

Link to comment
Share on other sites

i tried various form classes and a lot actually really sucked but i have found one that was worth using and have been expanding this class for a year or so. in the end it saved me tons on time validating forms and produce cleaner code.

 

oop can be helpfull but just use it when it needed in your case it can be extremely usefull.

 

if youre form class seems to be too diffucult try this one.

i have used it and it was pretty usefull

 

http://www.finalwebsites.com/snippets.php?id=15

Link to comment
Share on other sites

I'll take a look at that class, see how other's have done it.  Most of the example/open-source form classes I have found so far pull info from a database and build the form on that, but I wanted more flexibility.

 

The more I stare at my code, and my intentions behind it, I am actually saving myself time.  It's nice to not have to put all those damn if/else statements in the form markup -- just call a function that does it automatically for that form while drawing the XHTML markup.

 

I think I'm getting a stronger grasp on the principals and advantages and, ultimately, the uses of OOP.

Link to comment
Share on other sites

I wrote a form class about a year ago.  The HTML in it was specialized to a specific project, as was the entire form class.  I used it extensively for that project as just about every page had a page long form.  (It was basically pulling/manipulating data from a complex database, thus lots of forms were needed x.x.)

 

Anyway, I figure I might as well share:

 

Hrmmm was gonna post it here, but it's quite long, so:

 

I can't think of a good place to paste it, so... http://corbin.no-ip.org/phpfreaks/Forms.class.php  (Hopefully it'll stay up for you to see it ;p.  Been up 16.75 days...)

Link to comment
Share on other sites

Corbin, thanks, but I can only see the form it outputs, not the code behind it.  Can you just post it as a txt file?

 

I'm continuing with my class, and I hope to make it extensible and flexible enough to use on most projects (and just extend the class for specialized circumstances).  I'll post it here when I'm done, maybe, as a tutorial.

Link to comment
Share on other sites

It's more a case of "what's it worth"

 

If you're on a project where you need one form, it's not worth the overhead. If you're going to need to creat forms on-the-fly, it might be worth your time to create/modify one. Make it nice and re-usable and keep it for future projects :)

Link to comment
Share on other sites

I have to agree with deadonarrival.  Since that project, I've never used a form class, although that project would've taken much longer without.

 

One of the things I dislike about my form class in hindsite is how oriented it was to that specific project.  But, I guess when you have something that needs to look a certain way like a form, either you're going to pass a ton of variables, or it's going to be oriented to a certain project.

 

(Or I guess a ton of CSS could be used... hrmmm)

Link to comment
Share on other sites

CSS = sexy.

 

I've never made a form class, but I'd strongly suggest making it output only the elements, with no formatting, and let the style sheet control the rest.

 

Go beyond seperating data and logic from design, by seperating style from structure.

 

Sort of a

MC-SS system (Model, Controller, Style, Structure) :)

[Yes, I just overcomplicated an already complicated paradigm, oops!]

Link to comment
Share on other sites

Ditto to previous comments about the need for a form class depending on the size of the project.  If all you need is a registration, login, and contact form for your site, then it's not really worth the trouble.

 

However, if your site has a lot of forms and their based very closely on the models in your database, then it would surely be worth the time to create a form class that can easily build the form from a model instance, perform validation, and provide basic CRUD functions.

 

The real trick here is the first several hundred times you write any OO code, it'll suck and not be reusable.  So it almost never seems to be worth the trouble.  So what you need to do is do it anyways, and keep doing it, and keep trying to improve it.  Then go buy a book on design patterns and you'll see some canned solutions that solve many of the problems you ran into yourself.  You'll be one step closer to OOP zen at that point. ;)

Link to comment
Share on other sites

deadon/corbin: That's exactly my goal.  The only required element(s) are, depending on the input type, the name and the value.  A keyword is optional if using my validation technique, and a $extras array can be included.  In this array, the keys are the keywords.  For instance, you could do $extras['onChange']='javascript:...'.  Plug that in, and when the element is drawn/echoed, that keyword/value combo is included.  The same applies to classes: $extras['class']='my-input-class'.

 

See my new post for a tiny example of what I'm going for.  I was looking for some help on the logic.

 

I think this is worthwhile because my goal is to make it usable in EVERY site I do.

 

@roopurt: Currently, I'm not building the form based on anything in a database/template.  That option will undoubtedly come later.

Link to comment
Share on other sites

I agree that in most casses a form class wouldnt be usefull. however if you have build pages that uses forms all the time it kinda gets tiring to go through the whole process of building in the validation all over again. I've been building my form class for quiete a while now and made tons of mistakes in the start but its finally comming together now and building a form is now just 5 min work for both server and clientside form validation even if the form is huge

Link to comment
Share on other sites

Throwing my own stuff out there: Thacmus

Tutorial: Form (old, but still applies - too lazy to update...)

You can view the source under Source, thacmus/lib/field/* (the files in there).

 

You certainly don't have to use it, certain things you may like / hate.

 

DNS error on deadimp.org

 

C:\Users\Corbin>ping deadimp.org
Ping request could not find host deadimp.org. Please check the name and try again.

Link to comment
Share on other sites

  • 3 weeks later...
DNS error on deadimp.org

The DNS for deadimp.org should be working now - I don't know why there would be a DNS error.

Kind of a late response.

 

And to add something slightly random, Thacmus is now on SVN, so it should be easier just to browse the current source.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.