Filter globally using yii2 dropdown list - yii2

I have my drop down list which displays the data from the model, but when I select them it doesn't filter the data accordingly.
<?php $items = ArrayHelper::map(app\models\Facility::find()->all(),'facility_id' ,'facility_country');?>
<?= $form->field($model, 'facility_country')->dropDownList($items)->label(false); ?>
The above mentioned is the drop-down list in the search form.In the filterSearch model I have used my query like the below mentioned code.
$query->orFilterWhere(['like', 'facility_name', $this->facility_name])
->orFilterWhere(['like', 'facility_country', $this->facility_country]);
Can I know what the issue is? Thank you!!

The value of your $items variable are coming from your \app\models\Facility class, in an array with the following format:
[
'facility_id' => 'facility_country',
...
]
When you use this array with dropDownList(), you are saying you are sending the key 'facility_id' to your form.
So, in your search model, you need to search by id, something like:
->orFilterWhere(['like', 'facility_id', $this->facility_country]);
OR you could also do your search by name (I guess that's what you want):
$items = ArrayHelper::map(app\models\Facility::find()->all(),'facility_country' ,'facility_country');

Solution was really simple.. The issue was it was not submitting the form which was just doing nothing.
I was not just submitting the form just added onchange event as the code below.
<?php $items = ArrayHelper::map(app\models\Facility::find()->all(),'facility_country' ,'facility_country');?>
<?= $form->field($model, 'facility_country')->dropDownList($items,['class'=> 'col-sm-2 col-lg-2 col-xs-7 pull-left', 'style'=> 'height:34px;','onchange' => 'this.form.submit()'])->label(false);?>
Thanks guys for your help..

Related

Yii2 Display Related Data not in Array, not using Listview or Gridview

I have a main view called Dashboard.php in which I want to display a logged in employee's cell phone (from the employee_phone table which stores all employee phone numbers and are differentiated by 'phone_type' (ie cell, home, main)) in an arbitrary field labeled as 'phone 1:' on the view, then display either their 'home' or 'main' number as 'phone 2:'. Please note, for clarity I left out the 'home' phone provider as I'm sure I can figure it out if someone can help with the 'cell' phone type. I cannot get any phone number to display and I've tried several configurations. Any help is appreciated and I apologize in advance for my newness. I've read this page: http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#querying-data and it seems like it fits my criteria but I just can't make it work. I've also read the related questions here on SO but they seem related to working with data in an array and displaying it in a ListView or Gridview. I also don't seem to be able to get the provider to be able to access the method getEmployeeCellPhone() with the magic method of employeeCellPhone.
I have two tables:
employee Table:
id
user_id
employee_phone Table:
id
employee_id
phone_number
phone_type
Employee.php Model:
public function getEmployeePhones()
{
return $this->hasMany(\frontend\models\EmployeePhone::className(), ['employee_id' => 'id']);
}
public function getEmployeeCellPhone()
{
return $this->hasOne(\frontend\models\EmployeePhone::className(), ['employee_id' => 'id'])
->where(['=', 'phone_type', 'Cell'])
->all();
}
EmployeeController:
public function actionDashboard($id)
{
$model = $this->findModel($id);
$providerCellPhone = $model->employeeCellPhone;
return $this->render('dashboard', [
'model' => $this->findModel($id),
'providerCellPhone' => $providerCellPhone,
]);
}
Dashboard.php View:
<div class="col-lg-3">
Phone 1: <?= $model->$providerCellPhone ?><br>
Phone 2: <?= $model->$providerHomePhone ?>
</div>
Please try the following to check if your issue is solved -
//EmployeeController
public function actionDashboard($id)
{
$model = $this->findModel($id);
return $this->render('dashboard', [
'model' => $model,
]);
}
And the view file -
//Dashboard.php View
<div class="col-lg-3">
Phone 1: <?= $model->employeeCellPhone[0]->phone_number ?><br>
Phone 2: <?= $model->employeeHomePhone[0]->phone_number ?>
</div>
To properly output the value $model->employeeCellPhone[0] is required because in your getEmployeeCellPhone() function, you have used the ->all() function. The Dashboard code is written assuming that in DB only one phone number will exist per user per phone_type. If that is not the case, you need to loop over $model->employeeCellPhone in the view and get the desired output.
Also, your Model code pasted above, doesn't show the getEmployeeHomePhone() function, I am assuming you have it there.

Kartik DepDrop at update form not working in Yii2

For example, we have an update form with the fields
<?= $form->field($model, 'company_name')->dropDownList($data,
['prompt' => 'Select Company Name..', 'id' => 'cat-id']
) ?>
<?php
echo $form->field($model, 'employee_name')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'initialize' => true,
'depends'=>['cat-id'],
'placeholder'=>'Select...',
'url'=>yii\helpers\Url::to(['claim/subcat'])
]
]);
?>
A value of depended dropdown is not set when the first dropdown has a value ($cat-id). It shows placeholder "Choose a model" instead of list of models for current manufacturer. The same happens, when depended dropdown also have a value ($model->model_id). It is not showed. Only placeholder "Choose a model" is showed
You must do one of the following for update:
Option 1: Set data property array for dependent dropdown to have a preset dependent list on init.
Option 2: Set pluginOptions['initialize'] property to true for dependent dropdown. This will run the ajax calls on init to generate the dropdown list.

How to implode an array to show it in a textbox in yii2 ActiveForm?

