2011-04-08 2 views
1

в ваших рамках есть ли автоматизация для создания форм?Как вы пишете формы?

Для примера скажем, у вас есть этот массив полей:

$fields = array('name'=>array('type'=>'input',otherparams) 
       'desc'=>array('type'=>'textarea',otherparams) 
       ); 

на основе полей, которые вы должны сделать HTML как это:

<form> 
    Name: <input name="name" type="text"> 
    Description: <textarea name="desc"></textarea> 

//>Submit 
</form> 

ли вы построить свой HTML с помощью руки или есть какая-то автоматизация?

Thanks

+0

Какие рамки вы используете, если таковые имеются? –

+0

@angry: мой пользовательский фреймворк –

ответ

0

Я работаю с каркасом Yii. Php автоматически генерирует html. Вы пишете html вручную, но это для просмотров. В представлениях также есть динамические переменные php, которые меняются. Фактически полный html-документ объединяется, вызывая контроллер с веб-адресом, этот контроллер решает, какие модели, если он требуется, применить к форме и какому представлению включить модель. Затем он генерирует html.

SiteController.php

<?php 

class SiteController extends Controller 
{ 
    /** 
    * Declares class-based actions. 
    */ 
    public function actions() 
    { 
     return array(
      // captcha action renders the CAPTCHA image displayed on the contact page 
      'captcha'=>array(
       'class'=>'CCaptchaAction', 
       'backColor'=>0xFFFFFF, 
      ), 
      // page action renders "static" pages stored under 'protected/views/site/pages' 
      // They can be accessed via: index.php?r=site/page&view=FileName 
      'page'=>array(
       'class'=>'CViewAction', 
      ), 
     ); 
    } 

    /** 
    * This is the default 'index' action that is invoked 
    * when an action is not explicitly requested by users. 
    */ 
    public function actionIndex() 
    { 
     // renders the view file 'protected/views/site/index.php' 
     // using the default layout 'protected/views/layouts/main.php' 
     $this->render('index'); 
    } 

    /** 
    * This is the action to handle external exceptions. 
    */ 
    public function actionError() 
    { 
     if($error=Yii::app()->errorHandler->error) 
     { 
      if(Yii::app()->request->isAjaxRequest) 
       echo $error['message']; 
      else 
       $this->render('error', $error); 
     } 
    } 

    /** 
    * Displays the contact page 
    */ 
    public function actionContact() 
    { 
     $model=new ContactForm; 
     if(isset($_POST['ContactForm'])) 
     { 
      $model->attributes=$_POST['ContactForm']; 
      if($model->validate()) 
      { 
       $headers="From: {$model->email}\r\nReply-To: {$model->email}"; 
       mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers); 
       Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.'); 
       $this->refresh(); 
      } 
     } 
     $this->render('contact',array('model'=>$model)); 
    } 

    /** 
    * Displays the login page 
    */ 
    public function actionLogin() 
    { 
     $model=new LoginForm; 

     // if it is ajax validation request 
     if(isset($_POST['ajax']) && $_POST['ajax']==='login-form') 
     { 
      echo CActiveForm::validate($model); 
      Yii::app()->end(); 
     } 

     // collect user input data 
     if(isset($_POST['LoginForm'])) 
     { 
      $model->attributes=$_POST['LoginForm']; 
      // validate user input and redirect to the previous page if valid 
      if($model->validate() && $model->login()) 
       $this->redirect(Yii::app()->user->returnUrl); 
     } 
     // display the login form 
     $this->render('login',array('model'=>$model)); 
    } 

    /** 
    * Logs out the current user and redirect to homepage. 
    */ 
    public function actionLogout() 
    { 
     Yii::app()->user->logout(); 
     $this->redirect(Yii::app()->homeUrl); 
    } 
} 

ContactForm.php = Это модель.

<?php 

