Jump to content

OOP for Forms?


tmallen

Recommended Posts

I'm trying to really learn OOP for PHP so I can reuse more code locally. The problem is, knowing all of the terminology hasn't done a thing for me as far as producing real results. I want to write a class that easily generates and processes a standard mail form. It could be more generic even and have a mail() function.

 

So, from scratch:

<?php

class Form
{
    public function display()
    {
    }
}

Where do I start as far as outputting an HTML form based on, say, a hash? Please point out anything and everything wrong here, because I don't know very much about using OOP practically.

 

- Really f'ing confused...

Link to comment
https://forums.phpfreaks.com/topic/108754-oop-for-forms/
Share on other sites

class Form

{

    public $connection;

    function __construct($connection = "null") {  /*I'm assuming you want to do user validation.  You can figure out what to do if you aren't*/

              if (!$connection) {

                    $connection = mysql_connect("stuff");

                    //more stuff

              }

              $this->connection = $connection;

    }

    public function validate($form_data) {

                //process stuff here

                return true; //OR return false if it didn't work.  You know how to do that, lol

    }

    public static function clean($text) {

                return mysql_real_escape_string($text);

    }

}

 

Just an example.   Now, you can do:

$conn = mysql_connect("stuff");

$form = new Form($conn);

if ($form->validate($_POST)) {

       $post = Form::clean($text);

}

else {

       die("Validation failed.");

}

 

REALLY basic example.

 

Link to comment
https://forums.phpfreaks.com/topic/108754-oop-for-forms/#findComment-557805
Share on other sites

Thanks! I'm more interested in the proper application of OOP techniques for either generating HTML, in this case for a form, or better yet, for filling a view. There really aren't any "Build your own MVC framework using OOP" books floating around at my bookstores...My PHP knowledge is pretty good, but I'm hitting a wall right now as I try to implement OO techniques. Maybe I should write an imperative/procedural series of functions and try to convert it to an Object??

Link to comment
https://forums.phpfreaks.com/topic/108754-oop-for-forms/#findComment-557808
Share on other sites

Oh, generating a form?  Here:

 

class Form {
  protected $form;
  function __construct($name, $action, $method, $other=null) {
       $this->form .= sprintf('<form action="%s" method="%s" name="%s"', $action, $method, $name);
       if ($other) {
              foreach ($other as $k=>$v) {
                 $this->form .= " $k=\"$v\"";
              }
        }
        $this->form .= ">";
   }
   public function getForm() {
         return $this->form;
   }
   public function textInput($name, $maxlength=15) {
        $this->form .= sprintf('<br /><input type="text" name="%s" maxlength="%d" />', $name, $maxlength);
   }
   //continue this, lol
}

 

Basic stuff, you can add more to it, such as a $other var for each type of field, for things like id and such.  I made it on the constructor to show you an example.

Link to comment
https://forums.phpfreaks.com/topic/108754-oop-for-forms/#findComment-557815
Share on other sites

Why is NULL in quotes here?

 

__construct($connection = "null")

 

That defaults to a string 'null' and not a NULL value.

 

Using a class is pretty much building a self-contained script

 

Here's a quick example class showing some key elements you can use. This assumes a decent amount of previous php experience.

 

<?php

