GithubHelp home page GithubHelp logo

formr / formr Goto Github PK

View Code? Open in Web Editor NEW
348.0 348.0 74.0 398 KB

Create and Validate PHP Forms in Seconds.

Home Page: https://formr.github.io

License: GNU General Public License v2.0

PHP 100.00%
bootstrap bulma form form-builder form-class form-library form-validation forms honeypot open-source php-form php-form-builder php-validation php-validator recaptcha validation

formr's Introduction

Formr

Latest Version on Packagist Total Downloads

Formr is a ridiculously fast and easy PHP form builder, with support for Bootstrap and Bulma right out of the box!

Find docs here: http://formr.github.io

If you find Formr useful, please consider starring the project and/or making a donation. Thank you!

Features

  • Create complex forms with server-side processing and validation in seconds
  • Built-in support for Bootstrap and Bulma
  • Built-in support for reCAPTCHA v3
  • Built-in POST validation rules, including validating email, regex, comparisons, slugging, and hashing
  • Instantly make one field required, all fields required, or all but one field required
  • Create and validate radio groups and checkbox arrays in seconds
  • Upload images: resize, rename, and create thumbnails
  • Extensible: easily create and save your own field element wrappers
  • Extensible: easily create and save your own dropdown menus
  • Extensible: easily create and save your own form & validation sets
  • Send plain text and HTML emails
  • Generate CSRF tokens and honeypots
  • Object-oriented; supports multiple forms per page
  • Little helpers to assist in building, layout, testing and debugging
  • And a ton of other cool stuff!

Installation

Composer

Run the following command to install Formr with Composer

composer require formr/formr

Then include the autoload.php file and create a new form object.

require_once 'vendor/autoload.php';
$form = new Formr\Formr();

Download

Download the .zip file and place the Formr folder in your project, then include the Formr class and create a new form object.

require_once 'Formr/class.formr.php';
$form = new Formr\Formr();

Bootstrap & Bulma Ready

Bootstrap and Bulma form classes are ready to go! Just tell Formr you want to use Bootstrap or Bulma when creating a new form and Formr will take care of the rest.

$form = new Formr\Formr('bootstrap');
$form = new Formr\Formr('bulma');

Basic Example

Simply enter your form labels as a comma delimited string and Formr will build the form, complete with opening and closing tags, a submit button, and email validation - plus all values retained upon POST. Easy!

$form = new Formr\Formr('bootstrap');
$form->create_form('Name, Email, Comments|textarea');

Produces the following HTML

<form action="/index.php" method="post" accept-charset="utf-8">

    <div id="_name" class="form-group">
        <label class="control-label" for="name">
            Name
        </label>
        <input type="text" name="name" id="name" class="form-control">
    </div>

    <div id="_email" class="form-group">
        <label class="control-label" for="email">
            Email
        </label>
        <input type="email" name="email" id="email" class="form-control">
    </div>

    <div id="_comments" class="form-group">
        <label class="control-label" for="comments">
            Comments
        </label>
        <textarea name="comments" id="comments" class="form-control"></textarea>
    </div>

    <div id="_button" class="form-group">
        <label class="sr-only" for="button"></label>
        <button type="submit" name="button" id="button" class="btn btn-primary">Submit</button>
    </div>

</form>

Basic Example with More Control

Using the create() method tells Formr you want control over adding the form tags and submit button yourself. Otherwise it's the same as the Basic Example above.

$form = new Formr\Formr('bootstrap');
$form->form_open();
$form->create('First name, Last name, Email address, Age|number, Comments|textarea');
$form->submit_button();
$form->form_close();

Produces the following HTML

<form action="/index.php" method="post" accept-charset="utf-8">
    <div id="_first_name" class="form-group">
        <label class="control-label" for="first_name">
            First name
        </label>
        <input type="text" name="first_name" id="first_name" class="form-control">
    </div>
    <div id="_last_name" class="form-group">
        <label class="control-label" for="last_name">
            Last name
        </label>
        <input type="text" name="last_name" id="last_name" class="form-control">
    </div>
    <div id="_email_address" class="form-group">
        <label class="control-label" for="email_address">
            Email address
        </label>
        <input type="email" name="email_address" id="email_address" class="form-control">
    </div>
    <div id="_age" class="form-group">
        <label class="control-label" for="age">
            Age
        </label>
        <input type="number" name="age" id="age" class="form-control">
    </div>
    <div id="_comments" class="form-group">
        <label class="control-label" for="comments">
            Comments
        </label>
        <textarea name="comments" id="comments" class="form-control"></textarea>
    </div>
    <div id="_submit" class="form-group">
        <label class="sr-only" for="submit"></label>
        <button type="submit" name="submit" id="submit" class="btn btn-primary">Submit</button>
    </div>
