I have created datetime field in mysql. I want to store it in the db when i pick the date by using datepicker.
This is my part of code in controller
public function actionCreate()
{
$model=new EmpDetails;
$model->created = date("Y-m-d H:i");
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['EmpDetails']))
{
$model->attributes=$_POST['EmpDetails'];
if($model->save())
$this->redirect(array('view ','id'=>$model->emp_id));
}
$this->render('create',array(
'model'=>$model,
));
}
The part of my form.php is:
<div class="row">
<?php echo $form->labelEx($model,'dateof_leave'); ?>
<?php $model->created=new CDbExpression('NOW()');
$sqldate = date('Y-m-d H:i:s',strtotime($textFieldValue));?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'model' => $model,
'attribute' => 'dateof_leave',
'htmlOptions' => array(
'size' => '10', // textField size
'maxlength' => '10', // textField maxlength
),
));
?>
<?php // echo $form->textField($model,'dateof_leave'); ?>
<?php echo $form->error($model,'dateof_leave'); ?>
</div>
am facing the error Property "EmpLeave.created" is not defined.
Please clarify my doubts and explain me how can i overcome this issue?
Replace
$model->created=new CDbExpression('NOW()');
On
$model->created=date("Y-m-d H:i:s");
Because CJuiDatePicker needs string on input.
In yout Controller you add line
$model->created = date("Y-m-d H:i");
In your _form.php you add input form for dateof_leave. So when posting form the $model->created is EMPTY. If i am understand right In controller u must add
$var= $_POST['EmpDetails']['dateof_leave'];
$model->created = date("Y-m-d H:i", $var);
Related
I am working on a project in yii2. I need to place an input field on the index page. This field should be similar to the form field. i.e. the type of the field that is used in the form while creating a record. For this, I have done the following
public function actionIndex()
{
$model = MdcmetercustRel::className();// this is the class whose data field I want to get
$searchModel = new MdcmetersdataSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
My index
<?=
$form = ActiveForm::begin();
$relModel=$model->getModels()[0]; print_r($relModel['cust_id']);
$form->field($relModel, 'cust_id')->textInput()
?>
When I refresh my page I am getting
Object of class yii\widgets\ActiveForm could not be converted to string
How can I achieve this?
Any help would be highly appreciated
Your mistake is <?=which is trying to output the whole script and you cant echo $form or ActiveForm::begin()
change it to
<?php
$form = ActiveForm::begin();
$relModel=$model->getModels()[0]; print_r($relModel['cust_id']);
echo $form->field($relModel, 'cust_id')->textInput()
?>
Also you need to change the
$model = MdcmetercustRel::className();
to
$model = new MdcmetercustRel();
otherwise there wont be an object in $model but a string i.e class namespace.
Previously, when I set enableAjaxValidation to false on my ActiveForm , the file validation worked so well ,but after I set enabledAjaxValidation to true in order to check unique slug, it doesn't work.
Here is what I've done
Form:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data'] , 'enableAjaxValidation' => true,'id' => 'article-form']); ?>
Model rule:
[['slug'], 'unique'],
[['featureFile' , 'bannerFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg' , 'on' => 'create'],
Controller:
use yii\web\Response; //Ajax Validation
use yii\widgets\ActiveForm; //Ajax Validation
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
{
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
Even though I choose the image file already but it still show validation error
Please help!!!
You can disable the ajax validation of the specified field.
Try
<?= $form->field($model, 'featureFile', ['enableAjaxValidation' => false])->fileInput() ?>
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 want to show selected value in Yii2 dropdown,
$_GET Value:
$id = $_GET["cid"];
Drop down code
$form->field($model, 'userid')
->dropDownList(
[User::getUser()],
//[ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name')],
['prompt'=>'Select a user','id'=>'user_dropdown'],
['options' =>
[
$id => ['selected' => true]
]
]
)->label('');
but this method is not working!
Try this.
$model->userid=$id;
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Basically, you affect the options (your <option> elements) by using the value attribute's actual value as the array key in the dropDownList options array.
So in this case I have an array of states and the value attributes have the state abbreviation, for example value="FL". I'm getting my selected state from the Address table, which stores the abbreviation, so all I have to do is use that as my array key in the options array:
echo $form->field($model, 'state')->dropDownList($listData, ['prompt'=>'Select...', 'options'=>[$address->state=>["Selected"=>true]]]);
The documentation spells it out: http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#dropDownList()-detail
i hope this will help you
$form->field($model, 'userid')
->dropDownList(
[User::getUser()],
//[ArrayHelper::map(User::find()->where('id' => $id)->all(), 'id', 'name')],
['prompt'=>'Select a user','id'=>'user_dropdown'],
['options' =>
[
$id => ['selected' => true]
]
]
)->label('');
$model->userid = $_GET['cid'];
$form->field($model, 'userid')
->dropDownList(
$items, //Flat array('id'=>'val')
['prompt'=>''] //options
)->label('');
<?php
$selectValue = $_GET['tid']
echo $form->field($model, 'tag_id')
->dropdownList(
ArrayHelper::map(Tag::find()->where(['visibility'=>'1'])->orderBy('value ASC')->all(), 'tag_id', 'value'),
['options' => [$selectValue => ['Selected'=>'selected']]],
['prompt' => '-- Select Tag --'])
->label(false);
?>
This code will Auto Select the selected value received as input.
Where $selectValue will be numeric value received from GET method.
Final output : <option value="14" selected="selected">NONE</option>
Ok, if you are using ActiveForm then value of your model field will be used as the selected value. With Html helper dropDownList function accepts another parameter selection doc. Example:
$id = $_GET["cid"];
\yii\helpers\Html::dropDownList('userid', $id, [ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name'), [......])
This is my S.O.L.I.D approach.
Controller
$model = new User();
$model->userid = $id; #this line does the magick. Make sure the $id has a value, so do the if else here.
return $this->return('view', compact('model'))
But, if you prefer the setter method. Do this...
# Model
class User extends ActiveRecord
{
public function setUserId(int $userId): void
{
$this->userid = $userId;
}
}
# Controller
$model = new User();
$model->setUserId($userId);
View (view is as-is)
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Use this code below:
$category = \backend\models\ProductCategory::find()->WHERE(['deleted'=>'N'])->all();
$listData = ArrayHelper::map($category,'product_category_id','category_name');
echo $form->field($model, 'product_category_id')->dropDownList($listData,['prompt'=>'Select']);
All of the options I've added are unrequired.
What is written in the 'value' index is what dropdown item will be selected as default.
Prompt just displays a first option that doesn't have a value associated with it.
echo $form->field($model, 'model_attribute_name')
->dropDownList($associativeArrayValueToText,
[
'value'=> $valueIWantSelected,
'prompt' => 'What I want as a placeholder for first option',
'class' => 'classname'
]);
You'll find the function that assigns this in the following file:
vendor/yiisoft/yii2/helpers/BaseHtml.php
public static function renderSelectOptions($selection, $items, &$tagOptions = [])
Also from the function you can see that you can add an optgroup to your dropdown, you just need to supply a multidimensional array in where I've put $associativeArrayValueToText. This just means that you can split your options by introducing group headings to the dropdown.
I am trying to create a form "Movie" as follows and my database accepts movie_id, title, year, and description. When I run the code it tries to store the "array" as the year input. This is the error I get => movie_id, title, year, description) VALUES (NULL, 'Movie1', Array, 'some text')
THE VIEW:
<?php
echo $this->Form->create('Movie'); ?>
<?php echo __('Add Movie'); ?>
<?php
echo $this->Form->hidden('movie_id');
echo $this->Form->input('title');
echo $this->Form->input('year', array(
'type'=>'date',
'dateFormat'=>'Y',
'minYear'=>'1990',
'maxYear'=>date('Y'),
));
echo $this->Form->input('description');
?>
<?php echo $this->Form->end(__('Submit'));
?>
THE CONTROLLER:
public function add() {
if ($this->request->is('post')) {
$this->Movie->create();
if ($this->Movie->save($this->request->data)) {
$this->Session->setFlash(__('The movie has been created'));
$this->redirect (array('action'=>'index'));
}
else {
$this->Session->setFlash(__('The movie could not be created. Please, try again.'));
}
}
}
I believe your problem is here:
$this->Form->input('year', array(
'type'=>'date',
'dateFormat'=>'Y',
'minYear'=>'1990',
'maxYear'=>date('Y'),
));
Instead of it you should use
$this->Form->input('Movie.year', array(
'type'=>'text',
'name' => 'data[Movie][year]',
));
If you don't want to use 'text' type input, then use 'select' with your options array. Here main concern is, Movie.year and overwrite the default CakePHP's naming procedure to 'name' => 'data[Movie][year]'. Check here.
The best thing to do is to debug your $this->request->data.
I'm not sure myself, but I once have this problem. What happen is, when you define an input as a date, it will be behave as an array.
It will become $this->request->data['Movie']['year']['year'];
You can modify the data by doing the following
$this->request->data['Movie']['year'] = $this->request->data['Movie']['year']['year'];