Yii2 Checkbox list, not checked model values - php

Lets talk in code directly.
<div class="checkbox-list">
<?php
var_dump ($model->categoriesIds); // [1,2] so database has two categries.
$cats=Category::find()->all(); foreach($cats as $i=>$category){?>
<?= $form
->field($model, 'categoriesIds[]')
->checkbox([
'label'=>$category->name,
'value' => $category->id
])
->label(false)
?>
<?php } if(count ($cats)==0){ echo '<li>No Categories found.</li>';} ?>
</div>
i've categories's values but it don't check checkboxes based on this array, its saving values as well properly.

Use checkboxlist to loop your categories
<?
use yii\helpers\ArrayHelper;
$cats=Category::find()->all();
$cats=ArrayHelper::map($cats, 'id', 'name');
echo $form->field($model, 'categoriesIds[]')->checkboxList($cats);
?>

all();
$regs=ArrayHelper::map($reg, 'region_id', 'region_name');
?>
<?php echo $form->field($model, 'region_id[]')->checkboxList($regs); ?>

Related

how to set default selection in radio button - Active form yii

Here i need to add default selection in radio button(checked).
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'email') ?>
<?php if(!empty($usernames)){
echo '<label>Select Any Username To Which You Want To Login</label><div class="all_username">';
foreach ($usernames as $key => $value) { ?>
<?= $form->field($model, 'username[]')->radio(['value' => $value['username'], 'id' => ''])->label($value['username']) ?>
<?php } ?>
</div>
<?= $form->field($model, 'password')->passwordInput() ?>
<?php } ?>
You need to use following method where 1 is your selected ID.
$form->radioButtonList($model,'1', $usernames, array('separator'=>"" ));
You can probably use something like this:
foreach ($usernames as $key => $value) {
if(/*somecondition*/){
$model->username = $value['username'];
}?>
<?= $form->field($model, 'username[]')->radio(['value' => $value['username'], 'id' => ''])->label($value['username']) ?>
<?php } ?>
Only by assigning the $model->username a default value you can choose which radio will be selected.

how to display all the users in table users to my subjects table in add.ctp view

Here is my subjects add.ctp view
<?= $this->Form->create($subject) ?>
<fieldset>
<legend><?= __('Add Subject') ?></legend>
<?php
echo $this->Form->input('math');
echo $this->Form->input('english');
echo $this->Form->input('history');
echo $this->Form->input('science');
******this field will display all the users in drop down************* from users table
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
****UsersController.php ****
public function index()
{
$user= $this->set('users', $this->paginate());
$this->set('user', $user);
$this->set('_serialize', ['user']);
}
How to achieve this one please help me...
If you want user select box(Dropdown) in the subject add.ctp then you should send all the list of user from add() of SubjectsController.
In subjects add method
public function add()
{
//Your previous logics
$this->loadModel('Users');
$users= $this->Users->find('list');
$this->set('users', $users);
$this->set('_serialize', ['users']);
//Your previous logics
}
In your subject add.ctp
<?= $this->Form->create($subject) ?>
<fieldset>
<legend><?= __('Add Subject') ?></legend>
<?php
echo $this->Form->input('math');
echo $this->Form->input('english');
echo $this->Form->input('history');
echo $this->Form->input('science');
echo $this->Form->input('user_id', ['options' => $users]);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
In your UsersTable(Users Model), add/edit your initialize() as follow
$this->displayField('username');
$this->primaryKey('id');
at your Controller
$allUser = $this->Users->find(); // this will be get all user from user table
$this->set('allUser', $allUser);
at your View
/**#var array $allUser */// already type of array
<?= $this->Form->select('all_user', [
'multiple' => true,
'value' => $allUser
]); ?>
Use $this->Form->select() or $this->Form->input('users', ['options' => array()]);
if you do not want to do foreach loop.
try:
<?= $this->Form->select('users', $users); ?>