</form>

Pre-Built Forms

Formr has several common forms already baked in, and it's really easy to create and save your own.

$form = new Formr\Formr();
$form->fastform('contact');

Produces the following HTML

<form action="/index.php" method="post" accept-charset="utf-8">
    <fieldset>
        <label for="fname">
            First name:
        </label>
        <input type="text" name="fname" id="fname" class="input">

        <label for="lname">
            Last name:
        </label>
        <input type="text" name="lname" id="lname" class="input">

        <label for="email">
            Email:
        </label>
        <input type="email" name="email" id="email" class="input">

        <label for="comments">
            Comments:
        </label>
        <textarea name="comments" id="comments" class="input" ></textarea>

        <input type="submit" name="submit" value="Submit" id="submit">
    </fieldset>
</form>

Build Forms With Arrays

$data = [
    'text' => 'name, Name:',
    'email' => 'email, Email:',
    'checkbox' => 'agree, I Agree',
];

$form = new Formr\Formr('bootstrap');
$form->fastform($data);

Produces the following HTML

<form action="/index.php" method="post" accept-charset="utf-8">
    <fieldset>
        <div id="_name" class="form-group">
            <label class="control-label" for="name">
                Name:
            </label>
            <input type="text" name="name" class="form-control" id="name">
        </div>

        <div id="_email" class="form-group">
            <label class="control-label" for="email">
                Email:
            </label>
            <input type="email" name="email" class="form-control" id="email">
        </div>

        <div id="_agree" class="checkbox">
            <label for="agree">
                <input type="checkbox" name="agree" value="agree" id="agree"> I Agree
            </label>
        </div>

        <div id="_submit" class="form-group">
            <label class="sr-only" for="submit"></label>
            <input type="submit" name="submit" value="Submit" id="submit" class="btn">
        </div>
    </fieldset>
</form>

Build Forms in HTML

You have full control over how you build your forms...

<div class="my-wrapper-class">
    <?php $form->text('name', 'Name'); ?>
</div>

<div class="my-wrapper-class">
    <?php $form->email('email', 'Email address', '[email protected]', 'emailID', 'placeholder="[email protected]"'); ?>
</div>

<div class="my-wrapper-class">
    <input type="text" name="address" value="<?php $form->value('address') ?>">
</div>

Produces the following HTML

<div class="my-wrapper-class">
    <label for="name">
        Name
    </label>
    <input type="text" name="name" id="name">
</div>

<div class="my-wrapper-class">
    <label for="emailID">
        Email address
    </label>
    <input type="email" name="email" id="emailID" value="[email protected]" placeholder="[email protected]">
</div>

Retrieving POST Values

It's super easy to retrieve your $_POST values and assign them to variables!

$name = $form->post('name');
$email = $form->post('email');

Validation

Formr can easly process and validate your forms

Like the create() method, we can pass a list of our form labels to the validate() method, which will get the $_POST values of our form fields and put them into an array. If your field name is email, a valid_email validation rule will be applied automatically!

Basic usage

$form->validate('Name, Email, Comments');

Let's make sure the form was submitted, then we'll validate and get the value of our email field from the array.

if($form->submitted()) {
    $data = $form->validate('Name, Email, Comments');
    $email = $data['email'];
}

Adding Rules

Let's make sure Name is a minimum of 2 characters and a maximum of 30 by adding our validation rules wrapped in parentheses.

$form->validate('Name(min[2]|max[30]), Email, Comments');

Fine-Tune Your Validation

Of course you can get more in-depth with your validation, and even add custom error messaging! The following is a basic example, however Formr's validation methods are quite powerful and include, among other things, comparing values between fields and hashing using bcrypt()

Let's get the value of our email field using the post() method.

$email = $form->post('email');

Now let's make sure it's a valid email address by entering the valid_email validation rule in the third parameter. If there's an error, the text entered into the second parameter will notify the user to correct the Email field.

$email = $form->post('email','Email','valid_email');

We can take that a step further and enter a full custom error message in the second parameter to make our forms even more user-friendly.