Children field is an array in mongoDB:
<?= $form->field($model, 'children') ?>
The error I get is:
Array to string conversion
I need to use implode(',', $model->children) somehow, how to use it in an ActiveForm? What to do now?
What is the solution? How to turn that array into a string?
The content of the $model->children attribute is displayed when being used in a $form->field() call. If the content of the attribute is an array and you want/need it to be a string you'll have to convert the content before the field() call.
So like this, it will probably work.
<?php
$model->children = implode(',', $model->children);
echo $form->field($model, 'children');
?>
Not sure editing a list value like this (in a textfield) is the best way. You'll have to explode the string back when saving. But the code above is the solution to turn that array into a string.
As I wanted to turn it into string in every widget, grid view and so I used afterFind() function in my model in order to convert it into string. Now everything seems awesome:
public function afterFind() {
parent::afterFind();
if (is_array($this->children)) {
$this->children = implode(',', $this->children);
}
}

yii2 hidden input value

In Yii2 I'm trying to construct hidden input
echo $form->field($model, 'hidden1')->hiddenInput()->label(false);
But I also need it to have some value option, how can I do that ?
Use the following:
echo $form->field($model, 'hidden1')->hiddenInput(['value'=> $value])->label(false);
Changing the value here doesn't make sense, because it's active field. It means value will be synchronized with the model value.
Just change the value of $model->hidden1 to change it. Or it will be changed after receiving data from user after submitting form.
With using non-active hidden input it will be like that:
use yii\helpers\Html;
...
echo Html::hiddenInput('name', $value);
But the latter is more suitable for using outside of model.
simple you can write:
<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'abc value'])->label(false); ?>
You can do it with the options
echo $form->field($model, 'hidden1',
['options' => ['value'=> 'your value'] ])->hiddenInput()->label(false);
you can also do this
$model->hidden1 = 'your value';// better put it on controller
$form->field($model, 'hidden1')->hiddenInput()->label(false);
this is a better option if you set value on controller
$model = new SomeModelName();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->group_id]);
} else {
$model->hidden1 = 'your value';
return $this->render('create', [
'model' => $model,
]);
}
Like This:
<?= $form->field($model, 'hidden')->hiddenInput(['class' => 'form-control', 'maxlength' => true,])->label(false) ?>
You can use this code line in view(form)
<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'your_value'])->label(false) ?>
Please refere this as example
If your need to pass currant date and time as hidden input :
Model attribute is 'created_on' and its value is retrieve from date('Y-m-d H:i:s') ,
just like:"2020-03-10 09:00:00"
<?= $form->field($model, 'created_on')->hiddenInput(['value'=>date('Y-m-d H:i:s')])->label(false) ?>
<?= $form->field($model, 'hidden_Input')->hiddenInput(['id'=>'hidden_Input','class'=>'form-control','value'=>$token_name])->label(false)?>
or
<input type="hidden" name="test" value="1" />
Use This.
You see, the main question while using hidden input is what kind of data you want to pass?
I will assume that you are trying to pass the user ID.
Which is not a really good idea to pass it here because field() method will generate input
and the value will be shown to user as we can't hide html from the users browser. This if you really care about security of your website.
please check this link, and you will see that it's impossible to hide value attribute from users to see.
so what to do then?
See, this is the core of OOP in PHP.
and I quote from Matt Zandstr in his great book PHP Objects, Patterns, and Practice fifth edition
I am still stuck with a great deal of unwanted flexibility, though. I rely on the client coder to change a ShopProduct object’s properties from their default values. This is problematic in two ways. First, it takes five lines to properly initialize a ShopProduct object, and no coder will thank you for that. Second, I have no way of ensuring that any of the properties are set when a ShopProduct object is initialized. What I need is a method that is called automatically when an object is instantiated from a class.
Please check this example of using __construct() method which is mentioned in his book too.
class ShopProduct {
public $title;
public $producerMainName;
public $producerFirstName;
public $price = 0;
public function __construct($title,$firstName,$mainName,$price) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
}
And you can simply do this magic.
$product1 = new ShopProduct("My Antonia","Willa","Cather",5.99 );
print "author: {$product1->getProducer()}\n";
This produces the following:
author: Willa Cather
In your case it will be something semilar to this, every time you create an object just pass the user ID to the user_id property, and save yourself a lot of coding.
Class Car {
private $user_id;
//.. your properties
public function __construct($title,$firstName,$mainName,$price){
$this->user_id = \Yii::$app->user->id;
//..Your magic
}
}
I know it is old post but sometimes HTML is ok :
<input id="model-field" name="Model[field]" type="hidden" value="<?= $model->field ?>">
Please take care
id : lower caps with a - and not a _
name : 1st letter in caps

How to retrive Custom Post Type Meta Fields in Custom WP_Query

Can some one let me know How I can render the Custom Post Type Meta Fields (Meta-boxes).
I have a Custom Post Type Called "News" and I successfully added a metabox to my Custom Post Type called "News Info" which is suppose to store : A TextField = News Resource A Select option = News Type A check box
I can retrieve the Custom post Type "News"content using a custom Loop as:
<?php
$args = array( 'post_type' => 'news');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="content">';
the_content();
echo '</div>';
endwhile;
?>
But I have no idea how to get the associated meta fields to "news" posts? trust me I Google this a lot but couldn't find any solution all of them just tried to render the Metabox on the admin page but no sample for presenting on the page!
Can you please let me know how I can get access and render the data on the page using the wp-query loop?
Thanks
To build upon SidGBF's answer, you can use get_post_meta(get_the_ID(),'YOUR_FIELD_NAME',true);
That is a little verbose if you're going to use it again and again, so it might be helpful to add this to your functions.php file:
function get_custom_field($field_name){
return get_post_meta(get_the_ID(),$field_name,true);
}
Then you can just use get_custom_field('YOUR_FIELD_NAME').
If you'd like to print the value of the field, use echo get_custom_field('YOUR_FIELD_NAME')
Your solution may be found in http://codex.wordpress.org/Function_Reference/get_post_meta . To get the post's ID you may use get_the_ID().