/** 
* ContactForm class. 
* ContactForm is the data structure for keeping 
* contact form data. It is used by the 'contact' action of 'SiteController'. 
*/ 
class ContactForm extends CFormModel 
{ 
    public $name; 
    public $email; 
    public $subject; 
    public $body; 
    public $verifyCode; 

    /** 
    * Declares the validation rules. 
    */ 
    public function rules() 
    { 
     return array(
      // name, email, subject and body are required 
      array('name, email, subject, body', 'required'), 
      // email has to be a valid email address 
      array('email', 'email'), 
      // verifyCode needs to be entered correctly 
      array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()), 
     ); 
    } 

    /** 
    * Declares customized attribute labels. 
    * If not declared here, an attribute would have a label that is 
    * the same as its name with the first letter in upper case. 
    */ 
    public function attributeLabels() 
    { 
     return array(
      'verifyCode'=>'Verification Code', 
     ); 
    } 
} 

Это мнение: contact.php

<?php 
$this->pageTitle=Yii::app()->name . ' - Contact Us'; 
$this->breadcrumbs=array(
    'Contact', 
); 
?> 

<h1>Contact Us</h1> 

<?php if(Yii::app()->user->hasFlash('contact')): ?> 

<div class="flash-success"> 
    <?php echo Yii::app()->user->getFlash('contact'); ?> 
</div> 

<?php else: ?> 

<p> 
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you. 
</p> 

<div class="form"> 

<?php $form=$this->beginWidget('CActiveForm'); ?> 

    <p class="note">Fields with <span class="required">*</span> are required.</p> 

    <?php echo $form->errorSummary($model); ?> 

    <div class="row"> 
     <?php echo $form->labelEx($model,'name'); ?> 
     <?php echo $form->textField($model,'name'); ?> 
    </div> 

    <div class="row"> 
     <?php echo $form->labelEx($model,'email'); ?> 
     <?php echo $form->textField($model,'email'); ?> 
    </div> 

    <div class="row"> 
     <?php echo $form->labelEx($model,'subject'); ?> 
     <?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?> 
    </div> 

    <div class="row"> 
     <?php echo $form->labelEx($model,'body'); ?> 
     <?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?> 
    </div> 

    <?php if(CCaptcha::checkRequirements()): ?> 
    <div class="row"> 
     <?php echo $form->labelEx($model,'verifyCode'); ?> 
     <div> 
     <?php $this->widget('CCaptcha'); ?> 
     <?php echo $form->textField($model,'verifyCode'); ?> 
     </div> 
     <div class="hint">Please enter the letters as they are shown in the image above. 
     <br/>Letters are not case-sensitive.</div> 
    </div> 
    <?php endif; ?> 

    <div class="row buttons"> 
     <?php echo CHtml::submitButton('Submit'); ?> 
    </div> 

<?php $this->endWidget(); ?> 

</div><!-- form --> 

<?php endif; ?> 

Переход на страницу: http://yoursite/index.php/contact/ активирует метод actionContact в SiteController. Это захватывает размещенную контактную информацию, помещает ее в модель, а затем отображает представление.

+0

пример? ....... – dynamic

+0

Пример теперь предоставлен. –

+0

В основном вы написали форму на обратной странице: D – dynamic

0

CodeIgniter позволяет создавать формы с использованием Form Helper, хотя я предпочитаю писать сам HTML.

0

попробовать это (не тестировал)

<?php 
$fields = array('name'=>array('type'=>'input',name='fname') 
       'desciprtion'=>array('type'=>'textarea',name='desc') 
       ); 
?> 
<form name="myform" action="" method="post"> 
<?php 

foreach($fields as $key=>$value) 
{ 
    echo "<label>$key</label>"; 
    echo " <$key['type'] name=\"$key['name']\" id=\"$key['id']>\"> 
} 
?> 
+0

Я знаю, что смогу это сделать, Но я бы не стал забирать колесо, я прошу какое-то готовое решение ... – dynamic

Смежные вопросы