class sample {

# All variables defined here will be available by any method (function)
# of this class. They can be accessed using $this->varname

# Declare some variables that can be used outside the class as well
public $buffer, $elements = array();

# Declare some variables that will be protected from outside of the class
private $name, $action, $output = TRUE, $e = array();

# Constructor method - called when the class is made. Can be named 'sample'
# alternatively
function __construct ( $name, $action = FALSE, $doOutput = TRUE ) {

	$this->name = $name;
	$this->action = $action;

	if ( $doOutput == FALSE )
		$this->output = FALSE;

}

# A sample method accessable from outside the class
public function addElement ( $name, $type, $value = FALSE ) {

	if (  preg_match( '/[^\\w-]++/', $name )  ) {
		$this->error( 'Attempted to add an element with an invalid name ('. $name . ')' );
		return FALSE;
	}

	switch ( $type ) {

		case 'text':
			$this->elements[$name] = '<input type="text" name="'. $name .'"'. ( empty($value) ? '' : ' value="'. htmlentities($value) .'"' ) .' />';
			break;
		case 'password':
			$this->elements[$name] = '<input type="password" name="'. $name .'" />';
			break;
		case 'textarea':
			$this->elements[$name] = '<textarea name="'. $name .'">'. ( empty($value) ? '' : htmlentities($value) ) .'</textarea>';
			break;
		case 'dropdown':
			if (  !is_array( $value ) || empty( $value )  ) {
				$this->error( 'Attempted to make a dropdown with a string or empty array ('. $name .')' );
				return FALSE;
			}
			$buffer = '<select name="'. $name .'">' . "\n";
			foreach ( $value as $val => $text )
				$buffer .= '  <option value="'. htmlentities($val) .'">'. htmlentities($text) .'</option>' . "\n";
			$buffer .= '</select>';
			$this->elements[$name] = $buffer;
			break;
		default:
			$this->error( 'Attempted to add unknown element "'. $type .'" ( '. $name . ')' );
			return FALSE;

	}

}

# Another sample public method
public function buildForm ( ) {

	if ( count($this->elements) < 1 ) {
		$this->error( 'Elements must be added before building form' );
		return FALSE;
	} elseif (  preg_match( '/[^\\w-]++/', $this->name )  ) {
		$this->error( 'Attempted to create a form with an invalid name ('. $name . ')' );
		return FALSE;
	}

	$buffer = '<form name="'. $this->name .'" action="'. $this->action .'">' . "\n";

	foreach ( $this->elements as $name => $content ) {

		$buffer .= '<b>'. $name . '</b><br />' . "\n";
		$buffer .= $content . "\n<br /><br />\n";

	}

	$buffer .= '<input type="submit" name="submit" value="Submit" />' . "\n";
	$buffer .= '</form>';

	if ( $this->output === TRUE )
		echo $buffer;

	return $buffer;
	echo 'lol';

}

# A sample method protected from outside the class
private function error ( $text = FALSE ) {

	if ( !empty($text) ) {
		$this->e[] = $text;
	}

}

public function errorReport( ) {

	if (  empty( $this->e )  )
		return FALSE;

	$buffer = '<b>Errors:</b><br />' . "\n";
	foreach ( $this->e as $error )
		$buffer .= $error . "<br />\n";

	return $buffer;

}

}

# The class in use

$form = new sample( 'thisForm', 'somepage.php' );

$form->addElement( 'box1', 'text', 'Some "values"..' );
$form->addElement( 'selectBox', 'dropdown', array('val1'=>'Value 1', 'val2'=>'Value 2') );

if (  ( $err = $form->errorReport() ) === FALSE )
$form->buildForm();
else
echo $err;


?>

 

Hope that helps explain classes a little

Link to comment
https://forums.phpfreaks.com/topic/108754-oop-for-forms/#findComment-557882
Share on other sites

OK, I'm slowly getting this. Can anyone take a look here and point out what I'm doing right/wrong? Note that I know I haven't taken care of every input type.

 

<?php

class Form
{
    public $elements;

    function __construct($elements)
    {
        $this->elements = $elements;
    }

    public function build()
    {
        $output = '<form>';

        foreach($this->elements as $name => $type) {
            if ($type != 'submit') {
                $output .= "<label>$name</label>";
            }

            switch($type) {
            case 'text':
                $output .= "<input type='text' name='$name' />";
                break;
            case 'textarea':
                $output .= "<textarea name='$name'></textarea>";
                break;
            case 'submit':
                $output .= "<input type='submit' value='$name' />";
                break;
            default:
                $output .= "<input type='text' name='$name' />";
                break;
            }
        }

        $output .= '</form>';

        return $output;
    }
}

$myForm = new Form(array(
    'Name' => 'text',
    'Phone' => 'text',
    'Comments' => 'textarea',
    'Submit' => 'submit'
));

echo $myForm->build();

Link to comment
https://forums.phpfreaks.com/topic/108754-oop-for-forms/#findComment-557982
Share on other sites

I have made something like this, it's more "divided" and a bit simple, cause im not so good at programming =P, hope it helps, it has a spaces divider and a blank divider.

 

