tammyhart / Reusable-Custom-WordPress-Meta-Boxes

177 stars 97 forks source link

Practices for required fields? (not an issue) #44

Open cibulka opened 11 years ago

cibulka commented 11 years ago

Hello, thanks for a wonderful library!

I am trying to find the best approach to field validation - checking if the input is correct (dates for non-js users, email, ...) AND required fields.

I know, that the original creator doesn't support the library anymore, so it's more of a question for the community. Can you guide me somewhere? I would be glad to share my knowledge if I encounter something useful myself.

Thank you!

cibulka commented 11 years ago

OK, let me answer my own question. :) This is my current approach:

1) inc/sample.php (or your custom file): Add custom paramater req in fields array to fields that you wish to be required and set it to true. Such as:

array( // Text Input
    'label' => 'Text Input', // 

2) meta_box.php: Get the data and set new variable (basically repeat pattern from lines 20 to 28).

$req = isset($field['req']) ? $field['req'] : null;

3) meta_box.php: Run another case/switch statement and do whatever you want to do with the results.

switch($req) {
    case 'true':
        echo' This is required.';
    break;
}

4) meta_box.php /optional/: I like to add "req" and "unreq" class to table rows to be able to do some fancy jQuery validation magic.

function meta_box_callback() {
        // Nonce
    // Begin the field table and loop
    echo '<table class="form-table meta_box">';
    foreach ( $this->fields as $field) {
        if (isset($field['req'])) { $req = 'req'; } else { $req = 'unreq'; } // required check (cibulka)

        if ( $field['type'] == 'section' ) {
            // req class (cibulka)
            echo '<tr class="'.$req.'">[...]</tr >';
        } else {
            // req class (cibulka)
            echo '<tr class="'.$req.'">[...]</tr>';
        }
    } // end foreach
    echo '</table>'; // end table
}

Does it make sense?

SIDENOTE (for PHP beginners like me): I like to add comments to code, that clearly state what are my edits of default library. You can cmd+F you edits easily, which is essential for debugging (you never know what you can mess up) and updating.