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

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);
}
}

Related

Access query fields in mongodb inside forEach

In mongodb, we can use forEach() on find() method for iterating over documents inside the collection . Now the question is can we access the query field inside the forEach . For eg:-
db.mycollection.find({name : 'Mike'}).forEach(function(document) {
// var firstName = name;
})
Can we do something like this or what alternative we can use ? Please help.
You are almost there, try the below code:
db.mycollection.find({name : 'Mike'}).forEach(function(document) {
var firstName = document.name; // Just use the . operator
print(firsName)
// Rest of your operations.
})

not able to pass array from controller to view in cakephp 3 using $this->set('data', array received from find())

Not able to pass array variable form controller to view below code
If, I print in controller it is showing "Undefined variable: data"
public function report(){
$results=$this->Nodals->find()->toArray();
$this->set('data',$results);
print_r($data); die();}
Try using compact like this.
public function report(){
$data=$this->Nodals->find()->toArray();
$this->set(compact('data'));
};
Now do dd in your view to check if the data variable sending to the view. I am assuming your view file is report.ctp, so in report.ctp file write this line
<?php
dd($data);
?>
I hope it will help.
$data is not defined in your code if you want to print the query result from
$this->Nodals->find()->toArray(); then you need to store this in $data variable or any other variable
$results=$this->Nodals->find()->toArray();
$this->set('data',$results);
//data will be sent to the template which wrap the $result and in template you can access $reseult by using $data
print_r($results);
die();
or
$data=$this->Nodals->find()->toArray();
$this->set('data',$data);
print_r($data);
die();

Yii2 - Checkboxlist Value Store In Database

in my db structure
service_request type enum('towel','tissue','napkin')
then have a model
* #property string $service_request
then in my view
<?= $form->field($model, 'service_request')->checkBoxList([ 'towel' => 'Towel', 'tissue' => 'Tissue', 'napkin' => 'Napkin']) ?>
then when i choose towel, tissue and napkin then submit the form, it's have an error said
Service Request must be String
please help me
Thank You
Like Joji Thomas said, checkBoxList prodices an array.
You need to change your database structure so that it supports 1-to-many relations (each $model can have multiple service_requests) if you want to save this. Unfortunately Yii is not very good at this sort of thing out of the box so you have to do a bunch of things yourself.
First you need to create a ServiceRequest ActiveRecord.
Then your $model needs to have a relation like:
public function getServiceRequests() {
return $this->hasMany(ServiceRequest::className(), ['model_id' => 'id'];
}
Then in your controller (model create action) you will need to do something like this:
foreach (Yii::$app->request->post('ServiceRequest',[]) as $data) {
$item = new ServiceRequest($data);
$model->link('serviceRequests', $item);
}
If you wanna update the checkboxes too then you need to do something similar in your model update action as well.
Please change checkBoxList to radioList, because when selecting multiple values service_request becomes an array. Enum type can handle only string values.
First change your filed datatype from enum to varchar. enum only takes a single string value.
Secondly you need to implode service_request array to string for save to db.
Use bellow code before the model save function :
$model->service_request = implode("," , $model->service_request);
$model->save();

Filter globally using yii2 dropdown list

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..

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