LoginSignup
8
9

More than 5 years have passed since last update.

FuelPHPでフォームの必須項目に※をつける

Last updated at Posted at 2015-02-02

バリデーションルールはModelで定義しているのに必須項目はViewに直接※をつけているなんていうときにはもっと自動的にやっちゃおうよっていう感じのやつ

Validationクラスを拡張

fuel/app/classes/validation.php
<?php

class Validation extends \Fuel\Core\Validation {

    /**
     * If $field has 'required' rule, It will return true
     */
    public function is_required( $field ) {
        $fields = $this->fieldset()->field();
        if( isset($fields[$field]) ){
            foreach( $fields[$field]->rules as $r ){
                if( $r[0] == 'required' ){
                    return true;
                }
            }
        }
        return false;
    }
}
fuel/app/bootstrap.php
Autoloader::add_classes(array(
    'Validation' => APPPATH.'classes/validation.php',
));

ControllerからValidationを渡す

public function action_create(){
...
    $val = Model_Item::validation('create')
    if( $val->run() ){
    }
    $this->template->content = View::forge('item/create',array('val'=>$val));
...

Viewでフィールド毎にclassを出力

        <div class="form-group<?php echo ($errors && $val->error('title'))?" has-error":""; ?><?php echo ($val->is_required('title'))?' required':'';?>">
            <?php echo Form::label(__('model.topic.title'), 'title', array('class'=>'control-label')); ?>

            <?php echo Form::input('title', Input::post('title', isset($item) ? $item->title : ''), array('class' => 'form-control', 'placeholder'=>'')); ?>

        </div>

CSSで修飾

.form-group.required label:after{
  content:'*';
  color:#a94442;
  font-weight:bold;
  display:inline-block;
  margin-left:0.5em;
}

結果サンプル

1.PNG

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9