Jump to content
onjegolders

Creating own form, getting started

Recommended Posts

Am trying to get my own simple contact form up and running and I would prefer to have a very simple one but understand the code that makes it work before trying to do anything complicated.

I've created a contact form with contact template and have made action="form.php" method="POST"

I've tried setting up a template for form but I keep getting the error that the template does not exist when I submit.

On my form.php I want to start really simply just to test that the $input method is working so I just have:

<?php
$name = $input->post->name;
echo $name;
?>

Would appreciate any guidance just to get me on my way.

Share this post


Link to post
Share on other sites

Hi onjegolders,

You can find several ideas here on how to process/create your own forms:

  • Like 1

Share this post


Link to post
Share on other sites

Thanks guys,

This is more for users creating their own forms though isn't it?

Or can it be used in templates as well?

Ideally I'd like to create my form markup, perhaps allowing them some editable fields which I can call myself within the form and then to use the API to process the form.

But if that's too complicated, I'm open to other ideas.

Share this post


Link to post
Share on other sites

Ryan as posted a sample contact form to use as a simple contact form here:

It can be useful for what you are trying to do.

Share this post


Link to post
Share on other sites

Can't seem to get this form sending, have slightly modified Ryan's code but not working, code is below. Any one have any ideas?

<?php

// set this to the email address you want to send to (or pull from a PW field)
$emailTo = 'me@me.com';
// or if not set, we'll just email the default superuser
if(empty($emailTo)) { $emailTo = $users->get($config->superUserPageID)->email; }
// set and sanitize our form field values
$form = array(
'name' => $sanitizer->text($input->post->name),
'email' => $sanitizer->email($input->post->email),
'phone' => $sanitizer->text($input->post->phone),
'subject' => $sanitizer->text($input->post->subject),
'level' => $sanitizer->text($input->post->level),
'hours' => $sanitizer->text($input->post->hours),
'message' => $sanitizer->textarea($input->post->message),
);
// initialize runtime vars
$sent = false;
$error = '';
// check if the form was submitted
if($input->post->submit) {
// determine if any fields were ommitted or didn't validate
foreach($form as $key => $value) {
 if(empty($value)) $error = "<h2 class='error'>Please check that you have completed all fields.</h2>";
}
// if no errors, email the form results
if(!$error) {
 $subject = "Contact Form";
 $message = '';
 foreach($form as $key => $value) $message .= "$key: $value\n";
 mail($emailTo, $subject, $message, "From: $form[email]");
 $sent = true;
}
}
if($sent) {
echo "<h2>Thank you, your message has been sent.</h2>"; // or pull from a PW field
} else {
echo "<h2>Sorry, that didn't work.</h2>";
}

Thanks

Share this post


Link to post
Share on other sites

Please, do always provide all the error messages and describe "how it doesn't work"?

Share this post


Link to post
Share on other sites

Please, do always provide all the error messages and describe "how it doesn't work"?

Sorry Apeisa you're absolutely right.

Upon submit, it just outputs the 'else' statement ("Sorry that didn't work")

Edit: so I'm guessing that means - no errors, but didn't get sent?

Edited by onjegolders

Share this post


Link to post
Share on other sites

It does contain errors. Just echo $error.

Also, can we see the form markup?

Share this post


Link to post
Share on other sites

At what point should can I echo $error? I echoed it in the final else statement but didn't see anything.

Here is whole contact page markup

<?php include("./header.inc"); ?>

