views:

104

answers:

3

I'm coding up a small script that'll take form data and do something with it. If it fails, it shows the error and the form again. If it succeeds, it'll show a success message.

The backend code is using classes that'll throw exceptions if there's an error with the form data. The calls to the classes will be wrapped in a try{} catch{}.

What would be the best way to show the form twice?

I need something like:

If form submitted: 

   Try:
      Add the account via class
   Catch:
      Echo the error
      Show the form 

   Echo succcess

Else:
   Show the form
+1  A: 

Encode the HTML for the form in a variable, and echo out the variable at both locations.

$form = "<form>...</form";

if ($_POST) {
  if (addAccount($fname,$email)) {
    print "Success";
  } else {
    print "Errors";
    print $form;
  }
} else {
  print $form;
}
Jonathan Sampson
I was thinking that'd be the way to go
servxr
You might even prefer the HEREDOC syntax for the form variable declaration to make the HTML more readable. See: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
Jonathan Sampson
+1  A: 

For simple forms, I wrote like this:

<?php

   if ($submit)
   {
   var errorFound=0;
   if (empty($form_variable))
   { 
     errorFound=1; 
     $error_str="empty string";
   }

   if (!$errorFound)
   { process whatever you do with it then exit with die(); }

 ?> 
  <form action="name.php">
 <div> <input name='form_variable'> 
 <?php if ($errorFound) {echo $error_str} ?>
 </div> 
 <input type=submit name=submit>
 </form>

What happens is that if it's never submitted, it will go straight to html form and display but if you submitted and there is an error, it will cause php to display the form again with the echo'd error_st after the input tag.

netrox
+1  A: 

You can do all these stuff very easily with smarty like template engine. Its just exactly same as your question

{If $form eq submitted)}

{if $success} Add the account via class {else} Echo the error Show the form

Echo succcess {/if} {else} Show the form {/if}

Or if you just want to do it in php alone means just do the "netrox" method. Its good.

and these is another concept call heredoc in php. you can include your html in php in very easier way.

Ela