An example of the use,

$class1 = new formcreator;
$encrypt = "application/x-www-form-urlencoded";
$action = "validator.php";

echo $class1->main(POST, login, $encrypt, $action);
echo $class1->body(usuario, text, 15, 14, 2, 0, usuario, lol);
echo $class1->body(password, password, 13, 8, 2);
echo $class1->body(permisos, text, 1, 1, 2);
echo $class1->body(check, checkbox, 15, 14, 2, 0, usuario, lol);
echo $class1->boton(submit, Enviar);

 

 class formcreator {
       function main ($metodo, $nombre, $encryptacion, $action) {
                echo '<FORM method="'.$metodo.'" enctype="'.$encryptacion.'" action="'.$action.'">';
       }

       function body ($nombre, $tipo, $size, $max, $lineas = 0, $espacios = 0, $referencia = 0, $value = "") {
                if ($referencia == 0) {
                   if ($value != ""){
                      echo '<INPUT type="'.$tipo.'" name="'.$nombre.'"size="'.$size.'" maxlength="'.$max.'" value="'.$value.'">';
                   }
                   else {
                        echo '<INPUT type="'.$tipo.'" name="'.$nombre.'"size="'.$size.'" maxlength="'.$max.'">';
                   }
                }
                else {
                     echo ''.$referencia.' <INPUT type="'.$tipo.'" name="'.$nombre.'"size="'.$size.'" maxlength="'.$max.'">';
                }
                if ($lineas == 0) {
                $total_espacios = 0;
                   while ($espacios != $total_espacios) {
                         echo ' ';
                         $total_espacios++;
                   }
                }
                else {
                   $total_lineas = 0;
                   while ($lineas != $total_lineas) {
                   echo '<br>';
                   $total_lineas++;
                   }
                }
       } 

       function boton ($tipo, $texto) {
                echo '<INPUT type="'.$tipo.'" value="'.$texto.'">';
       }

       function close () {
                echo "</FORM>";
       }
}

Link to comment
https://forums.phpfreaks.com/topic/108754-oop-for-forms/#findComment-557987
Share on other sites

Updated again, now with legend and radio type included. Any advice is appreciated. Should I be breaking this up into more functions/classes at this point?

 

<?php

class Form
{
    public $elements;

    function __construct($elements, $method, $action, $legend)
    {
        $this->elements = $elements;
        $this->method = $method;
        $this->action = $action;
        $this->legend = $legend;
    }

    public function build()
    {
        $html = '<form action="' . $this->action . '" method="' . $this->method . '">';
        $html .= '<fieldset>';
        $html .= "<legend>$this->legend</legend>";

        foreach($this->elements as $name => $properties) {
            switch($properties['type']) {
            case 'text':
            case 'textarea':
                $html .= "<label for='$name'>{$properties['title']}</label>";
                break;
            }

            switch($properties['type']) {
            case 'text':
                $html .= "<input type='text' name='$name' id='$name' />";
                break;

            case 'textarea':
                $html .= "<textarea name='$name'></textarea>";
                break;

            case 'radio':
                $html .= '<fieldset>';
                foreach($properties['options'] as $id => $title) {
                    $html .= "<input type='radio' id='$id' value='$id' name='$name' />";
                    $html .= "<label for='$id'>$title</label>";
                }
                $html .= '</fieldset>';
                break;
            }
        }
        
        $html .= '</fieldset>';
        $html .= '</form>';
        return $html;
    }
}

$formFields = array(
    'name' => array(
        'title' => 'Name', 
        'type' => 'text'
    ),

    'comments' => array(
        'title' => 'Comments', 
        'type' => 'textarea'
    ),

    'preferred_com' => array(
        'type' => 'radio',
        'options' => array(
            'email' => 'Email',
            'phone' => 'Phone',
            'fax' => 'Facsimile'
        )
    ),

    'submit' => array(
        'title' => 'Submit Form', 
        'type'=> 'submit'
    ),
);

$myForm = new Form($formFields, 'post', 'form.php', 'Signup');

echo $myForm->build();

Link to comment
https://forums.phpfreaks.com/topic/108754-oop-for-forms/#findComment-557989
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.