symfony でいくつかのフォームを構成しています。必要なことの 1 つは、必須フィールドの横にアスタリスク (*) またはその他のインジケーターを付けることです。フィールドはすべてフォームフレームワークで必須に設定されており、フォームが送信されると「このフィールドは必須です」というエラーが返されますが、フォームが送信される前にインジケーターが必要です。
各フィールドのラベルを手動でオーバーライドせずにこれを行う方法はありますか?
symfony でいくつかのフォームを構成しています。必要なことの 1 つは、必須フィールドの横にアスタリスク (*) またはその他のインジケーターを付けることです。フィールドはすべてフォームフレームワークで必須に設定されており、フォームが送信されると「このフィールドは必須です」というエラーが返されますが、フォームが送信される前にインジケーターが必要です。
各フィールドのラベルを手動でオーバーライドせずにこれを行う方法はありますか?
元のクックブックからのより簡単な解決策はどうですか - 小枝のほんの数行:
これは、 Kris Wallsmith のブログにある自動解決策です。
lib/formatter/RequiredLabelsFormatterTable.class.php、これにより、必須フィールドのラベルに「必須」クラスが追加されます
<?php
class RequiredLabelsFormatterTable extends sfWidgetFormSchemaFormatterTable
{
protected
$requiredLabelClass = 'required';
public function generateLabel($name, $attributes = array())
{
// loop up to find the "required_fields" option
$widget = $this->widgetSchema;
do {
$requiredFields = (array) $widget->getOption('required_fields');
} while ($widget = $widget->getParent());
// add a class (non-destructively) if the field is required
if (in_array($this->widgetSchema->generateName($name), $requiredFields)) {
$attributes['class'] = isset($attributes['class']) ?
$attributes['class'].' '.$this->requiredLabelClass :
$this->requiredLabelClass;
}
return parent::generateLabel($name, $attributes);
}
}
lib/form/BaseForm.class.php、これはプロジェクト内のすべてのフォームに共通の基本クラスです:
protected function getRequiredFields(sfValidatorSchema $validatorSchema = null, $format = null)
{
if (is_null($validatorSchema)) {
$validatorSchema = $this->validatorSchema;
}
if (is_null($format)) {
$format = $this->widgetSchema->getNameFormat();
}
$fields = array();
foreach ($validatorSchema->getFields() as $name => $validator) {
$field = sprintf($format, $name);
if ($validator instanceof sfValidatorSchema) {
// recur
$fields = array_merge(
$fields,
$this->getRequiredFields($validator, $field.'[%s]')
);
} else if ($validator->getOption('required')) {
// this field is required
$fields[] = $field;
}
}
return $fields;
}
__construct()
メソッドの BaseForm にも次の数行を追加します。
$this->widgetSchema->addOption("required_fields", $this->getRequiredFields());
$this->widgetSchema->addFormFormatter('table',
new RequiredLabelsFormatterTable($this->widgetSchema)
);
このすべての後、すべてのラベルにrequired
クラスがあり、必要なcssを使用してユーザーにマークします。
私はJavascriptを使用してそれを行いました:
$('form').find('select, input, textarea').each(function(){
if($(this).attr('required') == 'required'){
$label = $('label[for='+ $(this).attr('id') +']');
if($label.find('.required-field').length == 0){
$label.append('<span class="required-field">*</span>');
}
}
});
フィールドのクラスをコンストラクタの一部として設定できますsfWidget
すなわち
$this->widgetSchema['form_field'] = new sfWidgetFormInput(array(), array('class' => 'required_field'));
注: これは、古い sfForms (ala 1.0) を使用していないことを前提としています。
ここでの更新 は、必要なアスタリスクを表示するための techchorus.net の CSS コードです。
.required
{
background-image:url(/path/to/your/images/dir/required-field.png);
background-position:top right;
background-repeat:no-repeat;
padding-right:10px;
}