<p class="italic_header">If you'd like to get in touch regarding tuition, please use the form below.</p>
<form action="" method="post" id="contact_form">

 <fieldset class="first">
  <h6>About yourself: </h6>

  <label for="name">Your name: </label>
  <input type="text" name="name" autofocus>

  <label for="email">Your email: </label>
  <input type="email" name="email">

  <label for="phone">Your phone number: </label>
  <input type="phone" name="phone">
 </fieldset>
 <fieldset>
  <h6 class="mt60">Your tuition: </h6>

  <label for="subject">Subject: </label>
  <select name="subject" id="subject" />
  <?php
  foreach ($page->subject_options as $subject) {
   echo "<option>$subject->subject_option</option>";
  }
 ?>
  </select>

  <label for="level">Level: </label>
  <select name="level" id="level" />
  <?php
  foreach ($page->level_options as $level) {
   echo "<option>$level->level_option</option>";
  }
 ?>
  </select>

  <label for="hours">Hours per week: </label>
  <input type="number" min="1" max="40" value="2" name="hours">
 </fieldset>
 <div class="clear"></div><!-- /.clear -->

  <fieldset class="full">
<label for="message">Additional information: </label>
<textarea name="message" cols="30" rows="10"></textarea>
<input type="submit" value="submit" id="submit">
  </fieldset>
</form>
<div id="contact_side">

 <h6>Or you can find me, here: </h6>
 <ul>
  <li>Skype: <?php echo $page->skype_name; ?></li>
  <li><a href="<?php echo $page->fb_url; ?>" target="_blank">Facebook</a></li>
  <?php if ($page->twitter_url) {
echo "<li><a href='$page->twitter_url' target='_blank'>Twitter</a></li>";
  } ?>
 </ul>

<?php

// set this to the email address you want to send to (or pull from a PW field)
$emailTo = 'me@me.com';
// or if not set, we'll just email the default superuser
if(empty($emailTo)) { $emailTo = $users->get($config->superUserPageID)->email; }
// set and sanitize our form field values
$form = array(
'name' => $input->post->name,
'email' => $input->post->email,
'phone' => $input->post->phone,
'subject' => $input->post->subject,
'level' => $input->post->level,
'hours' => $input->post->hours,
'message' => $input->post->message,
);
// initialize runtime vars
$sent = false;
$error = '';
// check if the form was submitted
if($input->post->submit) {
// determine if any fields were ommitted or didn't validate
foreach($form as $key => $value) {
 if(empty($value)) $error = "<h2 class='error'>Please check that you have completed all fields.</h2>";
}
// if no errors, email the form results
if(!$error) {
 $subject = "Contact Form";
 $message = '';
 foreach($form as $key => $value) $message .= "$key: $value\n";
 mail($emailTo, $subject, $message, "From: $form[email]");
 $sent = true;
}
}
if($sent) {
echo "<h2>Thank you, your message has been sent.</h2>"; // or pull from a PW field
} else {
echo "<h2>Sorry, that didn't work.</h2>";

}
?>

</div> <!-- end contact side -->
<?php include("./footer.inc"); ?>

Thanks for the help.

Share this post


Link to post
Share on other sites

sorry, I removed $sanitizer from this just to check in case that was what was failing.

I've been looking at this code for hours and still no clue as to what's wrong!

Think I may have to fall back to a simple PHP form I've used before otherwise, except it has no validation or sanitizer :(

Share this post


Link to post
Share on other sites

The problem seems that you're checking for $input->post->submit, yet the submit button has no name="submit", so it never enters the code in the if.

I restructured a little your code. There's still a lot to improve, but you get the idea:


<?php

include("./head.inc");

$success_message = "<h2>Thank you, your message has been sent.</h2>"; 
$success = false; // we assume it and set to true if mail sent
$error = false;

// set and sanitize our form field values

$form = array(
 'name' => $input->post->name,
 'email' => $input->post->email,
 'phone' => $input->post->phone,
 'subject' => $input->post->subject,
 'level' => $input->post->level,
 'hours' => $input->post->hours,
 'message' => $input->post->message
);

print_r($form);

// check if the form was submitted
if($input->post->submit) {

 // determine if any fields were ommitted or didn't validate
 foreach($form as $key => $value) {
   if( strlen(trim($value)) == 0 ) {
     $error_message = "<h2 class='error'>Please check that you have completed all fields.</h2>";
     $error = true;
     break;
   }
 }
 // if no errors, email the form results
 if(!$error) {
   $emailTo = 'me@me.com';
   if(empty($emailTo)) $emailTo = $users->get($config->superUserPageID)->email;
   $subject = "Contact Form";
   $message = '';
   foreach($form as $key => $value) $message .= "$key: $value\n";

   if(mail($emailTo, $subject, $message, "From: $form[email]")){
     $success = true;
   }
 }
}
?>

