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
Related
In a projects/create active form I have a field "related company account" as a dropdown (select2 by kartik). Behind this field I'd like to place a plus sign or something else to add new accounts to the dropdown with the following behavior:
gather all input done so far (like $input = compact(array_keys(get_defined_vars())); but probably needed on client side)
jump to accounts/create and pass $input
after submiting the new account jump back to projects/create (e.g. return $this->redirect(Yii::$app->request->referrer);) and fill the previously entered data (extract($input, EXTR_PREFIX_SAME, "arr");)
I'm struggling now with several issues:
Is this process according to best practice or should I change something fundamentally?
How is the button like? Submit button, link or some form of javascript?
Problem with Submit button is that not all required fields may be filled. So saving and resuming/updating the project model might not be possible.
Problem with link is that it is constructed before data was entered
Problem with javascript is that I have no glue
Any hints are welcome. Thank you in advance.
One alternative i would suggest is using Session.
As for the "Add Accounts" button, i would use Submit button, and give different name to actual Submit button (two submit button in form, as answered in here). So, the projects/create view will look like this :
<?php $form = ActiveForm::begin(); ?>
...
...
...
<?= $form->field($model, 'account_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Account::find()->all(), "id", "name"),
'options' => ['placeholder' => 'Select a related company account ...'],
'pluginOptions' => [
'allowClear' => true
],
]) ?>
<?= Html::submitButton('Add Account ;)', ['class' => 'btn btn-success', 'name' => 'add_account_submit']) ?>
...
...
...
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
And then check in ProjectsController, which submit button pressed by user. If add account was pressed, then save the inputed field (i would put this function in model for clearance), else, save the model or anything. And, before all that, check if session about project is set, if yes then pre-load it to model (again, in model). Okay, like they say, one code is worth a thousand words, so, this is ProjectsController will look like :
class ProjectsController extends Controller
{
...
...
...
public function actionCreate($category)
{
$model = new Projects();
if (Projects::isSavedInSession()) {
$model->loadFromSession();
}
if (Yii::$app->request->post('add_account_submit')) { // if add_account_submit is clicked
$model->saveTosession(Yii::$app->request->post('Projects')); // I assume your model named Projects, if not, change this value to your model name
return $this->redirect(['accounts/create']);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->clearSession(); // we dont need the session anymore
return $this->redirect(['index');
}
return $this->render('create', [
'model' => $model,
]);
}
...
...
...
}
And Projects model will look like :
class Projects extends \yii\db\ActiveRecord
{
...
...
...
public static function isSavedInSession() { // why this is static is beyond this question context
if (Yii::$app->session->get('projects')) return true;
return false;
}
public function loadFromSession() {
if (Yii::$app->session->get('projects_name')) $this->name = if (Yii::$app->session->get('projects_name'));
if (Yii::$app->session->get('projects_account_id')) $this->account_id = if (Yii::$app->session->get('projects_account_id'));
...
... // insert all model's field here
...
}
public function saveToSession($fields) {
Yii::$app->session->set('projects', 1);
foreach ($fields as $field=>$value) {
Yii::$app->session->set('projects_' . $field, $value);
}
}
public function clearSession() {
Yii::$app->session->remove('projects'));
Yii::$app->session->remove('projects_name'));
Yii::$app->session->remove('projects_account_id'));
...
... // insert all model's field here
...
}
...
...
...
}
And in the AccountsController, just tell the program to jump back to projects/create if projects session is set, like so :
class AccountsController extends Controller
{
...
...
...
public function actionCreate($category)
{
$model = new Accounts();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if (Projects::isSavedInSession()) {
return $this->redirect(['projects/create');
}
return $this->redirect(['index');
}
return $this->render('create', [
'model' => $model,
]);
}
...
...
...
}
Well, it's looks bit lengthy, but yeah, it's worth trying. Anyway, you could use this approach for another purpose, save current form state for example.
Oh, one more thing, i haven't tested this in real code, so if any error exposed on my code, hit me up in comment.
Happy coding. :)
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..
I want to get value of field in controller.
could you please help me?
here is my form code:
<?php
$form = ActiveForm::begin([
'id' => 'request-form',
'action' => 'site/request_page',
'method' => 'post',
'fieldConfig' => ['autoPlaceholder' => false]
]);
?>
<?= $form->field($model, 'workroom_id')->label(FALSE) ?>
and this is my controller code:
public function actionRequest_page() {
echo Yii::$app->request->post('workroom_id');
die();
}
But I got nothing in result.
write workroom_id in safe rule like this-
public function rules()
{
return [
[['workroom_id'],'safe']
];
}
Use bellow code -
echo Yii::$app->request->post('MODEL_NAME')['workroom_id'];
You should expand your action form-attribute. By using Url::to() for instance. As in echo \yii\helpers\Url::to(['site/request_page']);
And access your post data differently. Try var_dump(Yii::$app->request->post()); to see what your form data looks like. The other answer shows how to access it correctly.
The docs have an excellent starting place for working with forms.
I have a model "Product" that I would like to modify or "mutate" one of its attributes for, but only in specific instances.
I store attribute, price as an integer. So $1.99 gets stored as 199.
I would like to incorporate this with the activeForm in such a way that when getting the price it converts to "1.99" in the field (visually). But when I submit the form, before validation, it modifies the price from "1.99" to "199".
I'm assuming this will require Behaviors, and specifically attaching a behavior to the model before creating the active form. However, I'm still confused on how to set this up. I see there is an AttributeBehavior class or I can make my own Behavior class, but I've been having trouble figuring out implementation in this case.
The situation:
foreach ($store_item->storeProducts as $i=>$product) {
?>
<tr>
<td>
<?= $form->field($product, '['.$i.']price')->label(false); ?>
</td>
</tr>
<?php
$i++;
}
?>
Here is a scenario where I check for empty attribute and assign value before saving. Note owner returns the Model so that you can access model attributes and functions that are public. Let me know if I can explain anything further
public function behaviors()
{
return [
[
'class' => AttributeBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'yourAttrib',
],
'value' => function ($event) {
$code = "N/A";
if(!empty($this->owner->yourAttrib))
{
$code = $this->owner->yourAttrib; //here change your attribute accordingly
}
return $code;
},
],
//other behaviors
];
}
You could simply use a getter/setter, e.g. :
public function getRealPrice()
{
return $this->price/100;
}
public function setRealPrice($value)
{
$this->price = $value*100;
}
And don't forget to :
add realPrice in your model's rules,
use realPrice in your form (instead of price).
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);
}
}