Codeigniter updating database with checkbox

i have a table named group where i have columns like admin,editor,user,guest they are all boolean.
i want to create a group using checkbox. so in my view i got checkbox like admin,editor,user,guest and a create button. When i click the create button i want the checked options to be true in database and unchecked remains false. how can i do that?
I am new in codeigniter.
<html>
<head>
<title>Create A group</title>
</head>
<body>
<?php echo form_open('group/create_group'); ?>
<div>
<?php echo form_label("Gruop Name"); ?>
<?php
$data=array(
'name'=>'group_name',
'placeholder'=>'enter group name'
);
?>
<?php echo form_input($data); ?>
</div>
<div>
<?php $data=array(
'name'=>'role[]',
'value'=>'1',
'type'=>'checkbox'
);
?>
<?php echo form_label('Admin'); ?>
<?php echo form_checkbox($data); ?>
</div>
<div>
<?php $data=array(
'name'=>'role[]',
'value'=>'2'
);
?>
<?php echo form_label('User'); ?>
<?php echo form_checkbox($data); ?>
</div>
<div>
<?php $data=array(
'name'=>'role[]',
'value'=>'3'
);
?>
<?php echo form_label('Editor'); ?>
<?php echo form_checkbox($data); ?>
</div>
<div>
<?php $data=array(
'name'=>'role[]',
'value'=>'4'
);
?>
<?php echo form_label('Others'); ?>
<?php echo form_checkbox($data); ?>
</div>
<div>
<?php $data=array(
'type'=>'submit',
'value'=>'Create'
); ?>
<?php echo form_submit($data); ?>
</div>
<?php echo form_close(); ?>
</body>
First
Set "false" as default value at all those fields.
Second
If you can set only one role per user then you should use radiobox instead checkbox
Third
Capture the parameters sent by the post.
Assuming that you created a route for group/create_group that goes to the data_submitted method
public function data_submitted() {
$data = array(
'role' => $this->input->post('role'),
//more info that you get from the post..
);
Now load your model and save it...
}
Put off [] and in your php file logic your can do : $this->input->post("role"); and get value. If you want to do multi-choice's checkbox your must change to an unique name and set value to true for each of them.
Have nice day !

List to DropDown list in Yii