<?php if(!$success) : // : alternative version instead of {} ?>

 <?php 
 if($error) {
   echo $error_message; // or pull from a PW field
 } 
 ?>

 <p class="italic_header">If you'd like to get in touch regarding tuition, please use the form below.</p>
 <form action="./" method="post" id="contact_form">

   <fieldset class="first">
    <h6>About yourself: </h6>

    <label for="name">Your name: </label>
    <input type="text" name="name" autofocus>

    <label for="email">Your email: </label>
    <input type="email" name="email">

    <label for="phone">Your phone number: </label>
    <input type="phone" name="phone">
   </fieldset>
   <fieldset>
    <h6 class="mt60">Your tuition: </h6>

           <label for="subject">Subject: </label>
           <select name="subject" id="subject" />
           <?php
           foreach ($page->subject_options as $subject) {
            echo "<option>$subject->subject_option</option>";
           }
          ?>
           </select>

           <label for="level">Level: </label>
           <select name="level" id="level" />
           <?php
           foreach ($page->level_options as $level) {
            echo "<option>$level->level_option</option>";
           }
          ?>
           </select>

           <label for="hours">Hours per week: </label>
           <input type="number" min="1" max="40" value="2" name="hours">
   </fieldset>
   <div class="clear"></div><!-- /.clear -->

    <fieldset class="full">
         <label for="message">Additional information: </label>
         <textarea name="message" cols="30" rows="10"></textarea>
         <input type="submit" name="submit" value="submit" id="submit">
    </fieldset>
 </form>
 <div id="contact_side">

<?php else: // if success ?>

 <?php echo $success_message; ?>

<?php endif; // end if success ?>

 <h6>Or you can find me, here: </h6>
 <ul>
  <li>Skype: <?php echo $page->skype_name; ?></li>
  <li><a href="<?php echo $page->fb_url; ?>" target="_blank">Facebook</a></li>
  <?php if ($page->twitter_url) {
       echo "<li><a href='$page->twitter_url' target='_blank'>Twitter</a></li>";
  } ?>
 </ul>

</div> <!-- end contact side -->

<?php include("./foot.inc");
  • Like 1

Share this post


Link to post
Share on other sites

Wow Soma, I can only thank you for putting so much time in to help me out. I've tested your code "as is" and the email gets sent perfectly.

I am a bit confused however about the structure. What exactly is happening before the form HTML gets called through?

Can i remove the print_r?

Also you mention alternative version at one point, is this duplicate code, should I be using one part or another?

Sorry for the questions and thanks again for taking the time to write.

Share this post


Link to post
Share on other sites

You're welcome, it's just a matter of debugging it right. You'll get more experienced the more you try to.

The print_r will just output the array in a readable format. It's a method to bebug, see it somethings there. You can remove it.

The alternative : is for if and foreach's in php you can do this to wrap instead of the curly brackets {}. It's easier if you're mixing html and php and instead of the closing } you write "endif;" or "endforeach;" - If you want an else in a if condition you write "else:".

<?php foreach($a as $B) : ?>
  <p><?php echo $b</p>
<?php endforeach; ?>

<?php if($a == $B) : ?>
  <p><?php echo $b</p>
<?php else: ?>
  <p>not same</p>
<?php endif; ?>

