1
私はset_value()
を使用してフォームにデータを埋め込みました。しかし、フィールドがempty()
(これが失敗した理由)であれば、set_value()はデフォルト値を挿入できますか?Codeigniter:set_value()が空の場合に文字列を挿入します。
私はset_value()
を使用してフォームにデータを埋め込みました。しかし、フィールドがempty()
(これが失敗した理由)であれば、set_value()はデフォルト値を挿入できますか?Codeigniter:set_value()が空の場合に文字列を挿入します。
回答が見つかりました。 2つのコールバック関数を使用してset_rules()
の値をインターセプトします。私はこの記事のコードを削除して理解しやすいようにしました。
configファイル:
// This is where the default text will come from so it's easy to modify
// The second config (['address']) is there just to show that ['test'] is an array
$config['test']['name'] = 'Default Text';
$config['test']['address'] = 'Some other text';
ルール:
// The sample rule. Do not add 'required' in the rules since _sanitize already
// does the checking for blank values. Insert the name of the field
// within the []. _sanitize() needs to be called before _check().
$this->form_validation->set_rules('name', 'Name', 'trim|callback__sanitize[name]|callback__check[name]');
2つのコールバック関数:_sanitize()および_check()
// CALLBACK: _sanitize
/*
* If field is empty(), inserts the default value found in the config file
* Works alongside _check().
*/
public function _sanitize($str, $arg){
if(empty($str)){
$text = $this->config->item('test');
return $text[$arg];
}
// If !empty(), return the value as if nothing happened
return $str;
}
// CALLBACK: _check
/*
* If value is equivalent to the default value (from the config file), mark it as FALSE
* Works alongside _sanitize().
*/
public function _check($str, $arg){
$text = $this->config->item('test');
if($str == $text[$arg]){
$this->form_validation->set_message('_check', 'The %s field is required');
return FALSE;
}
return TRUE;
}
最後に、ビューのコード:
// Put at top of page
<?php
$name = array(
'name'=>'name',
'value'=>set_value('name'),
'class'=>"form-text",
'maxlength'=>200
);
?>
// Put within the page
<?php echo form_input($name); ?>