April 20, 2014, 8:36pm
I would like to add html5 placeholder text in my ActiveForm field and perhaps remove the label text without using CSS or JS.
The code I tried below outputs the following html.
<?= $form->field($model, 'company_name', [
['placeholder' => 'Company Name']] ) ?>
<div class="field-project-company_name" placeholder="Company Name">
<label class="control-label" for="project-company_name">Your Company Name</label>
<input type="text" id="project-company_name" class="form-control" name="Project[company_name]">
Does anyone have any ideas or suggestions?
One direct way to do this is to use my ActiveForm and ActiveField extension from yii2-widgets.
This will set label as placeholder across all possible fields (except inputs like checkbox/radio) in forms.
For all fields in form do this:
$form = kartik\widgets\ActiveForm::begin(['fieldConfig' => ['autoPlaceholder'=>true]]);
For only a specific field in form do this:
$form = kartik\widgets\ActiveForm::begin();
echo $form->field($model, 'username', ['autoPlaceholder'=>true])->textInput();
Alternatively, if you do not want to use the extension, you can play around with the template property of ActiveForm and ActiveField to achieve your requirement.
Don’t forget about older browsers. You will need to use jQuery plugin to solve this problem. First time when I faced with it, I read this article: cross-browser support for placeholder attribute in HTML5. I hope it will help you too.