Zebra_Form::add PHP Method

add() public method

create a new form $form = new Zebra_Form('my_form'); add a text control to the form $obj = $form->add('text', 'my_text'); make the text field required $obj->set_rule( 'required' => array( 'error', // variable to add the error message to 'Field is required' // error message if value doesn't validate ) ); don't forget to always call this method before rendering the form if ($form->validate()) { put code here } output the form using an automatically generated template $form->render();
public add ( string $type ) : reference
$type string Type of the control to add. Controls that can be added to a form: - {@link Zebra_Form_Button buttons} - {@link Zebra_Form_Captcha CAPTCHAs} - {@link Zebra_Form_Checkbox checkboxes} - {@link Zebra_Form_Date date pickers} - {@link Zebra_Form_File file upload controls} - {@link Zebra_Form_Hidden hidden controls} - {@link Zebra_Form_Image image button controls} - {@link Zebra_Form_Label labels} - {@link Zebra_Form_Note notes} - {@link Zebra_Form_Password password controls} - {@link Zebra_Form_Radio radio buttons} - {@link Zebra_Form_Reset reset buttons} - {@link Zebra_Form_Select selects} - {@link Zebra_Form_Submit submit buttons} - {@link Zebra_Form_Text text box controls} - {@link Zebra_Form_Textarea textareas} - {@link Zebra_Form_Time time pickers} @param mixed $arguments A list of arguments as required by the control that is added. @return reference Returns a reference to the newly created object
return reference
    function &add($type)
    {
        // if shortcut for multiple radio buttons or checkboxes
        if ($type == 'radios' || $type == 'checkboxes') {
            // if there are less than 3 arguments
            if (func_num_args() < 3) {
                // trigger a warning
                _zebra_form_show_error('For <strong>' . $type . '</strong>, the <strong>add()</strong> method requires at least 3 arguments', E_USER_WARNING);
            } elseif (!is_array(func_get_arg(2))) {
                // trigger a warning
                _zebra_form_show_error('For <strong>' . $type . '</strong>, the <strong>add()</strong> method requires the 3rd argument to be an array', E_USER_WARNING);
            } else {
                // controls' name
                $name = func_get_arg(1);
                // the values and labels
                $values = func_get_arg(2);
                // a 4th argument (the default option) was passed to the method
                if (func_num_args() >= 4) {
                    // save the default value
                    $default = func_get_arg(3);
                    // if default value is not given as an array
                    // (makes sense for checkboxes when there may be multiple preselected values)
                    // make it an array
                    if (!is_array($default)) {
                        $default = array($default);
                    }
                }
                if (func_num_args() >= 5) {
                    $additional = func_get_arg(4);
                }
                $counter = 0;
                // iterate through values and their respective labels
                foreach ($values as $value => $caption) {
                    // sanitize controls' name (remove square brackets)
                    $sanitize_name = preg_replace('/\\[\\]$/', '', $name);
                    // santize the value
                    $value = preg_replace('/\\_{1,}/', '_', preg_replace('/[^a-z0-9\\_]/i', '_', $value));
                    // create control
                    $obj =& $this->add($type == 'radios' ? 'radio' : 'checkbox', $name, $value, isset($default) && in_array($value, $default) ? isset($additional) ? array_merge($additional, array('checked' => 'checked')) : array('checked' => 'checked') : (isset($additional) ? $additional : ''));
                    // if this is the first control in the array
                    // we will later need to return a reference to it
                    if ($counter++ == 0) {
                        $pointer =& $obj;
                    }
                    // add the label for the control
                    $this->add('label', 'label_' . $sanitize_name . '_' . $value, $sanitize_name . '_' . $value, $caption);
                }
                // if the array of values was not empty
                // return reference to the first control
                if (isset($pointer)) {
                    return $pointer;
                }
            }
            // for all other controls
        } else {
            $file_name = ucfirst(strtolower($type));
            // the classes have the "Zebra_Form_" prefix
            $class_name = 'Zebra_Form_' . ucfirst(strtolower($type));
            // include the file containing the PHP class, if not already included
            require_once dirname(__FILE__) . '/includes/' . $file_name . '.php';
            // if included file contains such a class
            if (class_exists($class_name)) {
                // prepare arguments passed to the add() method
                // notice that first argument is ignored as it refers to the type of the control to add
                // and we don't have to pass that to the class
                $arguments = array_slice(func_get_args(), 1);
                // if name was not specified trigger an error
                if (strlen(trim($arguments[0])) == 0) {
                    trigger_error('Name is required for control of type ' . $class_name, E_USER_ERROR);
                }
                // use this method to instantiate the object with dynamic arguments
                $obj = call_user_func_array(array(new ReflectionClass($class_name), 'newInstance'), $arguments);
                // make available the form's properties in the newly created object
                $obj->form_properties =& $this->form_properties;
                // get some attributes for the newly created control
                $attributes = $obj->get_attributes(array('id', 'name'));
                // perform some extra tasks for different types of controls
                switch ($class_name) {
                    // if the newly created control is a file upload control
                    case 'Zebra_Form_File':
                        // set a flag to be used at rendering
                        $this->form_properties['has_upload'] = true;
                        break;
                        // if the newly created control is a radio button or a checkbox
                    // if the newly created control is a radio button or a checkbox
                    case 'Zebra_Form_Radio':
                    case 'Zebra_Form_Checkbox':
                        // radio buttons and checkboxes might have a "master label", a label that is tied to the radio buttons' or
                        // checkboxes' name rather than individual controls' IDs. (as grouped radio buttons and checkboxes share
                        // the same name but have different values)
                        // we use this so that, if the controls have the "required" rule set, the asterisk is attached to the master
                        // label rather than to one of the actual controls
                        // therefore, we generate a "lookup" array of "master" labels for each group of radio buttons or
                        // checkboxes. this does not means that there will be an actual master label - we use this lookup
                        // array to easily determine if a master label exists when rendering the form
                        // sanitize the control's name
                        $attributes['name'] = preg_replace('/\\[\\]$/', '', $attributes['name']);
                        // if there isn't a master label for the group the current control is part of
                        if (!isset($this->master_labels[$attributes['name']])) {
                            // create the entry
                            // the "control" index will hold the actual label's name if a "master" label is added to the form
                            $this->master_labels[$attributes['name']] = array('control' => false);
                        }
                        break;
                }
                // put the reference to the newly created object in the 'controls' array
                $this->controls[$attributes['id']] =& $obj;
                // return the identifier to the newly created object
                return $obj;
            }
        }
    }

Usage Example

function page_add_bookmark()
{
    $form = new Zebra_Form('form');
    $form->clientside_validation(array('close_tips' => true, 'on_ready' => false, 'disable_upload_validation' => true, 'scroll_to_error' => false, 'tips_position' => 'right', 'validate_on_the_fly' => true, 'validate_all' => true));
    $form->add('label', 'label_url', 'url', 'URL');
    $url = $form->add('text', 'url', 'http://');
    $url->set_rule(array('required' => array('url_error', 'URL musí být vyplněno.'), 'url' => array(true, 'url_error', 'Pole musí obsahovat platné URL (včetně protokolu).')));
    $form->add('label', 'label_title', 'title', 'Název stránky');
    $title = $form->add('text', 'title', '');
    $title->set_rule(array('required' => array('title_error', 'Název musí být vyplněn.')));
    $form->add('submit', 'submitbtn', 'Přidat');
    if ($form->validate()) {
        $ok = model_add($_POST['url'], $_POST['title'], array());
        if ($ok) {
            flash('info', 'Záložka byla vytvořena');
        } else {
            flash('error', 'Záložku se nepodařilo vytvořit.');
        }
        redirect_to('/');
    }
    // set('form', $form->render('views/add_form.php', true));
    set('form', $form->render('', true));
    set('title', 'Nová záložka');
    return html('add.html.php');
}
All Usage Examples Of Zebra_Form::add