get input data in controller yii2? - php

i am trying get input field from a form in yii2. i need to use it in a controller depending on the value. i am trying to see the value using var_dump but it is not working. i am getting "NULL" as the value.. Or is there a way to make a form use different controllers.
controller
public function actionBlog()
{
$thumbs= new Thumbs;
$thumbs->user=Yii::$app->user->identity->email;
$thumbs->topic_id=Yii::$app->getRequest()->getQueryParam('id');
$ra=Yii::$app->request->post('rate');
var_dump($ra);
if(ra=='down'){
if ($thumbs->load(Yii::$app->request->post()) && $thumbs->validate()) {
$thumbs->load($_POST);
$thumbs->save();
return $this->refresh();
}
} else {
return $this->refresh();
}
return $this->render('blog',[
'thumbs' => $thumbs,
]);
}
this is my view
<?php $form = ActiveForm::begin(['id' => "contact-form"
]);
?>
<?= $form->field($thumbs, 'rate')?>
<?= Html::submitButton('Update', ['blog'], ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
i also tired using doing it like this
$rr=Yii::$app->request->post($thumbs)['rate'];
var_dump( $rr);
and i get this error:
Illegal offset type in isset or empty

You have a error in if(ra=='down') condition, '$' is missing.

If I remember right .. you should try
$ra=Yii::$app->request->post(['Thumbs']['rate']);

Related

Yii2 Ajax Validation not validating one field unique

Very weird behavior i found out with yii2 ajax validation i found today.
Basically i was trying to perform ajax validation on 1 field of the form to check that the input is unique and not found anywhere in that field of that table.
If you ask me the following code should work correctly:
In model:
public function scenarios(){
return ['update' => ['username']];
}
public function rules(){
return [['username'], 'unique'];
}
In Controller:
public function actionUpdate(){
$user = User::findmodel.. bla bla
some more bla bla..
if(Yii::$app->request->isAjax){
$user->setScenario('update');
$user_post_ajax = Yii::$app->request->post('User');
$user->username = $user_post_ajax['username'];
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($user);
}
some more bla bla bla..
}
In View:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($user, 'username', ['enableAjaxValidation' => true])->textInput() ?>
<?= Html::submitButton('Save', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
This should work, but it doesn't, it doesn't display the validation errors, in this case something like: 'Username is already taken', it doesn't display neither valid nor invalid. It performs the ajax request, and i can see the json response in the dev tools but it doesn't display at all. But, When you move the $user->setScenario('update'); outside the if condition, above the if(Yii::$app->request->isAjax) only then it works perfectly fine. I don't understand this, am i missing something? Why using setScenario when ajax request changes the behavior?
You're overriding the scenarios() function from the Yii Model, thus not validating any attributes.
Check: https://github.com/yiisoft/yii2/blob/master/framework/base/Model.php#L184
What you should do, is:
public function rules(){
return [['username'], 'unique', 'on'=>['update']];
}

Yii2 rendering view doesn't work correctly

I have 3 tables:
Order
Ordered_number
Number
Ordered_number connects the other two - it has order_id and number_id columns.
In my Index Action, I want to render view named "call", where I have a form with choosing one order. When I submit which order I want, I want to go to actionCall and send there numbers connected with this order. Something isn't correct and I think I may be doing something wrong.
public function actionIndex()
{
$model = new \common\models\Order();
if ($model->load(Yii::$app->request->post())){
$numery = \common\models\Number::find()
->joinWith('ordered_number')
->where(['ordered_number.order_id' => $model->id]);
return $this->redirect(['/call', 'numery' => $numery]);
} else {
$this->render('call', ['model' => $model]);
}
}
When I open my actionIndex it displays a blank page instead of rendering a view that I want.
My "call" view:
<?php
use common\models\Customer;
use common\models\Order;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\web\View;
use yii\widgets\ActiveForm;
/* #var $this View */
/* #var $form ActiveForm */
/* #var $model Order */
var_dump($this);
die();
echo "<h1>Dodaj numery do przedzwonienia</h1>";
echo "Wybierz zamówienie, którego numery chcesz przedzwonić: ";
$form = ActiveForm::begin();
$form->field($model, 'id')->dropDownList(ArrayHelper::map(Customer::find()->all(), 'id', 'id'));
Html::submitButton("Przedzwoń", ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']);
ActiveForm::end();
I added var_dump in my view, and it displays it, but without var_dump and die() command, there is simply blank page without text I want to be next.
Missing return statement in else
return $this->render('call', ['model' => $model]);

Getting unknown property in ActiveQuery Yii 2

Hello I have been getting unknown property error in when I am not using a foreach method of getting the value of the active query instance I need help accessing it without using foreach.
Here is my current code
$status = SiteController::LookupStatus($_user);
<?php if($status->status == 1): //if status == 0?>
<?= HTML::a('<b>REMOVE</b>',
['site/removesubject', 'containerid' => $values['containerid']],
['class' => 'btn-danger btn-transparent' , 'data-method' => 'post']) ?>
<?php else: ?>
<!-- do this -->
<?php endif; ?>
I tried accessing it with $status->status but I am getting the error but when I use the foreach method I am successfully getting it.
Also, here is my active record
public static function LookupStatus($clientid){
return Enrollment::find()->select(['status'])->where([
'clientid' => $clientid,
]);
}
You should specify one(), all() at the end of find() in your model.
public static function LookupStatus($clientid){
$model = Enrollment::find()->select(['status'])
->where(['clientid' => $clientid,])
->one()
return $model->status;
}

Yii2 in a form submission model is null after redirect

Upon form submission, if model is found in controller, a view is rendered with a set flash message but also with a customized message like hello <?= $model->username; ?> when applicable.
Everything worked fine, until I decided I'd be fun to add return $this->refresh(); to prevent form resubmission. Which ultimately throws Trying to get property of non-object in the view as model is righfully null.
As I see, the redirect method prevents the render method from being executed, hence the model variable from being sent to the view.
I'm using POST http method, I guesss I could change to GET if necessary. Have you any idea how to rework this?
CONTROLLER
public function actionIndividualSearch() {
$model = new Order();
$model->scenario = Order::SCENARIO_SEARCH;
if ($model->load($post = Yii::$app->request->post()) && $model->validate()){
//if ($model->load($post = Yii::$app->request->get()) && $model->validate()){
$model = Order::find()->where(['number' => $post['Order']['number']])->one();
$flash = $model ? ($model->status == Order::STATUS_COMPLETED ? 'orderCompleted' : 'orderNotCompleted' ) : 'orderNotFound';
Yii::$app->session->setFlash($flash);
return $this->refresh();
//return $this->redirect(['', 'model'=>$post['Order']['number']]);
}
return $this->render('individualSearch', [
'model' => $model,
]);
}
VIEW
<?php
use yii\widgets\DetailView;
use yii\helpers\Html;
?>
<div class="page-header">
<h1>Consulta tu Orden</h1>
</div>
<p>Por favor introdusca el número de orden impreso en su ticket.</p>
<?php echo $this->render('_search', ['model' => $model]); ?>
<?php if(Yii::$app->session->hasFlash('orderCompleted')): ?>
Hi <?= Html::encode($model->customer->first_name); ?> ...
<?php elseif(Yii::$app->session->hasFlash('orderNotCompleted')): ?>
Hi <?= Html::encode($model->customer->first_name); ?> ...
<?php elseif(Yii::$app->session->hasFlash('orderNotFound')): ?>
Dear Customer...
<?php endif; ?>
After refresh your Order model is empty and $model->customer is null.
And you're trying to get $model->customer->first_name in view.
The answer lied in using session variables, the flash type specifically. This allowed me to preserve variables between requests. Thanks to all involved.

Rendering partial form

Is there any way to render partial view which contains a part of form that it's main part is in another view file with AJAX?
I exactly mean one form variable:
`<?php $form = ActiveForm::begin(['enableAjaxValidation' => true,]); ?>`
For Example :
Controller
public function actionOlddetform()
{
return $this->renderAjax('_olddet');
}
View
<?php $form = ActiveForm::begin(['enableAjaxValidation' => true,]); ?>
<?= $form->field($model, 'date')->input() ?>
<?= $form->field($model, 'annotations')->textarea(['rows' => 3]) ?>
<div id="details-form"></div>
<?php ActiveForm::end(); ?>
Part of form included with AJAX for details-form container depends on date value. I know how to check date and show any content of that partial view but when I want to include a part of form I get an error:
PHP Notice 'yii\base\ErrorException' with message 'Undefined variable: form'
It seems you forgot to actually pass the model into your view:
public function actionOlddetform()
{
return $this->renderAjax('_olddet', ['model' => $dataModel]);
}
And if you want to render "sub-views" from your main view, you need to pass the variables in there as well (even though I don't see a render call in your view):
<?= $this->render('_formPart', ['form' => $form, 'model' => $model]) ?>

Categories