Yii2 Boostrap ActiveForm Horizontal Layout - yii2

Good afternoon,
I am new to programming and struggling to understand Yii2 layout with Bootstrap.
What I am after is really simple, so I thought, but I can't seem to get it to remotely work. I want to create a horizontal form with the labels in front of each input and be able to control to the width of each input.
In my current code, I have 2 simple fields, I want the first to span half of the form (col-md-6) and the second should span the totality of the form (col-md-12), but this just isn't working and I don't understand the why so I'm struggling to fix it.
Below is my view
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;;
use yii\bootstrap\ActiveForm; //used to enable bootstrap layout options
/* #var $this yii\web\View */
/* #var $model backend\models\Projects */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="projects-form">
<?php
$form = ActiveForm::begin([
'id'=>$model->formName(),
'layout' => 'horizontal',
'class' => 'form-horizontal',
'fieldConfig' => [
'enableError' => true,
]
]);
?>
<h2>Project Information</h2>
<h3>General Information</h3>
<div class="form-group row">
<div class="col-md-6">
<?php
echo $form->field(
$model,
'ProjNo'
)->textInput(['maxlength' => true]);
?>
</div>
<div class="col-md-6">
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<?php
echo $form->field(
$model,
'ProjName'
)->textInput(['maxlength' => true]);
?>
</div>
</div>
<p></p>
<p></p>
<?php
ActiveForm::end();
?>
</div>
This is the _form view which is called within the create and update views.
What I don't quite get is why the label alignment isn't consistent because I specify a different width for the overall field and why even though I specified col-md-12, which should be full width from my understanding, it only seems to take about half of the available width.
Any help is greatly appreciated!
Thank you.
current example of what is generated
I just want the labels to line up and be able to have fields with different widths. In the above, when I change the class, the labels change alignment.

You can use the template option under the form's fieldConfig option like below to specify the order of the input, label, and error-block, and these settings would be applied throughout the form for all inputs, in below configurations I am placing the label after the input you can change that if you want.
$form = yii\bootstrap\ActiveForm::begin ( [ 'id' => $model->formName () ,
'layout' => 'horizontal' ,
'class' => 'form-horizontal' ,
'fieldConfig' => [
'enableError' => true ,
'template' => '{input}{error}{label}',
] ] );
you can wrap the {label} and {input} with div like
'template' => '<div class="col-sm-6">{input}{error}</div>
<div class="col-sm-3">{label}</div>',
and remove all the extra HTML from your view just wrap the $form->field() with row see below
$form = yii\bootstrap\ActiveForm::begin ( [ 'id' => $model->formName () ,
'layout' => 'horizontal' ,
'class' => 'form-horizontal' ,
'fieldConfig' => [
'enableError' => true ,
'template' => '<div class="col-sm-6">{input}{error}</div>{label}',
] ] );
?>
<h2>Project Information</h2>
<h3>General Information</h3>
<div class="row">
<?php
echo $form->field (
$model , 'ProjNo'
)->textInput ( [ 'maxlength' => true, ] );
?>
</div>
<div class="row">
<?php
echo $form->field (
$model , 'ProjName'
)->textInput ( [ 'maxlength' => true, ] );
?>
</div>
EDIT
as per discussion you do not want equally aligned labels and inputs but instead you want variable inputs and labels within each row and for doing so you need to configure the template part of the input fields separately and it can look like below if i understood correctly
you should configure your form options and field template options like below and remove the extra class applied on the label col-sm-3 by assigning it control-label class manually
$form = yii\bootstrap\ActiveForm::begin ( [ 'id' => $model->formName () ,
'layout' => 'horizontal' ,
'class' => 'form-horizontal' ,
'fieldConfig' => [
'enableError' => true ,
'options' => [
'class' => ''
]
] ] );
?>
<h2>Project Information</h2>
<h3>General Information</h3>
<div class="row">
<?php
echo $form->field (
$model , 'name' , [ 'template' => '<div class="col-sm-2">{label}</div><div class="col-sm-4">{input}{error}</div>' , ]
)->textInput ( [ 'maxlength' => true ] )->label ( null , [ 'class' => 'control-label' ] )
?>
<?php
echo $form->field (
$model , 'price' , [ 'template' => '<div class="col-sm-2">{label}</div><div class="col-sm-4">{input}{error}</div>' , ]
)->textInput ( [ 'maxlength' => true ] )->label ( null , [ 'class' => 'control-label' ] );
?>
</div>
<div class="row">
<?php
echo $form->field (
$model , 'product_subcategory' , [ 'template' => '<div class="col-sm-2">{label}</div><div class="col-sm-10">{input}{error}</div>' , ]
)->textInput ( [ 'maxlength' => true , ] )->label ( null , [ 'class' => 'control-label' ] );
?>
</div>
<?php
echo yii\bootstrap\Html::submitButton ( 'Submit' );
yii\bootstrap\ActiveForm::end ();
Hope this helps you out

