Jump to content

FrontendForms - A module for creating and validating forms on the frontend


Recommended Posts

Hello @ all

I want to share a new module with you, which makes the creation and validation of forms easy.  Take a look at the following example of a simple contact form:

// A very simple example of a contactform for demonstration purposes

$form = new Form('contactform');

$gender = new Select('gender');
$gender->setLabel('Gender');
$gender->addOption('Mister', '0');
$gender->addOption('Miss', '1');
$form->add($gender);

$surname = new InputText('surname');
$surname->setLabel('Surname');
$surname->setRule('required');
$form->add($surname);

$name = new InputText('name');
$name->setLabel('Name');
$name->setRule('required');
$form->add($name);

$email = new InputText('email');
$email->setLabel('E-Mail');
$email->setRule('required');
$form->add($email);

$subject = new InputText('subject');
$subject->setLabel('Subject');
$subject->setRule('required');
$form->add($subject);

$message = new Textarea('message');
$message->setLabel('Message');
$message->setRule('required');
$form->add($message);

$privacy = new InputCheckbox('privacy');
$privacy->setLabel('I accept the privacy policy');
$privacy->setRule('required')->setCustomMessage('You have to accept our privacy policy');
$form->add($privacy);

$button = new Button('submit');
$button->setAttribute('value', 'Send');
$form->add($button);

if($form->isValid()){

  print_r($form->getValues());
  // do what you want

}

// render the form
echo $form->render();

This piece of code creates a simple contact form and validates it according to the validation rules set. Inside the isValid() method you can run your code (fe sending an email)

Highlights:

  • 30+ validation types
  • Support for UiKit 3 and Bootstrap 5 CSS framework
  • SPAM protection
  • Highly customizable
  • Hookable methods for further customization
  • Multi-language

You can download and find really extensive information on how to use at https://github.com/juergenweb/FrontendForms.

Please report errors or suggestions directly in GitHub.

Best regards and happy testing 🙂

  • Like 21
Link to comment
Share on other sites

Thank you @OrganizedFellow

This module is on a very early stage, so it has to be tested carefully. I have done a lot of tests and it has been working well, but I hope a lot of people will try it out to test it further to find possible weak points and errors.

Link to comment
Share on other sites

  • 3 weeks later...

Hi 

I tried to install the module to processwire (latest version) and got a fatal error:

Aw shucks… Fatal Error: Uncaught Error: Using $this when not in object context in C:\xampp\htdocs\p20\site\modules\FrontendForms\FrontendForms.module:41

After changing line 41 in FrontendForms.module from:

Link to comment
Share on other sites

Hi Juergen,

I tried to install the module to processwire (latest version) and got a fatal error:

Aw shucks… Fatal Error: Uncaught Error: Using $this when not in object context in C:\xampp\htdocs\p20\site\modules\FrontendForms\FrontendForms.module:41

After changing line 41 in FrontendForms.module and remove the '$this' module installed in processwire. The line 41 changed to:
'summary' => 'Create forms and validate them using the Valitron library.',

Just writing this remark as maybe help some other users in module installation. I am going to test your module in the following days. 

Thanks for your work

  • Thanks 1
Link to comment
Share on other sites

Hello @sp1ke

thank you for your issue report. This error was produced by my editor during find and replace process. It is not possible to use $this inside the module info method. I have replaced all translateable strings from __('My string') to $this->_('My string') because using $this is the prefered method inside the class of a module. During these replacements I have overlooked the replacement inside the module info method.

I have replaced it on GitHub to:

'summary' => __('Create forms and validate them using the Valitron library.'),

So in this case the string is also translateable.

Thanks

  • Like 1
Link to comment
Share on other sites

Hi Juergen,

I made a template based on your example code for simple contact page. But I get an error message:

Aw shucks… Fatal Error: Uncaught TypeError: Argument 1 passed to Form::add() must be an instance of object, instance of Select given, called in C:\xampp\htdocs\p20\site\templates\contact.php on line 13 and defined in C:\xampp\htdocs\p20\site\modules\FrontendForms\Formelements\Form.php:203

I am attaching a screenshot of the error message and also part of the template file. Can you please help me on that?

Thanks in advance

frontendforms-er_message.jpg

frontendforms-template.jpg

Link to comment
Share on other sites

Hello

This is very strange, because I have no problems and the error message will also make no sense. I have installed it on a new install of PW without problems.

The problem is the type hinting in this case:  The method add() expects an object and the variable $gender in your case is an object - it is an object of the class Select. So there should not be a problem, but you can try the following:

// Replace this code in FrontendForms/FormeElements/Form.php line 203

public function add(object $field)

// with this code 

public function add($field)

But before removing the type hinting from this method, please try the following:

For testing purposes remove the add() method by the select field and take a look if the problem persists with other fields (fe. the name input field).

Which version of PHP do you use?

Please let me know!

 

Link to comment
Share on other sites

Hi Juergen,

I replaced the code in FrontendForms/FormeElements/Form.php line 203
public function add(object $field)
// with this code 
public function add($field)

as you suggested and the module is working fine now.

Versions information:
ProcessWire: 3.0.184
PHP: 7.1.18 (XAMPP server)

Thank you for your quick reply.

Have a nice day!

Link to comment
Share on other sites

Hello @sp1ke

glad to hear that, but I would recommend you to update your PHP version to at least 7.2+, because object type hinting is only possible with higher PHP versions. Otherwise you will get this error message everytime someone uses object type hinting (like me ;-).

Best regards

 

Link to comment
Share on other sites

Hello,

