yii2 adding a extra value in form field - php

I am working in a yii2 project. I have a form with text field. One field in form is length. currently I use text field for that. What I need is a text field for value and followed by a dropdown box in that we can choose cm or inch or pixel like that. How to do that and How to get value in controller.

You can do it by 2 ways:
First,
Take an input field and one dropDownList using html helper class or you can create simple dropDownList using html
<?= $form->field($model, 'length')->textInput(['maxlength' => 255]); ?>
<?= Html::dropDownList('length_type', null,[ 'cm' => 'cm', 'inch' => 'inch', 'pixel' => 'pixel'],['class' => 'form-control','id'=>'length_type']) ?>
if you want to use html helper class than import Html class as below
use yii\helpers\Html;
Now, use length type in controller
if(isset($_POST['length_type']) && $_POST['length_type'] !=null)
{
$len_type=$_POST['length_type'];
// use this variable according to yuor need
}
Second,
decalare varibale length_type in model class
in view,
<?= $form->field($model, 'length')->textInput(['maxlength' => 255]); ?>
<?= $form->field($model, 'length_type')->dropDownList([ 'cm' => 'cm', 'inch' => 'inch', 'pixel' => 'pixel'], ['class' => 'priority_list']) ?>
In controller you can use model variable directry as
$len=$model->length;
$len=$model->length_type;

Related

how to get and display username in another form field when user select name from dropdownlist in yii2?

I want to display the lecturer username in another text input field form when the user selects the lecturer name in the drop-down list above.
this is my code for drop-down list lecturer name
<?= $form->field($model, 'LecturerName')->dropDownList(
ArrayHelper::map(User::findAll(['category' => 'lecturer']),'fullname','fullname'),
['prompt'=>'Select Lecturer']
) ?>
this is my code for lecturer username
<?= $form->field($model, 'LecUsername')->textInput(['maxlength' => true]); ?>
I want to get and display the LecUsername based on the selected drop-down list above. the LecUsername is from the database.
As you are using the dropdown you need to bind the change event for the dropdown to insert the value from the dropdown to the input text. And to make sure that you are inserting the LecUsername for the LecturerName you need to have the LecUsername as the value for the dropdown, means the drop-down data should have the username field as the index, currently you are using the fullname as the index and the value so change the code according to the field name you have for the username, i assume it is username for the example.
ArrayHelper::map(User::findAll(['category' => 'lecturer']),'username','fullname')
so your dropdown code will look like
<?= $form->field($model, 'LecturerName')->dropDownList(
ArrayHelper::map(User::findAll(['category' => 'lecturer']),'username','fullname'),
['prompt'=>'Select Lecturer']
) ?>
then add the below on top of your view file where you have the form
$ddId=Html::getInputId($model, 'LecturerName');
$inputId=Html::getInputId($model, 'LecUsername');
$js = <<< JS
$(document).ready(function(){
$("#{$ddId}").on('change',function(e){
$("#{$inputId}").val($(this).val());
});
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
A better way for dropdowns is to use the library Kartik-v\select2 and use the event pluginEvents option to specify the event select2:select, your code should look like below in that case.
// Usage with ActiveForm and model
echo $form->field($model, 'LecturerName')->widget(Select2::classname(), [
'data' => ArrayHelper::map(User::findAll(['category' => 'lecturer']),'username','fullname'),
'options' => ['placeholder' => 'Select Lecturer'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents'=>[
"select2:select" => 'function() { $("#{$ddId}").on('change',function(e){
$("#{$inputId}").val($(this).val());
}); }',
]
]);

Yii2 check if a package is defined or not

In another Yii2 application I used a package called navatech/yii2-roxymce to replace the textarea with HTMl editable box. In the current application I don't want to use it while I want to keep everything easy reusable. In other words, I want a conditional check says that, if the package is installed call it, if not call the ordinary active form textarea.
I have tried class_exists like the following:
<?php
// _form.php code
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\Url;
use navatech\roxymce\widgets\RoxyMceWidget;
......
<?php if (class_exists('RoxyMceWidget')): ?>
<?= RoxyMceWidget::widget([
'model' => $model, //your Model, REQUIRED
'attribute' => 'content', //attribute name of your model, REQUIRED if using 'model' section
'name' => 'Post[content]', //default name of textarea which will be auto generated, NOT REQUIRED if using 'model' section
'value' => isset($_POST['Post']['content']) ? $_POST['Post']['content'] : $model->content, //default value of current textarea, NOT REQUIRED
'action' => Url::to(['roxymce/default']), //default roxymce action route, NOT REQUIRED
'options' => [//TinyMce options, NOT REQUIRED, see https://www.tinymce.com/docs/
'title' => 'RoxyMCE',//title of roxymce dialog, NOT REQUIRED
'height' => 450,
],
]);?>
<?php else: ?>
<?= $form->field($model, 'content')->textarea(['rows' => 14]);?>
<?php endif; ?>
.....
However, after the installation of navatech\roxymce\widgets\RoxyMceWidget using composer, the conditional statement gives the same result. i.e printing the ordinary activeform text area, so class_exists seems to always return false inspite off the widget is being installed.
Is there any other right way to check if a package is found or not?
You must provide fully qualified namespace for the class.
class_exists('navatech\roxymce\widgets\RoxyMceWidget')
with prs4 you must include namespace:
class_exists('navatech\roxymce\widgets\RoxyMceWidget')
or:
class_exists(RoxyMceWidget::className()) if it already defined in the use statement.
updated: you should use lastest version of yii2-roxymce, current is 2.0.0.1