Please help with this code:
<ul class="activity-projects">
<?php foreach ($ownProjects as $userProject) : ?>
<li>
<a class="<?php echo ($userProject->id == $project_id) ? 'active' : '';?>"
href="<?php echo Yii::app()->createUrl('user/activity', array(
'user_id'=>$user->id,
'project_id'=>$userProject->id,
'date'=>$date)
); ?>"><?php echo $userProject->name; ?></a>
</li>
<?php endforeach; ?>
<?php foreach ($projects as $userProject) : ?>
<li>
<a class="<?php echo ($userProject->project_id == $project_id) ? 'active' : '';?>"
href="<?php echo Yii::app()->createUrl('user/activity', array(
'user_id'=>$user->id,
'project_id'=>$userProject->project->id,
'date'=>$date)
); ?>"><?php echo $userProject->project->name; ?></a>
</li>
<?php endforeach; ?>
</ul>
How to change it to dropdown list, using CHtml::dropDownList. Thanks for watching!
First, you need to define a key-value array like this:
$options = array();
<?php foreach ($ownProjects as $userProject)
array_push($options, array($userProject->id => $userProject->name));
?>
echo CHtml::dropDownList('seletName', '1', $options);
This will be produced an html <select> tag with "seletcName" name. And also option with value "1" will be selected option. You can use your desired value for first and second parameters.
Also you can use CActiveForm#dropDownList for this purpose.
In your form, use the form dropDownList() function.
<?php echo $form->dropDownList(
$model,
'project_id',
CHtml::listData(OwnProjects::model()->findAll(),
'id', 'name'),
array('empty' => '(Select project)','class'=>"form-control")
);
?>
From your example, it looks like OwnProjects is not a model on its own, but a subset of a model. You can customise the query
<?php echo $form->dropDownList(
$model,
'project_id',
CHtml::listData(OwnProjects::model()->findAllByAttributes(array('user_id'=> Yii:app()->user->id),
'id', 'name'),
array('empty' => '(Select project)','class'=>"form-control")
);
?>
This solution finally helps me:
<?php $options = array();
foreach ($projects as $userProject) :
$options[$userProject->id] = $userProject->project->name;
endforeach;
echo CHtml::dropDownList('selectName', '1', $options);
?>

yii manage sub table's data in form

I am working on YII framework, and I am a newbie.
I have user register form as shown below:
Username: [Textbox]
Email: [Textbox]
Address: [Text area]
User Loan Type: (Checkbox list as below)
Loan Type 1
Loan Type 2
Loan Type 3
Loan Type 4
Loan Type 5
Status [yes/no]
Now I have 3 models:
1) User (for user data)
2) LoanType (just for loan type list)
3) UserLoanType (mapping between user and loan type)
All 3 models have HAS_MANY and BELONGS_TO relations as we generally do in YII.
Now when user click on register button I want to save data in user_loan_type table as well. I can simply add core php logic in actionCreate. But is there any standard YII practice for this?? Because I need validation, remain form selected during edit etc. Can anyone guide me how to do this? Or point me any example link, I have googled but did't help.
Thanks.
I am able to save data in database,
Now during edit I want to retrieve 3rd table's(tbl_user_loan_request_type) data. I have used below code.
$user = User::model()->findByPk(5);
print_r($user->UserLoanTypes);
But it is giving me blank array.
Where I am wrong??
You may define afterSave methods in your class, like this:
Model User
public function relations()
{
return array(
'UserLoanTypes' => array(self::MANY_MANY, 'LoanType', 'UserLoanType(userId, loanId)'),
);
}
// relation
array('UserLoanTypes', 'safe'),
// label
'UserLoanTypes' => 'User Loan Type'
protected function afterSave()
{
parent::afterSave();
UserLoanType::model()->deleteAll('userId=:id', array(':id' => $this->id));
foreach ($this->UserLoanTypes as $loanId) {
$userLoanType = new UserLoanType();
$userLoanType->userId = $this->id;
$userLoanType->loadId = $loadId;
$userLoanType->save();
}
}
protected function afterDelete()
{
parent::afterDelete();
UserLoanType::model()->deleteAll('userId=:id', array(':id' => $this->id));
}
In form:
<div class="row">
<?php echo $form->labelEx($model,'UserLoanTypes'); ?>
<?php echo $form->checkBoxList($model,'UserLoanTypes', CHtml::listData($LoanTypes, 'id', 'loanName')); ?>
<?php echo $form->error($model,'UserLoanTypes'); ?>
</div>
In view you may:
<?php $this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'id',
'name',
'UserLoanTypes' => array(
'name' => 'UserLoanTypes',
'value' => implode(',', CHtml::listData($model->UserLoanTypes, 'id', 'name')),
),
),
)); ?>
If you don't need to assign multiple loanTypes to one User, it would be easier. All you need is the User model for the form visualization:
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'user-form',
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'Username'); ?>
<?php echo $form->textField($model,'Username'); ?>
<?php echo $form->error($model,'Username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Email'); ?>
<?php echo $form->textField($model,'Email'); ?>
<?php echo $form->error($model,'Email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Address'); ?>
<?php echo $form->textArea($model,'Address'); ?>
<?php echo $form->error($model,'Address'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'UserLoanType'); ?>
<?php echo $form->checkBoxList($model,'idLoanType', CHtml::listData(LoanType::model()->findAll, 'id', 'name')); ?>
<?php echo $form->error($model,'UserLoanTypes'); ?>
</div>
<?php $this->endWidget(); ?>

Categories