Thank you for your suggestion to update my PHP version. I will do it asap. I have another question: it's from the README.md file and about the sanitizer:

#### setSanitizer()

Method to add a sanitizer to the form field. Returns a sanitizer object. You can use all ProcessWire sanitizer methods by adding the sanitizer name inside the parenthesis of the setSanitizer() method. You can also set multiple sanitizer methods to one field if necessary.
Please note: For security reasons, the text sanitizer will be applied to each inputfield automatically, so you do not have to add it manually. The only exception is input textarea, where a textarea sanitizer will be applied by default.

What confused me is the 'Please note' paragraph. As I cannot understand the difference between inputfield and textarea: which one is automatically sanitized and why textarea is an exception. Do I have manually do the sanitization of the textarea input or not?

For the rest, your documentation is excellent. Very clear instructions how to use the module and also a lot of examples. Very helpful - great job!

Thanks in advance.

Link to comment
Share on other sites

Hello @sp1ke

3 hours ago, sp1ke said:

As I cannot understand the difference between inputfield and textarea

An inputfield is a single line input and textarea is a multiline input. ProcessWire provides an extra sanitizer for textareas. Take a look at https://processwire.com/api/ref/sanitizer/textarea/ .

Using "sanitizer text" for normal inputfields and "sanitizer textarea" for textareas was my personal choice. These 2 sanitizers will be applied by default - no need for you to do it manually. This is only for security reasons.

If you are not satisfied with it, you can disable the sanitizer on each field by using the removeSanitizers() method.

Take a look at this example:

$surname = new InputText('surname');
$surname->setLabel('Surname');
$surname->setRule('required');
$surename->removeSanitizers();// this line removes the text sanitizer from this inputfield
$form->add($surname);

In this case the value will not beeing sanitized, but this is not recommended (especially if you are storing values in the database).

If you want to add a special sanitizer for an input, you can use all sanitizers that will be shipped with ProcessWire. See a list of all available sanitizers at https://processwire.com/api/ref/sanitizer/

Example: You want to use the following sanitizers from ProcessWire:

$sanitizer->alpha(string $value) //Sanitize to ASCII alpha (a-z A-Z)
$sanitizer->camelCase(string $value) //Convert string to be all camelCase

All you need to do is to use the setSanitizer(name of the sanitizer in ProcessWire) method.

$surname = new InputText('surname');
$surname->setLabel('Surname');
$surname->setRule('required');
$surename->removeSanitizers();// this line removes the text sanitizer from this inputfield
$surename->setSanitizer('alpha'); // this adds the alpha sanitizer
$surename->setSanitizer('camelCase');// this adds the camelCase sanitizer
$form->add($surname);

Using camelCase sanitizer for the surename makes no sense in real life, so it is only applied as an example 😉

Hope it will be a little bit clearer.

  • Like 1
Link to comment
Share on other sites

Hi Juergen,

Thank you again for your very detailed and informative reply. It really made everything crystal clear. 

These days I am finishing a translation of language csv file in greek. Would you like to send it to you, so you can add it to the module language file? Do you believe it would be better if I send you a separate csv file only with the greek translation so you may just add the new column to your csv file?

Have a nice day!

  • Like 1
Link to comment
Share on other sites

Hello @sp1ke

That would be great and could really be a time saver for other Greek people. I would say you send me only the Greek csv file and I will add it on GitHub as el.csv (I guess el is the language code for Greek, am I right?).

Thanks and have a nice weekend

Link to comment
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
 Share

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By jploch
      Hey folks,
      Iam working on a module that extends InputfieldPageTable. I use PageTableExtended as a starting point and all went well so far, except I can't access my config values outside of the module file. The config values allways return the defaults, and not the values in the pw field settings. 

      Here is the code that sets the defaults inside my inputfield module file:
      public function init() { parent::init(); // defaults $this->set('gridMaxWidth', '1600'); $this->set('gridColumns', '12'); } Here is how I add the config field:
      public function ___getConfigInputfields() { $inputfields = parent::___getConfigInputfields(); $fieldsetGrid = $this->modules->get('InputfieldFieldset'); $fieldsetGrid->label = $this->_('Default Grid Settings'); $f = $this->wire('modules')->get('InputfieldText'); $f->attr('name', 'gridMaxWidth'); $f->attr('value', $this->gridMaxWidth); $f->label = $this->_('Container max width'); $f->description = $this->_('Grid container max width in px'); // page name format description $f->notes = $this->_('default is 1600'); // page name format notes $fieldsetGrid->append($f); $inputfields->append($fieldsetGrid); return $inputfields; } Accessing the values outside my module files like this (this gives me the default: 1600, even if I insert another value in the backend field settings):
      $default = $this->wire('modules')->get('InputfieldPageGrid'); $default->gridMaxWidth; Any Ideas?
    • 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 DV-JF
      Hi all...
      after looking into the I've recognized some errors caused by this module.
      Error: Exception: Login not attempted due to overflow. Please wait at least 5 seconds before attempting another login. (in /***/public_html/wire/modules/Session/SessionLoginThrottle/SessionLoginThrottle.module line 150) Error: Exception: Login not attempted due to overflow. Please wait at least 20 seconds before attempting another login. (in /***/public_html/wire/modules/Session/SessionLoginThrottle/SessionLoginThrottle.module line 150) Error: Exception: This request was aborted because it appears to be forged. (in /***/public_html/wire/core/SessionCSRF.php line 191) Is there a way to output these errors in a user friendly way, without throwing an "Internal Server Error" on the Frontpage (see attached video)?
      Many greets!

      IMG_3955.MOV
    • 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?
×
×
  • Create New...