Related

Strategi must be a string

please help me..
when data input arises such problems "Strategi must be a string."
this is my controller :
$isistrategi = $_POST['FormNarasi'];
$fn = FormNarasi::find()->where([
'kriteria_id' => $model->id,
'form_spmi_id' => $formSpmi->id,
])->one();
if(empty($fn))
$fn = new FormNarasi;
$fn->kriteria_id = $model->id;
$fn->form_spmi_id = $formSpmi->id;
$fn->strategi = $isistrategi;
this is my _form :
<?php
$fn = FormNarasi::find()->where([
'kriteria_id' => $model->id,
'form_spmi_id' => $formSpmi->id
])->one();
echo $form->field($fn, 'strategi')->widget(CKEditor::className(), [
'options' => ['rows' => 6],
'preset' => 'advance'
])
?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success','value'=>'1','name'=>'btn-submit']) ?>
</div>
<?php ActiveForm::end(); ?>
please help, master
Here you are assigning an array to the model
$isistrategi = $_POST['FormNarasi'];
...
$fn->strategi = $isistrategi; // HERE
and in the following code you are accessing it. There is an array assigned. So you should assign there a string (the content of the CKEditor)
echo $form->field($fn, 'strategi')->widget(CKEditor::className(), [ // HERE
...
])
As #Sfili_81 mentioned, do not access the $_POST directly and rather use $model->load(Yii::$app->request->post())

Cakephp3: How to output checkboxes into 2 colums?

I have this call to output a set of checkboxes within my view:
<?=$this->Form->input('roles._ids', [
'options' => $roles,
'label' => false,
'multiple' => 'checkbox',
'templates' => [
'checkboxWrapper' => '<label class="mt-checkbox">{{label}}<span></span></label>',
'nestingLabel' => '{{input}}{{text}}',
'inputContainer' => '<div class="col-md-1" style="padding-top: 10px;"><div class="mt-checkbox-list" data-error-container="#form_2_services_error">{{content}}</div></div>'
]]);
?>
Does anyone know a solution - how to break the output into 2 divs?
I wanted to have half the checkboxes in a single
<div class="col-md-1" style="padding-top: 10px;">
(see line "inputContainer") div container. Is that anyhow possible?
If you want to separate checkbox in two columns you can do like this
<?php
$this->Form->templates([
'checkboxWrapper' => '<div class="col-md-6">{{label}}</div>'
]);
?>
<?=$this->Form->input('roles._ids', [
'options' => ['asdasd','asdasd','asdasd'],
'label' => false,
'multiple' => 'checkbox',
]);
?>
OR you can just change the style of default template of cakehphp by adding this css
.checkbox {
width: 49%;
display: inline-block;
}
Hope this will help

Yii2 How to Use Html::tag or Html::beginTag