$email = $form->post('email','Email|Please enter a valid email address','valid_email');

Full Example

<?php
// include the Formr class
require_once 'Formr/class.formr.php';

// create our form object and use Bootstrap 4 as our form wrapper
$form = new Formr\Formr('bootstrap');

// make all fields required
$form->required = '*';

// check if the form has been submitted
if($form->submitted())
{
    // make sure our Message field has at least 10 characters
    $form->validate('Message(min[10])');

    // let's email the form
    $to = '[email protected]';
    $from = '[email protected]';
    $subject = 'Contact Form Submission';

    // this processes our form, cleans the input, and sends it as an HTML email
    if($form->send_email($to, $subject, 'POST', $from, 'HTML'))
    {
        // email sent; print a thank you message
        $form->success_message('Thank you for filling out our form!');
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Formr</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <?php
            // print messages, formatted using Bootstrap alerts
            $form->messages();

            // create the form
            $form->create_form('First name, Last name, Email address, Message|textarea');
        ?>
    </div>
</body>
</html>

formr's People

Contributors

ameotoko avatar bvfbarten avatar gotylergo avatar joelrsimpson avatar mdmiko avatar timgavin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

formr's Issues

Errors don't displayed in inline mode

V1.1
I don't understand why in_array() return false; I changed by isset();
may be a problem with == != === ?

line 311 :

        //if (in_array($key, $this->errors)) {
        if (isset($this->errors[$key])) {
            return true;
        }

line 2362:

<div class='xxx'>IS EMPTY</a>; I add .$this->errors[$name].

        # add div if using inline errors
        if ($this->in_errors($name) && $this->inline_errors) {
//            return '<div class="' . $this->inline_errors_class . '"></div>';
            return '<div class="' . $this->inline_errors_class . '">'.$this->errors[$name].'</div>';
        }

inline errors are not displayed

When inline errors are turned on ($form->inline_errors = true;) and an input field is incorrect, the splash message displays but the field is not highlighted.

Upload_resize bug

turn on php error reporting

try this script here:
=> http://formr.github.io/upload-files/#a-complete-example

you will get Warning: imagejpeg(/www/formr/uploads/thumbnails//tn_20M3N2Qr1MRs0zmwkl7Yq4Q9hjZR818W.jpg): failed to open stream: No such file or directory in C:\wamp64\www\httpformr\class.formr.php on line 1368

see this double trailing slashes => '/www/formr/uploads/thumbnails//'?

Why there is double trailing slashes?

radio inline not working due to warning / message

hi,
i am trying to get radio buttons displayed inline, but unfortunately i get a warning message after each radio button called "Please enter a value for the radio: ". If this message is removed all radios are displayed inline.
How can I remove this warning or get it displayed at the end of the radio-group?

echo $form->input_radio_inline('meal','all'); echo $form->input_radio_inline('meal','vegetarian'); echo $form->input_radio_inline('meal','vegan'); echo $form->input_radio_inline('meal','fruits'); echo $form->input_radio_inline('meal','nothing');

regards,
andre

allow_html MUST come last

First Tim, let me tell you how happy I am to have found Formr. I just started using it for Wordpress and it works exactly they way I wanted! Great job, and the tutorial videos are perfect!

Now to a minor issue: I noticed that when using the rule 'allow_html', this rule must come last if there are several rules (such as also checking the max_length). If not the html tags will be stripped. You could either fix this or just spell it out in the documentation.

request: option for input label creation

Hello,

could you include an option to whether create a label for the form inputs?

For my needs i did the following:

in class Formr add class global variable

public $generate_labels = false;

then change the class constructor to

function __construct($wrapper = '', $generate_labels = false) {
$this->generate_labels = $generate_labels;
...
}

then in function label add this just before the closing bracket

    if ($this->generate_labels) {
        return $this->_create_label($data);
    }

Three issues

I still think there are issues. Please see the below code and the produced output:

$form = new Formr();
echo $form->form_open("","","?p=customer");
echo $form->input_checkbox("chkReverse", "Reverse-Charge", "1");
echo $form->input_text("txtVAT", "VAT Amount");
echo $form->form_close();

Producing this output:

<form action="?p=customer" method="post" accept-charset="utf-8">

<label for="1">
	<input type="checkbox" name="chkReverse" id="1" value="1"> Reverse-Charge
</label>

<label for="">VAT Amount</label> 
<input type="text" name="txtVAT" class="input" id="txtVAT">

</form>

Three problems here:

  1. The checkbox label is surrounding and the text label is on top. Inconsistent. Bad for CSS.
  2. The checkbox is not using the name as id. Instead, it uses the value. Bug?
  3. The text label does not set the for attribute to the used id. Bug?

Custom Errormessage on $form->post()

Seems custom error message (see below) is never displayed on

$form->post('email','Email|Please enter your email address','valid_email');

$form->error_message()


Thank you for that helpfull tool !

Please put this library on Packagist/Composer

I would like to use Formr for the Bootstrap 4 form generation, but it's 2019 and I'm not adding unversioned dependencies to my app. Would you accept a pull request to setup the library for Composer? You would need to create the account at Packagist.

Value parameter of input_submit not working

Hi Tim,
Thanks again for the excellent Formr!
I have a small problem with the value parameter for input_submit.

I have the following in my code:
$form->input_submit('submit', '', 'Enregister', 'submit_id', 'class="btn btn-success"');

I would expect to see 'Enregistrer' as the the value attribute (and displayed as the text inside the button), but this results in:

<input type="submit" name="submit" value="Submit" id="submit_id" class="btn btn btn-success">

So I can't change the submit button's text independently of the button name. Would be nice if you could fix it.

Cheers,
-- christer

Using medoo class inside my.dropdowns

Hello,

I'm trying to access my database inside my.dropdowns. For this I use Medoo class . I have an external config file like this:

require_once('Medoo.php');
use Medoo\Medoo;
$database = new Medoo([
	'database_type' => 'mysql',
	'database_name' => 'database',
	'server' => 'localhost',
	'username' => 'root',
	'password' => 'root',
	'charset' => 'utf8',
	'prefix' => 'db_'
]);

I tried something like this and it work but it's really messy (especially the fact I need to include the config file multiple times)... Do you have any idea how to do in a better way?

class MyDropdowns {
    public static function all_tags()
    {
        require('../lib/config.php');
        $content =  $database->select('content', ['id','title'],['ORDER'=>['title'=>'ASC']]);
        foreach($content as $t) {
            $return[$t['id']] = $t['title'];
        }
        return $return;
    }
}

Thanks

titib

Form submission alerts without Bootstrap

For my latest project I do not use Bootstrap, and I found that the alerts ("... saved") do not work. They show up, but can not be closed. Is there an easy javascript+CSS way to handle this without bootstrap?

Text Input 5th parameter for text string gets messy when included in error

If I have a string in the 5th parameter of text input, and I do something wrong in the form, it screws up the styling.

<div class="row">
<div class="col-md">

<?php
if($ip_wait_secs > 0) {
    $form_disabled='disabled';
} else {
    $form_disabled='autofocus';
}

// Commenting out my workaround here:
//if(($form->in_errors('desired_username'))&&(!$ip_wait_secs > 0)){
    $form_disabled='class="form-control is-invalid" autofocus';
}

echo $form->input_text('desired_username',$fs[0],'','',$form_disabled);

if($ip_wait_secs  > 0){
    $form_disabled='disabled';
} else {
    $form_disabled=null;
}
?>
</div>
<div class="col-md">

2020-04-27_9-45-46

2020-04-27_9-46-10

My workaround is to include the form-control and is-invalid classes if there is an invalid string input by the user.

Many thanks for an outstanding product and best wishes for continued success!

Undefined index: token

Whenever I try to submit my form I get the following error

Undefined index: token

#0 lib/formr/class.formr.php(283): Core\Error::errorHandler()
#1 App/Controllers/AuthController.php(121): Formr->submit()

Controller File

 $form = new \Formr('bootstrap');

if ($form->submit()) {
}

View File

{!! $form->form_open('', 'loginForm', Site::url('login'), 'post', 'class="form"') !!}

                {!! $form->csrf() !!}

                <div class="form-fields-split">
                    {!! $form->input_text('username', 'Username <span>*</span>') !!}
                    {!! $form->input_password('password', 'Password <span>*</span>') !!}
                </div>

                <button type="submit" class="g-recaptcha" data-sitekey="{{ env('RECAPTCHA_KEY') }}" data-callback='onSubmit'>Login</button>

                {!! $form->form_close() !!}

Can you specify type for input_button?

Just wondering if there is a way I can specify the type field for the function input_button. Right now it defaults to type="button", but I want to be able to specify the button as type="submit". Ending result:

<button type="submit" class="btn btn-primary btn-block">Apply Filters</button>

Otherwise I would have to use jquery onclick command to submit the form. I prefer a button instead of a normal submit button because I dont need to specify a value for a button and it works differently in bootstrap for me with regards to styling in bootstrap 4.

fields redisplayed incorrectly on submit with errors

If a form fails validation Formr automatically remembers and redisplays all the form fields.

It appears there is a bug as any field with a value of 0 (zero) on submission is redisplayed with no value (value is not defined on the input field), All other fields redisplay correctly.

compress image size of upload image

am using below code to upload image is there any way to compress image size `

    $form->upload_dir = 'uploads';
    $form->upload_rename = 'hash';
    $form->upload_accepted_mimes = 'image/jpg,image/jpeg,image/gif,image/png';
    if ($form->submit()) {
        $file = $form->post('file');
        $form->printr($file);
    }
    echo $form->messages();
    echo $form->form_open_multipart();
    echo $form->csrf(1800);
    echo $form->input_upload('file[]', 'Photo 1');
    echo $form->input_submit();
    echo $form->form_close();

`

Validation of input_tel phone number

in function _process_post($data)
I add this code :

        # valid tel
        if ($rule == 'tel')
        {
            $post=trim($post);
            $matches=null;
            if ($post!='' && !preg_match("#^[0-9\.\-\s]*$#us", $post, $matches))
            {
                var_dump($matches);
                if($this->_suppress_validation_errors($data)) {
                    $this->errors[$name] = $data['string'];
                } else {
                    $this->errors[$name] = $label . ' must be a valid phone number';
                }
            }
        }

**Please can you update the github with last corrections (for example : #32

i lost time with this knwon problem :)**

Install error with Composer

When I tried to install with Composer I've got the following error:

Could not find a version of package xlad/formr matching your minimum-stability (stable). Require it with an explicit version constraint allowing its desired stability.

any suggestion?

Composer versioning is not resolved yet.

Composer is still not able to install v1.1.2 it's stuck on 1.1

I've forked formr and tested this locally and got it to work by creating a new tag, v1.1.3, that includes the composer.json file currently on the master branch.

You could also remove the existing tags and then add them back with fixed composer.json files that have the version field omitted, but that seems like more trouble than it's worth. I would just make the new tag and be done with it. Hope this helps!

adding multiple hidden fields does not work

I tried following in fast_form
'hidden1' => [ 'name'=> 'email', 'id'=> 'email', 'value'=> 'test'], 'hidden2' => [ 'name'=> 'email2', 'id'=> 'email2', 'value'=> 'test2'],

request: more attributes

Hello,

I can see there are many "Form Validation Rules". 👍
I think it may be nice if some of them are also included as HTML attribute (if not in extra arguments string)

Formr HTML5
matches pattern
min_length
max_length maxlength
exact_length
greater_than max
less_than min
alpha pattern*
alpha_numeric  pattern*
alpha_dash pattern*
numeric pattern*
integer pattern*
decimal pattern*
valid_email pattern*
valid_ip pattern*

Regards.

The files are uploaded despite the mimes

Hi,
First of all, I want to say thanks for your wonderful work her.
I have a problem, types are not allowed of files ara uploaded despite the mimes,
I used $form->upload_accepted_mimes = 'images'; and getting the alert "Oops! The file was not uploaded because it is an unsupported mime type". But when I checked it entered the folder.

how can I prevent it by formr?

Thanks,
Golan

<?php  
require_once 'Formr/class.formr.php'

?>

<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
     <title>test</title>
     
</head>
<body>
       
<!-- Team -->
<section id="team" class="">
    
    
<div class="container">
        

<?php
// include the Formr class


// instantiate Formr
$form = new Formr();

// set our upload directory
$form->upload_dir = 'uploads';

// rename our upload with a 32-character hash
$form->upload_rename = 'hash';

// only allow images to be uploaded
$form->upload_accepted_mimes = 'images';

// resize the upload
$form->upload_resize = array(
	'thumbnail'	=> '100,100,tn_,/www/formr/uploads/thumbnails/,90'
);

// check if the form has been submitted
if($form->submit()) {
	
	// process the upload and put it into an array
	$file = $form->post('file');

    // printr() the array to see its keys/values
    $form->printr($file);
}

// always print Formr's messages!
echo $form->messages();

// open our form element
echo $form->form_open_multipart();

// add our file element
echo $form->input_upload('file');

// submit button
echo $form->input_submit();

//close the form
echo $form->form_close();

?>
</div>
  
</body>

</html>

input_checkbox() creates weird label

Hi,

if I create a new checkbox like this

// hint: input_checkbox($data, $label = '', $value = '', $id = '', $string = '', $inline = '', $selected = '')
echo $form->input_checkbox("chkReverse", "Reverse-Charge", "1", "chkReverse");`

the produced code looks like this:

<label for="1">
	<input type="checkbox" name="txtReverse" id="1" value="1"> Reverse-Charge
</label>

$data and $id are set to "chkReverse", but the $id is ignored. Also, the label surrounds the tag instead to become closed before.

All other inputs generate code like this (which is okay):

<label for="">VAT Amount</label> 
<input type="number" name="txtVAT" id="txtVAT" class="input" style="width: 60px;">

I expect the above example to produce code like this:

<label for="">Reverse-Charge</label> 
<input type="checkbox" name="txtReverse" id="txtReverse" value="1">

Option value selected & session problem

There a problem if selected item is in session values. There is no code for this case.

Besides, I had another problem, i don't use === because we need to be tolerant with keys.
All the data stored in $ _POST are of type string.
But if the keys used when calling input_select() are of type integer or if a user set a value in $_Session, you may have a problem.

example :

$test = array(
            "0"=>"-",
            "1"=>"xxx", );

$test = array(
            0=>"-",
            1=>"xxx", );

echo $this->input_select('interet', 'xxxxxx','','','','','', $test);

here my code :

# user has entered a value in the 'values' argument
                    if ($this->session_values && $this->session && !empty($_SESSION[$this->session][$data['name']]) && $_SESSION[$this->session][$data['name']] == $key) {
                        $return .= $this->_t(2) . '<option value="' . $key . '" selected="selected">' . $value . '</option>' . $this->_nl(1);
                    }
                    elseif (!isset($_POST[$data['name']]) && $data['value'] == $key) {
//                    if (!isset($_POST[$data['name']]) && $data['value'] === $key) {
                        $return .= $this->_t(2) . '<option value="' . $key . '" selected="selected">' . $value . '</option>' . $this->_nl(1);
                    } else {
                        $return .= $this->_t(2) . '<option value="' . $key . '">' . $value . '</option>' . $this->_nl(1);
                    }

Issue with add_to_errors and in_errors_if

I've come across an issue with add_to_errors and in_errors_if.

In my code, I'm doing my own validation process. When I find a field that hasn't validated properly, I use add_to_errors to put it in the errors array. After I add all the failed fields I have the system doing a var_dump on $form->errors() to make sure they are in there, and it correctly returns the list.

In my form, I'm using in_errors_if to print out a message if the field is in the errors array. However, in_errors_if never returns anything. For example I have the following:

$output .= $form->input_text('lname', "Last Name:");
$output .= $form->in_errors_if('lname', 'Please enter the student\'s last name');
$output .= $form->input_date('dob', "Date of Birth:");
$output .= $form->in_errors_if('dob', 'Please enter the student\'s date of birth');

But even when lname and dob are both added using add_to_errors, the in_errors_if never triggers.

I also tried using if ($form->in_errors('dob')) { blah } but that never returns true either.

Am I missing something or is this a bug?

Required indicator is not working with Bootstrap

Hello!

Require indicator is a useful features, but it only works when form instance is not created with Bootstrap. Once you set Bootstrap, everything looks fine, but there is no asterix after label names. I tried to fix it in wrappers.php, but no luck.
Could someone give some help?
Thank you.

validate method undefined?

I just added the following validation statement:

$form->validate('firstname, lastname, email, phone, appointment_date');

which resulted in the following error message in the browser:

Fatal error: Uncaught Error: Call to undefined method Formr::validate() in ...

$form is defined and refers to a submitted form, since I pick up post parameters without any problem.

I quickly scanned the Formr source code and didn't see any definition of validate function. Does it still exist?

Setting custom error message for validation

First, really loving this script! Makes it so much easier. Had one issue though, when doing validation I want to be able to supress any errors that may come up except the custom one I set. For example:

$form->post('lp','Password|Invalid Login/Password','sanitize_string|alpha_dash|min_length[6]');

I do not want to tip hackers to any requirements for the password field. No matter what, if there was any validation issues, I want it to show my custom error message of Invalid Login/Password. Now this works if it doesnt meant the requirements, except min_length. If it doesnt meant that, it gives an error message of:

Password must be at least 6 characters

If I pass it a custom error message, IMO the error above shouldnt show up, only the custom error message I am passing. Is there anyway you can change this or give me the option to suppress the errors from the validation rules and only show my custom error message?

Multi-select auto repopulate

Hello and thanks again for your great job.

I have a small issue with a real simple code. The auto-repopulation of a multi-select input seams to doesn't work and I need to make it by my own.

Could you have a look on this :

$default_tags = array();
$form = new Formr('bootstrap');

if($form->submit()) {
  $tags = $form->post('tag[]');
  echo "post : ";
  var_dump($tags);
  // The auto-repopulate doesn't work...
  // But if I add this : $default_tags = $tags; the auto repopulate seems to work.
}
else {
  echo "post : -";
  $default_tags = array(12,25);
}
echo "<br>default : ";
var_dump($default_tags);

echo $form->form_open('test','test','');
echo $form->input_select_multiple('tag[]', 'Tag','','tag','multiple="multiple"','',$default_tags,'all_tags'); // all tags = array(1=>"value1",2=>"value2",...)
// when I first load the page ID 12 and 25 are selected.
// if I change, let's say : ID 12 and 23 and I submits,
// the post is well received but there's no ID selected anymore.

echo $form->input_submit('submitSave', '', 'save', 'submitSave', 'class="btn btn-outline-primary"');
echo $form->form_close();

Thanks a lot,

titib

Checkbox displays label text twice

When I do this code (on PHP 7.3):

$output .= $form->input_checkbox('agree','I Agree','agree','agreeID');

I get this output:

<div id="_agreeID" class="checkbox">
	<label class="control-label" for="agreeID">I Agree
		<input type="checkbox" name="agree" id="agreeID" value="agree">I Agree
	</label>
</div>

As you can see it's adding the words "I Agree" twice. In the browser this just gives me the check box and "I Agree I Agree". Is there some way to stop the duplicate text from appearing?

'selected' is ignored if form is entered by post

Hi Tim,

if you enter a form by a post from another form, e.g. a login, the 'selected' values are completely ignored:

2563 # check the element on initial form load
2564            if (!$_POST) {

I think you should rather ask for the specific form element:

2564            if (!isset($_POST[$data['name']])) {

Nils

Options check

Hello,

I get key/text pairs from a remote database I don't own (so I cannot just change the keys...) with keys being integers.

Now, here's my issue, with the following 3 pairs:

// labels are changed, but the keys are the same
$pairs = arrayr(
    0 => "foo",
    1 => "bar",
    3 => "baz",
);
// then let's create a simple drop down menu with it
$form->input_select('pairs', '', '', "choose", $pairs);

...the result was strange as "foo" was automatically defaulted instead of "choose"

Later, I've been told they can be combined and change my code this way

foreach ($pairs as $v => $l) {
    $form->input_select('pairs[]', $l, $v, "pairs_$v");
}

Now I have that error/red message: "Please enter a value for the checkbox: pairs[]"

For me, it's a bug because zero is a value and it shouldn't behave as if an true empty string or undefined/unset variable is passed.

Composer does not install v1.1.2

Cannot install v1.1.2 with Composer only v1.1

I think the version number needs to be omitted in composer.json. Right now the version is set at 1.1 in composer.json.

Found this on Packagist.org:
The easiest way to manage versioning is to just omit the version field from the composer.json file. The version numbers will then be parsed from the tag and branch names.

It doesn't displays values when $value='0'. Same problem with $id, and $label

The following code, it won't display the value

$value = '0';
$form->input_text('foo', '', $value, 'foo');

The same happens to the other attributes like $label, $id.
Having a $label='0' is rare but $value='0' is common, and I also had problems $id='0' that gives an error that an id is required.

I checked the formr code, and the problem is due of checks:

  • if(empty($var))
  • if(!empty($var))
  • if($var)

unfortunately, in php empty('0') === true, making these forms of checking for empty useless in this case.
a simple solution, is to rename all:

  • empty( with empty_(
  • if\((!?)(\$\w+)\) with if($1empty_($2))

and write a empty_ function that handles the '0' case.
I did that myself, unfortunately, I can't disclose due copyrights issues.

How do i create bootstrap input group

i create input group with below group code in bootstrap is there any way to create input group in formr

<div class="input-group mb-3">
  <div class="input-group-prepend">
    <span class="input-group-text" id="basic-addon1">@</span>
 </div>
  <input type="text" class="form-control" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1">
</div>

Is this lib using some cache?

Hello!

I am using this lib and I find a potential bug. I print a form as the documentation expains, but send the data with ajax js. The server processes it and sends back the same form, now filled with the entered data and js overrides the sended form with the filled one got back. The problem, that if I do not refresh the page, but modify something with php between sending the data and saving to the db, the lib gives back the data entered and not the actual one in the db (and modified by php before saving). Everything is working,, db data is ok, the lib is called with exactly the same paramters except value, but no change. If I refresh the page, the right data is shown from the db.
If I echo an input manually with the same parameters (and value), everything is working, actual db content is shown regardless the typed ones.
The $form is opened and closed in the same script, so in theory, it should not exist after saving and a new object is created for reproducing the form with the database data.
Reprinted form is called exatly like the first print, not like this:
<input type="text" name="fname" value="<?php echo $form->value('fname'); ?>">

Auto re-populate issue with input_text

Hello, and thank you for you great job!
I have a problem with the method input_text() re-populate value action. I have a very simple form, with only one input and one submit, used for create and modify content.
Here is a small version of my script which produce the problem.
When you access it with ?u=1 (update), you can see the text to update... but when you submit, it still shown. Same with adding.
And the stranger things is after submitted, the value for input_text and input_submit does not follow the same rule... (see the placeholder and submit value).

I don't know if I'm clear but I hope the script is :-)

Thanks again.

titib

<?php
require_once('lib/config.php');

$update = $_GET['u'];
if($update == '1') {
  // get data from database...
  $tag_data = 'content to modify';
}

$form = new Formr('bootstrap');
if($form->submit()){
  $update = '0';
  if($form->post('submit') == 'Modifier') {
    // update in database
  }
  else {
    // add in Database
  }
}

if($update == '1') {
  $form_placeholder = 'Name to modify';
  $form_tag = $tag_data;
  $form_submit = 'Modify';
}
else {
  $form_placeholder = 'Name to add';
  $form_tag = '';
  $form_submit = 'Add';
  $update = '0';
}
echo 'update = '.$update;

echo $form->messages();
echo $form->form_open();
echo $form->input_text('tag','',$form_tag,'tag','placeholder="'.$form_placeholder.'" class="form-control"');
echo $form->input_submit('submit','',$form_submit,'submit','class="btn btn btn-outline-primary"');
echo $form->form_close();

inline checkbox not inline and values not saved when submit

Following your tutorial and have added the inline checkboxes, unfortunately they are not displayed inline and the label is repeated twice and when I submit any selected values are lost (everything else works).

echo $form->input_checkbox_inline('hobbies[]','Fishing','fishing','fishing'); echo $form->input_checkbox_inline('hobbies[]','Hiking','hiking','hiking'); echo $form->input_checkbox_inline('hobbies[]','Camping','camping','camping'); echo $form->input_checkbox_inline('hobbies[]','Swimming','swimming','swimming');

  <input type="checkbox" name="hobbies[]" id="fishing" value="fishing" class="form-check-input"> <label for="fishing">Fishing   Fishing   </label>   </div>       <div id="_hiking" class="form-check form-check-inline">   <input type="checkbox" name="hobbies[]" id="hiking" value="hiking" class="form-check-input"> <label for="hiking">Hiking   Hiking   </label>   </div>       <div id="_camping" class="form-check form-check-inline">   <input type="checkbox" name="hobbies[]" id="camping" value="camping" class="form-check-input"> <label for="camping">Camping   Camping   </label>   </div>       <div id="_swimming" class="form-check form-check-inline">   <input type="checkbox" name="hobbies[]" id="swimming" value="swimming" class="form-check-input"> <label for="swimming">Swimming   Swimming   </label>   </div>

radio inline has the same issue

If I change the array hobbies[] to say hobbie then the select is preserved on submit and the label only appears once, appears to be something to do with arrays?

The data is being posted and I can display it in the form with print_r

[hobbies] => Array ( [0] => hiking ) [submit] => Submit

To get rid of bold had to override with form-check-inline not checkbox-inline as per docs/tutorial

PHP 7.2.11

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.