Post inside controller not loading into model in Yii2 - yii

When I want to get the variable from the form the post action doesn't load .
This is my view:
<?php
$form = ActiveForm::begin();
?>
<div class="form-group">
<input type="text" name="username" placeholder="FullName">
<?= Html::a(Yii::t('app', 'Start'), ['start', 'link' => $model->link], ['type' => 'button','class' => 'btn btn-primary btn-round']) ?>
</div>
<?php ActiveForm::end(); ?>
This is my controller:
if ($model->load(Yii::$app->request->post())){
exit(var_dump('everything is ok'));
}else {
exit(var_dump('nothing is right'));
}
The result is 'nothing is right'.

Apart from using the anchor link instead of a submit button, you are not using model to create active input hence the field names are without model names or the standard array format that Yii accepts, you should pass empty string to the load method as second parameter which is formName like below
$model->load(Yii::$app->request->post(),'');
So your complete form should look like
<?php
$form = ActiveForm::begin(
[
'action' => 'start',
]
);
?>
<div class="form-group">
<input type="text" name="username" placeholder="FullName">
<?php echo Html::submitButton(Yii::t('app', 'Start'), ['class' => 'btn btn-primary btn-round']) ?>
</div>
<?php ActiveForm::end();?>
EDIT
and your controller code should look like below, mind the first check it needs to be there so that the code is run when you submit only not on page load
if (Yii::$app->request->isPost) { //this should be here before the rest of the code
if ($model->load(Yii::$app->request->post(), '')) {
exit(var_dump('everything is ok'));
} else {
exit(var_dump('nothing is right'));
}
}

This is because load() method looks for post data inside model name property and you are writing the input yourself instead of using the Yii method for forms.
So your post Yii::$app->request->post() returns:
array(
'username' => 'value of username',
)
And your $model->load looks for
array(
'modelName' => array(
'username' => 'value of username',
)
)
To make your post data too look like that you could do it the right way that is, delete your Input and use this method inside the form:
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
Or the wrong way, modify your input and inside username use:
<input type="text" name="modelName[username]" placeholder="FullName">
Of course where I put username you must put your real model name.

Finally I find the solution
<?php
$form = ActiveForm::begin(
[
'action' => 'start',
]
);
?>
<div class="form-group">
<input type="text" name="username" placeholder="FullName">
<?= Html::a('submit', Url::to(['start', 'link' => $model->link]), ['data-method' => 'POST']) ?>
</div>
<?php ActiveForm::end();?>
thank you for all

Related

Yii2 - Undefined variable in View file

I am trying to pass the variable to view the page through the siteController, however when I try, I always get the error undefined Variable.
Here is my code in the siteController:
public function actionIndex(){
$Opere = Opere::find()->all();
return $this->render('index', [
'titolo' => $titolo, 'tecnica' => $tecnica, 'misura' => $misura, 'anno' => $anno,
'prezzo' => $prezzo, 'note' => $note, 'url_grandi' => $url_grandi]);
}
and here below is the code on the index page:
<?php foreach ($Opere as $o): //var_dump($o); ?>
<div class='grid-item'>
<img src='<?php $url_grandi;?>' class='grid-item-img'/>
<div class='grid-item-overlay'>
<div class='text'>
<div class='innerText'>
Titolo: <?php $titolo;?><br />
Tecnica: <?php $tecnica;?><br />
Misura: <?php $misura;?><br />
Anno: <?php $anno;?><br />
Prezzo: € <?php $prezzo;?><br />
Note: <?php $note;?>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
Thank you in advance
I found the solution, I added the incorrect variable in my foreach loop. I was trying to call the variable $titolo, however, in my foreach loop I had specified that the variable $titolo as $o. This is why it did not recognize the variable $titolo.
The following below is the correct code string to output the db data:
<?= $o->titolo;?>
and not:
<?php echo $titolo;?>
hope this helps someone else with a similar problem.

change value in datepicker on selection of combo value in yii

I have a combo box in a form. According to the selected value from combo ,value of date must be changed in datepicker.How to do this?
code goes like this:
<div class="row col2">
<?php $records = CHtml::listData(CodeValue::model()->findAll(array('order' => 'code_lbl','condition'=>"code_type= 'visit_type'")), 'code_id', 'code_lbl');?>
<?php echo $form->labelEx($model,'visit_type'); ?>
<?php echo $form->dropDownList($model,'visit_type',$records,array('empty' => 'Select Visit Type')); ?>
<?php echo $form->error($model,'visit_type'); ?>
</div>
<div class="row col2">
<?php echo $form->labelEx($model,'next_visited_date'); ?>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker',array(
'model' => $model,
'attribute'=>'next_visited_date',
//'flat'=>true,//remove to hide the datepicker
'options'=>array(
'showAnim'=>'drop',//'slide','fold','slideDown','fadeIn','blind','bounce','clip','drop'
'dateFormat' => 'yy-mm-dd',
'showButtonPanel' => true, // show button panel
),
'htmlOptions'=>array(
'style'=>''
),
));
?>
<?php echo $form->error($model,'next_visited_date'); ?>
</div>
I have to change the visit date according to visit type selected.
You'll have to use ajax for this:
Change your drop down to use ajax, something like:
<?php echo $form->dropDownList($model,'visit_type',$records,array(
'empty' => 'Select Visit Type',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('controller/myAction'),//your controller and action name
'update'=>'#Model_next_visited_date', //replace Model with the model name
'success'=> 'function(data) {
$("#Model_next_visited_date").empty(); //replace Model with the model name
$("#Model_next_visited_date").val(data); //replace Model with the model name
} '
)));
?>
and create a new action:
public function actionMyAction()
{
//you will receive drop down value in $_POST['Model']['visit_type']
// Place your date logic here.....
}
Hope that helps

