📄 Form.classes.php

Size: 2,731 bytes
Path: /home/islandholiday/public_html/admin/panel/OLD/Form.classes.php
Modified: 2020-09-29 10:43:32
<?php
class Form
{
    protected $sAction;

    protected $sMethod;

    protected $aTags = array();

    public function __construct($sAction, $sMethod = 'post')
    {
        $this->sAction = $sAction;
        $this->sMethod = $sMethod;
    }

    public function addTag(Tag $oTag)
    {
        $this->aTags[] = $oTag;
    }

    public function render()
    {
        foreach ($this->aTags as $oTag)
        {
            $sTags .= $oTag->render() . "\\r\
";
        }
        return sprintf(
            '<form action="%s" method="%s">
                %s
            </form>',
            $this->sAction,
            $this->sMethod,
            $sTags
        );
    }
}

class Tag
{
    protected $sTag;

    protected $sDisplayText;

    protected $aAttributes;

    public function __construct($sTag, $sDisplayText = '')
    {
        $this->sTag = $sTag;
        $this->sDisplayText = $sDisplayText;
    }

    public function addAttribute($sName, $mValue)
    {
        $this->aAttributes[$sName] = $mValue;
    }

    public function render()
    {
        if (is_array($this->aAttributes))
        {
            foreach ($this->aAttributes as $sName => $mValue)
            {
                $sAttributes .= sprintf('%s="%s" ', $sName, $mValue);
            }
        }
        if ($this->sDisplayText == '')
        {
            return sprintf(
                '<%s %s/>',
                $this->sTag,
                $sAttributes
            );
        } else {
            return sprintf(
                '<%s %s>%s</%s>',
                $this->sTag,
                $sAttributes,
                $this->sDisplayText,
                $this->sTag
            );
        }
    }
}


$oForm = new Form('/users/login/');

$oUsernameField = new Tag('input');
$oUsernameField->addAttribute('type', 'text');
$oUsernameField->addAttribute('name', 'username');

$oBr = new Tag('br');

$oPasswordField = new Tag('input');
$oPasswordField->addAttribute('type', 'password');
$oPasswordField->addAttribute('name', 'password');

$oSubmitButton = new Tag('button', 'Click Me!');
$oSubmitButton->addAttribute('type', 'submit');
$oSubmitButton->addAttribute('name', 'submit');
$oSubmitButton->addAttribute('value', 'login');

$oForm->addTag($oUsernameField);
$oForm->addTag($oBr);
$oForm->addTag($oPasswordField);
$oForm->addTag($oBr);
$oForm->addTag($oSubmitButton);

echo $oForm->render();
/*
<form action="/users/login/" method="post">
    <input type="text" name="username" />
    <input type="password" name="password" />
    <button type="submit" name="submit" value="login" >Click Me!</button>
</form>
*/
?>