i want to echo like this
<li>
<img src="img/h4-slide.png" alt="Slide">
<div class="caption-group">
<h2 class="caption title">some_title
</h2>
<h4 class="caption subtitle">Dual SIM</h4>
<a class="caption button-radius" href="some_route"><span class="icon"></span>check</a>
</div>
</li>
here my code for render image carousel :
$slides = [];
foreach (Slide::find()->orderBy('sortOrder')->all() as $slide) {
/** #var $slide common\models\Slide */
$slides[] = [
'content' => Html::img(Yii::$app->urlManager->baseUrl . '/uploads/slide/' . $slide->id . '.jpg'),
'caption' => Html::tag('content-group', $slide->title)."<br>".$slide->body,
];
}
And my carousel :
<div class="slider-area">
<div class="block-slider block-slider4">
<?= Carousel::widget([
'id' => 'bxlider-home',
'items' => $slides,
'options' => [
'class' => 'slide',
'data-interval' => 3000,
],
'controls' => [
'<span class="bx-next fa fa-angle-left"></span>',
'<span class="bx-prev fa fa-angle-right"></span>',
],
]) ?>
</div>
</div>
how to Slide->title, slide->body, and some links can be in class caption-group ?
I think it would be better to create new partial file.
Create a new file called _slider.php
Call $this->render('_slider') inside configuration of the slider. Please check below code.
$slides = [];
foreach (Slide::find()->orderBy('sortOrder')->all() as $slide) {
/** #var $slide common\models\Slide */
$slides[] = [
'content' => $this->render("_slider"),
'caption' => Html::tag('content-group', $slide->title)."<br>".$slide->body,
];
}
You can write html inside _slider.php easily now. Don't need to use Html::beginTag() etc.
Generating Tags
The code generating a tag looks like the following:
<?= Html::tag('p', Html::encode($user->name), ['class' => 'username']) ?>
<p class="username">samdark</p>
$options = ['class' => ['btn', 'btn-default']];
echo Html::tag('div', 'Save', $options);
// renders '<div class="btn btn-default">Save</div>'
Hyperlinks:
<?= Html::a('Profile', ['user/view', 'id' => $id], ['class' => 'profile-link']) ?>
Images:
<?= Html::img('#web/images/logo.png', ['alt' => 'My logo']) ?>
generates
<img src="http://example.com/images/logo.png" alt="My logo" />
Lists:
<?= Html::ul($posts, ['item' => function($item, $index) {
return Html::tag(
'li',
$this->render('post', ['item' => $item]),
['class' => 'post']
);
}]) ?>
Even more?
visit

yii2 ActiveForm numeric textfield

I've created an ActiveForm using yii2 like this:
<?=$form->field($item, 'finalPrice', [
'options' => [
'tag' => 'div',
'class' => '',
],
'template' => '<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label>{input}{error}</span>'
])->textInput([
// ** i want numeric value **
])->label(false)?>
and it rendered a result of:
<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label><input type="text" id="item-finalprice" class="form-control" name="Item[finalPrice]"><p class="help-block help-block-error"></p></span>
now i want to make it < input type="number" .. and not text.. (so user could change value using browser up/down buttons). is there any way to do it?
You can use ->textInput(['type' => 'number'] eg :
<?=$form->field($item, 'finalPrice', [
'options' => [
'tag' => 'div',
'class' => '',
],
'template' => '<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label>{input}{error}</span>'
])->textInput([
'type' => 'number'
])->label(false)?>
Try this . it worked for me
<?= $form->field($model, 'amount')->textInput(['type' => 'number']) ?>
Field like Phone Number/Membership No etc, some time we allow user only to enter numeric input in a text field. In such case applying pattern match rule work great for me.
Simply set a rule in the model class and you are done.
public function rules()
{
return [
...
[['contactno'], 'string', 'max' => 25],
[['contactno'], 'match' ,'pattern'=>'/^[0-9]+$/u', 'message'=> 'Contact No can Contain only numeric characters.'],
...
];
}
<?= $form->field($model, 'code')->textInput(['type'=>'number']) ?>

Getting label with colon for model's field in a form

I need to have Body: (with colon at the end), not Body rendered as label for each field in my form. How can I achieve this the best way?
I tried modifying fieldConfig => template in ActiveForm::begin by adding div class=\"\">{label}:</div> into it:
<?php $form = ActiveForm::begin([
'id' => 'edit-form',
'options' => ['class' => 'form-horizontal'],
'fieldConfig' => [
'template' => "<div class=\"\">{label}:</div>\n<div class=\"\">{input}</div>\n<div class=\"\">{error}</div>",
'labelOptions' => ['class' => 'edit-label'],
]]); ?>
but it is wrong. Colon is rendered as separate DOM element, with incorrect styling and looks ugly.
I tried doing this awfully in CSS:
.edit-label::after {
content: ":";
}
but this is even worse.
I remember, that I made a lot of stupid things in Yii1 to get this. I don't want to repeat these stupid things, when implementing this in Yii2. What is the best way of achieving this?
When using Bootstrap 3 (yii\bootstrap\ActiveField) you can use additional placeholders in the $template and you need to replace {label} with {beginLabel}{labelTitle}:{endLabel}:
<?php $form = ActiveForm::begin([
'id' => 'edit-form',
'options' => [
'class' => 'form-horizontal',
'enctype'=>'multipart/form-data'
],
'fieldConfig' => [
'template' => "<div class=\"\">{beginLabel}{labelTitle}:{endLabel}</div>\n<div class=\"\">{input}</div>\n<div class=\"\">{error}</div>",
'labelOptions' => ['class' => 'edit-label'],
],
]); ?>
I don't know, how to solve this problem, if you're using basic yii\widgets\ActiveField instead.