clear inputed data after ajaxsubmit and updating clistview

in views index.php i have
<?php
$this->widget('zii.widgets.CListView',array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'id'=>"post_list",
));
?>
<div id="addtodo">
<?php $this->renderPartial('ajax_page', array('model' => $model, ));?>
</div>
and in ajax_page.php
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'post-todo',
'enableAjaxValidation'=>false,
)); ?>
<?php
echo $form->textFieldRow(
$model,
'title',
array(
'class' => 'input-medium span6 addtodo',
'placeholder'=>'New todo task',
'prepend' => '<i class="glyphicon glyphicon-plus"></i>',
)
);
?>
<div class="row buttons">
<?php echo CHtml::ajaxSubmitButton ("Post",
CHtml::normalizeUrl(array('todo/add')),
array("success"=>'js:function(data){$.fn.yiiListView.update("post_list",{});}'),
array('class'=>'')
); ?>
</div>
<?php $this->endWidget(); ?>
So, All work fine. but after updating CListview, inputed text keeping in input form .
How to clear input form after updating CListview with Ajax?
You can do this by using the javascript .reset() method. You will need to change your ajax button to this;
<?php echo CHtml::ajaxSubmitButton ("Post",
CHtml::normalizeUrl(array('todo/add')),
array("success"=>'js:function(data){
$.fn.yiiListView.update("post_list",{});
$("#post-todo")[0].reset();
}'),
array('class'=>'')
); ?>

CActiveForm object does not render JS code

I have a simple CFormModel subclass that is used as a form to change a password. The class has only two attributes (password1, password2 - for confirmation -). Here is the code:
class ChangePasswordForm extends CFormModel {
public $password1;
public $password2;
public function rules() {
return array(
array('password1, password2', 'required'),
array('password2', 'compare', 'compareAttribute'=>'password1'),
array('password1, password2', 'safe'),
);
}
public function attributeLabels() {
return array(
'password1' => 'Enter new password',
'password2' => 'Confirm new password',
);
}
}
In a controller view file, I use a CActiveForm object to render this form:
<?php
$form=$this->beginWidget('CActiveForm',
array(
'id'=>'change-pwd-form',
'action'=>array('site/changePasswordPost'),
'enableClientValidation'=>true,
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)
);
echo $form->errorSummary($changePwdForm);
?>
<fieldset><legend>Change your password</legend>
<div class="row">
<?php
echo $form->labelEx($changePwdForm, 'password1');
echo $form->passwordField($changePwdForm, 'password1');
?>
</div>
<div class="row">
<?php
echo $form->labelEx($changePwdForm, 'password2');
echo $form->passwordField($changePwdForm, 'password2');
?>
</div>
<div class="row">
<?php
echo CHtml::submitButton('Change password');
?>
</div>
</fieldset>
<?php
$this->endWidget();
?>
In the controller action, I render the view above, passing a ChangePasswordForm object:
$changePwdForm = new ChangePasswordForm;
$this->render('changePassword', array('userid'=>$userid, 'userType'=>$t,
'changePwdForm'=>$changePwdForm));
Yii::app()->end();
The problem is that while the view is rendered, no Javascript code is generated. Nothing. So clicking on the submit button, although it should not let me do it (since the two password fields are required), it does submit. What is wrong with the code above and no Javascript is created?
Add $form->error() for fields that you need to validate. I suppose you perform ajax validation in controller, if not - search by performAjaxValidation here

Yii framework, uploading files doesn't work

I have a form and I want to upload a file. here is my code:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'show-form',
'enableAjaxValidation'=>false,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
)); ?>
<fieldset>
<legend>DATI TECNICI</legend>
<div class="row">
<?php echo $form->labelEx($model,'tec_data_file'); ?>
<?php echo $form->fileField($model,'tec_data_file',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'tec_data_file'); ?>
</div>
</fieldset>
<?php $this->endWidget(); ?>
</div><!-- form -->
There was nothing added to the database after submitting, I did a bit of debuging with firebug and figured out that filefield generates a code like this:
<input id="ytShow_tec_data_file" type="hidden" name="Show[tec_data_file]" value="">
<input id="Show_tec_data_file" type="file" name="Show[tec_data_file]" maxlength="45" size="45">
and two data are sent by $_POST for tec_data_file (which is my file field in db). The first var is empty (I think it is related to first hidden input). and the second one contains my file. and when I'm assigning the variables to my model for saving:
$modelPhoto->attributes = $_POST['Photo'];
the tec_data_file gets an empty string! So nothing gets uploaded to my db. Anyone have an idea how to solve this? If you need more i
You need something like:
$model = new Photo;
$model->attributes = $_POST['Photo'];
$model->image = CUploadedFile::getInstance($model,'file');
where file is the name of the field.
I haven't tested this, it's from the documentation.