I moved the main php logic of the form to the top. This because I like it to have this way from top to bottom logic. I'm not saying you abolutely should do it that way, but for me it looks littler cleaner. There's also different approaches. (I'm sure diogo will post something else ;) )

This way I have set a $success var to be false and wrap the form into the if(!$success): and also print any errors before the form. And then in the else: of the if(!$success) is true have the success message printed and the form will not be shown.

Share this post


Link to post
Share on other sites

Thanks for your answers and for helping me to understand.

It's quite confusing at my level to know where to put the form and where the logic, I suppose the success or failure message would always have to come before or after the actual form.

I will take a closer look in the morning but I'm really grateful for the time you took to show me around :)

Share this post


Link to post
Share on other sites

Would it be possible to take that code and only make some of the fileds "required"? As it is the user has to enter every field for the form to process.

Share this post


Link to post
Share on other sites

Why not just delete the fields you don't require? Makes things simpler.

  • Like 1

Share this post


Link to post
Share on other sites

Would it be possible to take that code and only make some of the fileds "required"? As it is the user has to enter every field for the form to process.

Yes. http://bit.ly/IkP4qF

Share this post


Link to post
Share on other sites

Thanks Soma for that link :)

I understand it's possible in PHP, I was just looking for help within the context of this code.

Thanks anyway

Why not just delete the fields you don't require? Makes things simpler.

Not sure I understand.

Some fields users may choose to fill in to provide further information but are optional.

If I delete them, the values won't get sent with the form.

Share this post


Link to post
Share on other sites

It's OK, I've figured it out thanks.

I added a $required_fields array and looped that instead of $form.

Share this post


Link to post
Share on other sites

Sorry for the harsh answer ;)

You might not be clear with that this form example IS php. There's no PW related in here, apart from the $input->post. But that's just equal to $_POST.

How about doing a simple array with the field names required, and use that in the foreach check over those. You'll find plenty examples..

Share this post


Link to post
Share on other sites

Sorry for the harsh answer ;)

You might not be clear with that this form example IS php. There's no PW related in here, apart from the $input->post. But that's just equal to $_POST.

How about doing a simple array with the field names required, and use that in the foreach check over those. You'll find plenty examples..

No problems Soma, you're right, I did find the answer with a bit of searching, the solution was exactly the one you suggested.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By benbyf
      Hi, Looking to create form elements on a page–some input with a colection of form inputs and the appropriate labels and variables for that input. I've used ProForms in the past and rolled out my own when creating simply one off forms, but I wonder if anyone has found a good way of allowing form creation on page editing so that clients can adhocly make and edit forms?
      Thanks
    • By jds43
      Hello,
      I have a search page loosely based on Skyscrapers where I'm parsing a selector with options 'beds', 'bathrooms', 'size' fields. It is working well until I select 'Any' after I've run a search. This is where no results are returned (/?beds=&bathrooms=&size=&submit=). I want it to reset and show all results.
      I hope this isn't too vague.
       
    • By Mithlesh
      Changing it to null
    • By Tyssen
      I have a page that contains a single ProFields table field and I want to display the contents of the table on the front end and then for logged in users, they can edit certain columns in the table.
      What I have at the moment is
      $out = '<form action="'.$page->url.'" method="post" > <table class="table"> <tbody>'; $count = 1; foreach($page->fieldName as $row) : $out .= ' <tr> <td><input type="checkbox" name="fieldName_'.$count.'_columnName"></td> </tr>'; if($input->post->submit) : $page->of(false); $page->set('fieldName_'.$count.'_columnName', $sanitizer->text($input->post->{fieldName_'.$count.'_columnName})); $page->save(); endif; $count++; endforeach; $out .= ' </tbody> </table> <button class="button" type="submit">Save</button> </form>'; The two problems I have are:
      I get an error trying from $sanitizer->text($input->post->{fieldName_'.$count.'_columnName}), not sure how to make that dynamic.  If I change the above to just a static value, e.g. $page->set('fieldName_1_columnName', 'Testing') and save the form, it's not saving the values to the database. Where am I going wrong?
    • By VeiJari
      Hello forum. I'm trying to figure out how to detect if current form has errors after saving it in pw admin page. This is so that our event location isn't added in database if we detect errors. But I can't seem to find a correct way to detect errors? I only found the wire()->errors() and it always triggers even if I don't have any errors. 
      How can I detect errors in a form?
      By error I mean $page->error('this is the red error');
×
×
  • Create New...