yii2 DetailView template/layout without values

I have a little problem in yii2 framework.
I have DetailView widget
<?= DetailView::widget([
'model' => $table_1,
'attributes' => [
'year',
'table_zs_field_1',
'table_zs_field_2',
'table_zs_field_3',
'table_zs_field_4',
'table_zs_field_5',
'table_zs_field_6',
'table_zs_field_7',
'table_zs_field_8',
'table_zs_field_9',
'table_zs_field_10',
'table_zs_field_11',
'table_zs_field_12',
'table_zs_field_13',
'table_zs_field_14',
'table_zs_field_15',
'table_zs_field_16',
'table_zs_field_17',
'table_zs_field_18',
'table_zs_field_19',
],
]) ?>
If i write this to code I'll see a DetailView widget with names of fields(get from model) and values.
Problem: I want to hide values and show only names of fields from model and in next time hide names and show only values. Anybody know ?
Change the $template property of the Detailview.
The Default is
$template = '<tr><th>{label}</th><td>{value}</td></tr>'
Adding
'template'=>'<tr><th>{label}</th></tr>' ,
to the config array of your DetailView should show only the names of the fields.
Adding
'template'=>'<tr><td>{value}</td></tr>',
should show only the value.
See the corresponding section in the Documentation of DetailView.

Is it possible to redirect using dropdown onchange using value as parameter?

Using Yii2 I have the following code which displays a dropdown with my list of categories.
I was wondering is it possible so that on change the action executed is localhost:8888/article/category?id=1 rather that what it is atm (localhost:8888/article/category).
Does this require AJAX and/or JS or can it be done just using php?(id prefer php)
<?php $form = ActiveForm::begin(['id' => 'category-form', 'action' =>
'/advanced/article/category',]); ?>
<?= $form->field($model, 'category')->dropDownList($model->categoryList,[
'prompt'=>'Select Category to view',
'onchange'=>'this.form.submit()'
]) ?>
<?php ActiveForm::end(); ?>
You dont need ajax for this. js will do it.
<?= $form->field($model, 'category')->dropDownList($model->categoryList,[
'prompt'=>'Select Category to view',
'id'=>'cat-id',
]) ?>
And js to redirect when selected
$this->registerJs(
'$(document).ready(function(){
$("#cat-id").change(function(){
var e = document.getElementById("cai-id");
var strSel = e.options[e.selectedIndex].value;
window.location.href="'.Yii::$app->urlManager->createUrl('category?id=').'" + strSel;
});
});', View::POS_READY);
If you want use onchange attribute without writing any additional javascript, you need correct your code a bit more to get it working.
1) Change you form method to get (by default it's post):
<?php $form = ActiveForm::begin([
'id' => 'category-form',
'action' => '/advanced/article/category',
'method' => 'get', // Add this to your code
]); ?>
2) Explicitly set name of the category field in dropDownList options to avoid wrapping in formName():
<?= $form->field($model, 'category')->dropDownList($model->categoryList, [
'prompt'=>'Select Category to view',
'onchange'=>'this.form.submit()',
'name' => 'category', // Add this to your code
]) ?>
sorry you can make a onchange example but this time with a radiolist in yii2
field($model, 'estadoLaboral')->radioList(array('T'=>'Actualmente trabajo aquí','B'=>'Ya no trabajo aquí')) ?>
using javascript

Select or Dropdown list from CActiveRecord in Yii

I have table types and i want to build selectbox with all values from this table
In my controller i wrote this code
$allRegistrationTypes = RegistrationType::model()->findAll();
$this->render('index', array('allRegistrationTypes' => $allRegistrationTypes))
How build selectbox in view file ?
Well then its pretty simple all you need to do is first create List Data like
CHtml::ListData(allRegistrationTypes,'value you want to pass when item is selected','value you have to display');
for ex
typeList = CHtml::ListData(allRegistrationTypes,'id','type');
now remember both id and type are fields in table
now all you have to do is if you are using form then
<?php echo $form->dropDownList($model, 'type_id', $typeList, array('empty'=>'Select a tyoe')); ?>
and if you need multiple you can pass multiple => multiple in the array as htmlOptions
You would use CHtml::dropDownList, or activeDropDownList if there is a "parent" model and you want to leverage its validation rules.
If you want to make the <select> element multiple-selection-capable, pass in 'multiple' => 'multiple' and 'size' => X as part of the $htmlOptions parameter.
Simplest Method to get "Select Box" in YII Framework:
<div class="row">
<?php
echo $form->labelEx($model,'county');
$data = CHtml::listData(County::model()->findAll(), 'id', 'county');
$htmlOptions = array('size' => '1', 'prompt'=>'-- select county --', );
echo $form->listBox($model,'county', $data, $htmlOptions);
echo $form->error($model,'county');
?>
</div>
Good Luck..

Categories