This example describes the form builder usage that YII does not rely on model. Share to everyone for your reference. The implementation method is as follows:
The default Yii form builder only needs to do this:
Copy the code as follows: $form = new CForm (' Application.views.site.loginForm ', $model);
The application.views.site.loginForm here can also be a configuration array. However, if the $model parameter is not transmitted, it will be an error: Fatal Error:call to a member function Isattributesafe ()
For example, I'm going to generate a group form, but I don't want to rely on the model, so I can build a set of forms based on the configuration.
The label for the form that is generated by default is displayed according to $model->attributes, so I did 2 things:
1. Inherit the Cforminputelement overlay Renderlabel method, label the label as the element that you configured
2. Inherit the Cform overlay Renderelement method, $element instanceof ucforminputelement, and overwrite the Render method, elements and getbuttons loop output
Directly on the code:
app/protected/extensions/ucform.php
Copy CodeThe code is as follows: <?php
/**
* @author Ryan
*/
Class Ucform extends CForm
{
Public Function render ()
{
$output = $this->renderbegin ();
foreach ($this->getelements () as $element)
{
$output. = $element->render ();
}
foreach ($this->getbuttons () as $button)
{
$output. = $button->render ();
}
$output. = $this->renderend ();
return $output;
}
Public Function renderelement ($element)
{
if (is_string ($element))
{
if ($e = $this [$element]) = = = NULL && ($e = $this->getbuttons ()->itemat ($element)) = = = NULL)
return $element;
Else
$element = $e;
}
if ($element->getvisible ())
{
Ucforminputelement instead of Cforminputelement
if ($element instanceof ucforminputelement)
{
if ($element->type = = = ' hidden ')
Return "n". $element->render (). "N";
Else
Return "name}" >n ". $element->render (). "N";
}
else if ($element instanceof cformbuttonelement)
return $element->render (). "N";
Else
return $element->render ();
}
Return ';
}
}
Here's a simple invocation example:
Copy CodeThe code is as follows: <?php
/**
* @author Ryan
*/
Class Playersearchcontroller extends Controller
{
Public Function Actionindex ()
{
$config = Array (
' Class ' = ' DDD ',
' Action ' = ',
' Elements ' = array (
'
',
' Username ' = Array (
' Label ' = ' User name AH ',//note the label here
' Type ' = ' text ',
' MaxLength ' = 32,
' Value ' = '
),
'
',
' Password ' = array (
' Label ' = ' nickname ah ',//note the label here
' Type ' = ' password ',
' MaxLength ' = 32,
' Value ' = '
),
),
' Buttons ' = Array (
' Login ' = = Array (
' Type ' = ' Submit ',
' Label ' = ' Login ',
),
),
);
$model = new Cformmodel ();
$form = new Ucform ($config, $model);
$this->render (' Index ', compact (' form '));
}
}
It is hoped that this article is helpful to the PHP program design based on YII framework.