yii2 inserting 2 params as text inside dropdownlist - activerecord

Here is yii2 drop down list.
<?php echo $form->field($model, 'param1')->dropDownList(
ArrayHelper::map(Model::find()->all(),'param1','param2');
It makes drop Down list with values of param1s and text to choose from of param2s.
So you see param2 texts , choose one and corresponding param1 value goes to server.
No my problem is that I want to do the same but show user not only param2 text but I want text to be constructed from param2+param3.
example of what I want.
hidden value___________text
1_____________________alpha
2_____________________bravo
3_____________________lima
hidden value___________text
1_____________________alpha-red
2_____________________bravo-white
3_____________________lima-blue
Is that possible ?

One of the ways to do it will be using built-in ArrayHelper with toArray() method.
Put this in your model:
use yii\helpers\ArrayHelper;
...
public static function getList()
{
$initialModels = static::find()->all();
$models = ArrayHelper::toArray($initialModels, [
'app\models\YourModel' => [
'param1',
'combinedParam' => function ($model) {
return "$model->param2 - $model->param3";
},
],
]);
return ArrayHelper::map($models, 'param1', 'combinedParam');
}
Displaying it in view:
<?= $form->field($model, 'param1')->dropDownList(YourModel::getList()) ?>

Related

yii2 not rendering to view just refreshing the page

view.php code part:
View Picture
viewgood.php
<?php
echo 'hello';
GoodsController.php
public function viewgood($id = null) {
}
After clicking on button View Picture my page just refreshing instead of going to viewgood.php
What am I doing incorrectly?
I am a begginer in Yii2
Try use
View Picture
in a anchor tag html your need use the complete route, for use shortcut you try use
<?= Html::a('View Picture', ['/goods/viewgood/', 'id' => $good['GoodGallery'][0]['id']], ['class' => 'btn btn-primary']) ?>
view.php
You can use Html:a(), or in your example use Url helper to() function to generate the proper route for your anchor tag.
View Picture
GoodsController.php
public function actionViewgood($id=null){
//fetch the data e.g.
$model = Good::findOne(id);
//Do some extra code checking when no record is found like throw an exception or set a flash error message, etc.
//render the viewgood and pass the data (if needed)
return $this->render('viewgood', [
'model' => $model
]);
}
viewgood.php
<?php
//do what you want with the data passed by the controller. E.g. print the name of the good (if applicable)
echo $model->name;
//your other code ...
?>

Validation message not showing below the field in cakephp 3 latest version

I am trying to validate a multiple select field that have jquery chosen applied.
Validation is working perfectly but only problem is that validation message is not showing below the input field.
Here is my files.
profile_edit.ctp
<?php echo $this->Form->create($user,['action' => '', 'role'=>"form",'novalidate'=>true,'method'=>'post','id'=>'ProfileForm','templates'=>['label'=>false,'inputContainer'=>'{{content}}']]); ?>
<?php echo $this->Form->control('user_grades[].grade_id',['multiple','hiddenField'=>false, 'escape'=>false, 'type'=>'select', 'id'=>'sp_grade', 'options'=>App\Model\Table\GradesTable::getGrades('list'),'class'=>'form-control chosen-select']); ?>
<button type="submit" class="btn footer_btns float-left">Save</button>
<?php echo $this->Form->end(); ?>
MyAccountController.php
<?php
public function profileEdit(){
$user = $this->Users->get($this->Auth->user('id'), ['contain'=>['UserGrades']]);
if($this->request->is(['put','post'])){
$data = $this->request->getData();
if(isset($data['user_grades']) && !empty($data['user_grades'])) {
$this->UserGrades->deleteAll(['user_id' => $this->Auth->user('id')]);
}
if(null == $this->request->getData('user_grades')){
$this->request = $this->request->withData('user_grades.0.grade_id','');
}
$user = $this->Users->patchEntity($user, $this->request->getData(), [
'validate' => 'editProfileSection',
'associated' => [
'UserGrades' => ['validate'=> 'editProfileSection']
]
]);
if(empty($user->getErrors())){
if ($this->Users->save($user)) {
$this->Flash->success(__('Succesfully updated <strong>'.$user->full_name .'</strong> Information||Success'));
return $this->redirect(['action' => '']);
}
}
$this->Flash->error(__('Please check your inputs and try again.||Action Failed!'));
}
$this->set(compact('user'));
}
UserGradesTable.php
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\ORM\Query;
use Cake\ORM\TableRegistry;
use Cake\Event\Event;
use Cake\ORM\RulesChecker;
use Cake\Validation\Validator;
class UserGradesTable extends Table {
public function initialize(array $config) {
$this->addBehavior('Timestamp');
$this->addBehavior('Trim');
}
public function validationEditProfileSection(Validator $validator) {
$validator
->notEmpty('grade_id',"Please select at least one grade.");
return $validator;
}
}
I have tried to get error message and got following:
Array
(
[user_grades] => Array
(
[0] => Array
(
[grade_id] => Array
(
[_empty] => Please select at least one grade.
)
)
)
)
But this error is not showing below the input field. Any help will be appreciated.
You are not using the correct naming scheme for the form control, you cannot use [], if you want the form helper magic to work, then you must supply the actual index, ie:
user_grades.0.grade_id
See also Cookbook > Views > Helpers > Form > Creating Inputs for Associated Data

Yii2 images to have checkbox list in the search form

In my yii2 project I want to get checkbox for my images in order to search by images. Whenever the users checks the checkbox and submits the button, it should display the content only with those checked images.
My checkbox list
<?php $img = ArrayHelper::map(app\models\GhsPictogram::find()->all(), 'pictogram_id', 'pictogram_filepath') ?>
<?= $form->field($model, 'ghsPictogram',['template'=>'<div class="ghs-pict"> {label}{input} </div>'])->checkboxList($model->imageList($img)) ?>
My imageList method in my model
public function imageList($filenames) {
$imageList = [];
foreach ($filenames as $key => $value) {
$imageList[$key] = Html::img(
Yii::$app->request->baseUrl . 'web' . $value,
'', array("style"=>"width: 50px")
);
}//foreach $filenames
return $imageList;
}
But In my form it doesn't display the image. It instead displays the image src.
I have attached my output:
Help me find How can I display image in the search form field. Thank you
Checkbox list has an option called encode, which default to true and it encodes (as it says) html that is passed to it.
To solve it, just add 'encode' => true to checkboxList options property, like this:
<?= $form->field($model, 'ghsPictogram',['template'=>'<div class="ghs-pict"> {label}{input} </div>'])->checkboxList($model->imageList($img), [
'encode' => false
]) ?>

How to implement model validation on autocomplete field in yii2?

I am using a jui autocomplete widget in my form. Model validation is not working properly in here.
This is my view
<?php $form = ActiveForm::begin();?>
<div class="members-form">
<div class="col-md-5">
<?php
$data = FamilyName::find()
->select(['name as value', 'name as label','id as id'])
->asArray()
->all();
echo 'Family Name' .'<br>';
echo AutoComplete::widget([
'name' => 'family',
'id' => 'family_name',
'clientOptions' => [
'source' => $data,
// 'minLength'=>'3',
'autoFill'=>true,
'select' => new JsExpression("function( event, ui ) {
$('#members-family_name_id').val(ui.item.id);//#City-state_name is the id of hiddenInput.
}")],
]);
?>
<?= Html::activeHiddenInput($model, 'family_name_id')?>
<?= $form->field($model, 'remarks')->textInput() ?>
<?php ActiveForm::end(); ?>
</div>
</div>
my model code
public function rules()
{
return [
[['family_name_id', 'first_name',
'date_of_birth', 'relation_id', 'is_head','marital_status','remarks',
'gender','address_id'], 'required'],
];
}
Now if i try to create a new member with no data selected in any of the fields, then required fields will show like " ... cannot be blank" in red. But the family_name_id is not showing such validation. The data is not getting saved if leave the auto complete field empty but no validation message is being displayed. How can i show validation messages with jui auto complete ?
I believe you faced the same problem as I had few weeks ago. I experienced similar behavior: I saw autocomplete suggestions and could interact with them, but when I left the input field the client-site validation kept silent.
If you look at the html produced by your view, at the bottom you can see some javascript code, which is responsible for the client-side validation. It looks like:
jQuery(document).ready(function () {
....
jQuery('#app-new-form').yiiActiveForm(
[
{
"id":"application-familyname",
"name":" familyname ",
"container":".field-application-familyname",
"input":"#application-familyname",
"enableAjaxValidation":true,
"validate":function (attribute, value, messages, deferred, $form) {
yii.validation.required(value, messages, {"message":"Field cannot be empty"});
}
}
], []);
.....
});
This code assigns an event handler to your autocomplete field to start the client-side validation. But you have to pay attention, which id is used for the field. Unfortunately, yii2 takes the id provided by you only to construct the <input> element in html. When it produces javascript code the id is always generated from few permanent parts. The most important two are the name of the model and the name of the attribute. In your case id should be something like 'your_modelname -family_name_id'.
Because your explanation is not complete, this is only a guess. So, look at your html source and be sure you have the same id for the input you try to validate and the id in the JavaScript (see above).
You are using Html Hidden Input .. You have to use ActiveForm HiddenInput to show error validation..
use
<?= $form->field($model, 'family_name_id')->hiddenInput()->label(false);>
Why don't you use the family_name_id instead of creating a new select?
<?= $form->field($model, "family_name_id")->dropDownList(
ArrayHelper::map(FamilyName::find()->all(), 'id', 'name'),
['prompt' => 'Select']
) ?>
And you can change the label by using ->label('Family Name'), but i would recommend changing in model (unless you need "Family Name Id" as a label elsewhere).
I know you didn't said anything about that, but can i recommend you to see this answer about using methods that perform sql queries inside your view?

How do I pass a selectbox variable to the View from the Controller in CodeIgniter?

I want to pass a variable (selectbox id, which comes from database) to the view from the controller, but do not know how to do it.
Your original question wasn't that clear, but after reading the comments you could do this.
Controller
//whatever function you're using to populate your original array below.
$data['all'] = $this->model_name->getData();
//then run that data through a foreach loop to populate the dropdown variable.
foreach($data['all'])
{
$data['idDropDown'][$data['all']['id']]=$data['all']['ad'];
}
This will pass an array like: [455]=>Aliağa, [456]=>Balçova to the view as $idDropDown along with your original data as $all
Then in the view just used CI's form dropdown.
echo form_dropdown('id',$idDropDown);
Let's say you have a controller called article and a method index then in your view you will have :
<?php
echo form_open('article/index');
echo form_input('text');
echo form_close;
?>
And in your controller something like:
public function index()
{
if($this->input->post()) {
$this_is_catched_text = $_POST['text'];
}
}
This is without validation and other stuff. Just you get the idea how it works.
In your case it will be like this
$ilce = array(array("id" => 455, "il_id" => 35,"ad" => "Aliağa"),
array("id" => 456, "il_id" => 35, "ad" => "Balçova"));
$options = array();
foreach($ilce as $x) {
$options[$x['id']] = $x['ad'];
}
echo form_dropdown('names', $options);

Resources