yii2: js calulation in server side - yii2

This is a page for calculate the product order.
My mentor told me that:
"The code put the code calculation logic inside JavaScript which means, user can simply inject and modified the content and get discount to make it safe, may either do a recalculation on submit at server side before display, or make the js function to call API, and return the result instead of put calculation logic inside JS"
But I really can't get it, how can I make it in server side?
views:
<?php $form = ActiveForm::begin([
'action'=>['summary'],
'id'=>'order-form',
]); ?>
<?= Html::dropDownList('country', null,['malaysia'=>'Malaysia','singapore'=>'Singapore', 'brunei'=>'Brunei'],['id'=>'country']) ?>
<?= Html::textInput('code','',['class'=>'form-control','placeholder'=>'promotion code','id'=>'code', 'style'=>'text-transform:uppercase'])?>
<?= Html::button('Apply', ['class' => 'btn btn-primary', 'id'=>'apply']) ?>
<?= Html::hiddenInput('id', $model->id) ?>
<?= Html::hiddenInput('discount', '', ['id'=>'discount']) ?>
<?= Html::hiddenInput('ship','',['id'=>'ship']) ?>
<?= Html::hiddenInput('qty', $qty, ['id'=>'qty']) ?>
<?= Html::hiddenInput('subtotal', $subtotal, ['id'=>'subtotal']) ?>
<?= Html::submitButton('Checkout', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
js:
$(document).ready(function() {
var qty=$('#qty').val();
var subtotal=$('#subtotal').val();
$('#discount').val(0);
$("#apply").click(function() {
var code=$('#code').val().toUpperCase();
var off5=(subtotal*0.05).toFixed(2);
var off15=15;
if(code=='OFF5PC'){
if (qty>=2)
$('#discount').val(off5);
else{
$('#discount').val(0);
alert('At least 2 quantities');
}
}
else if(code=='GIVEME15'){
if(subtotal>=100)
$('#discount').val(off15);
else{
$('#discount').val(0);
alert('Minumum puchase of RM100');
}
}
else{
$('#discount').val(0);
alert('Invalid promotion code');
}
if ($('#discount').val()=='0'){
$('#code').val('');
}
});
if(qty>=2||subtotal>=150){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(10);
$('#shipping').html('10');
}
$("#country").change(function() {
var country=$('#country').val();
if(country=='malaysia'){
if(qty>=2||subtotal>=150){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(10);
$('#shipping').html('10');
}
}
else if(country=='singapore'){
if(subtotal>=300){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(20);
$('#shipping').html('20');
}
}
else if(country=='brunei') {
if(subtotal>=300){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(25);
$('#shipping').html('25');
}
}
});
});
controllers:
public function actionSummary()
{
$id=Yii::$app->request->post('id');
$qty=Yii::$app->request->post('qty');
$discount=Yii::$app->request->post('discount');
$shipping=Yii::$app->request->post('ship');
$subtotal=Yii::$app->request->post('subtotal');
$area=Yii::$app->request->post('country');
$code=Yii::$app->request->post('code');
$summary=Products::findOne($id);
return $this->render('summary', [
'model' => $summary,
'quantity'=>$qty,
'discount'=>$discount,
'shipping'=>$shipping,
'subtotal'=>$subtotal,
'area'=>$area,
'code'=>$code,
]);
}

use browser tools inspect to determine your id of each fields. Usually the default id in Yii2 begins with view_name combine with "-" and field name.

For validating the form onsubmit, you can enable ajaxvalidation in your form like below.
View:
<?php $form = ActiveForm::begin([
'action'=>['summary'],
'enableAjaxValidation' => true,
'id'=>'order-form',
]); ?>
<?= $form->field($model, 'country')->dropDownList(['malaysia'=>'Malaysia','singapore'=>'Singapore', 'brunei'=>'Brunei']) ?>
<?= $form->field($model, 'code', ['options' => ['class' => 'form-control', 'id'=>'code']])->textInput(['placeholder'=>'promotion code'])?>
<?= Html::button('Apply', ['class' => 'btn btn-primary', 'id'=>'apply']) ?>
<?= Html::hiddenInput('id', $model->id) ?>
<?= Html::hiddenInput('discount', '', ['id'=>'discount']) ?>
<?= Html::hiddenInput('ship','',['id'=>'ship']) ?>
<?= Html::hiddenInput('qty', $qty, ['id'=>'qty']) ?>
<?= Html::hiddenInput('subtotal', $subtotal, ['id'=>'subtotal']) ?>
<?= Html::submitButton('Checkout', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
In your controller file, please add the ajax validation code in your controller before inserting into database. Below is the example ajax validation code for validating from server side.
Controller:
public function actionYourActionName(){
$model = new YourModelClass();
if ($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if($model->save())){
//after successful save if you want to do any thing those codes will goes here.
}
}
return $this->render('your-view-file-name', ['model' => $model]);
}
Model:
<?php
namespace app\models;
use yii;
use yii\db\ActiveRecord;
class YourModelClass extends ActiveRecord
{
...
public function rules(){
return [
[['id', 'discount', 'ship', 'qty', 'subtotal'], 'safe'],
[['country', 'code'], 'required']
];
...
}
?>

Related

Yii2 update a record based on form in a view file

I tried to update one field of record based on value in a form. The form are placed within a modal in a view file.
view
Modal::begin([
'header' => '<h3>Update Payment Reference</h3>',
'toggleButton' => ['label' => 'Pay','class' => 'btn btn-success'],
]); ?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'pcpayreference')->textInput(['maxlength' => true]) ?>
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php Modal::end();
But I have no idea how to pass those value to my controller so it can update whatever the user have input and submitted.
Controller
public function actionPay($id)
{
$model = Purchase::findOne($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->pcstatus = 'Paid';
$model->pcpaydate = date('Y-m-d H:i:s');
$model->save();
return $this->redirect(['view', 'id' => $model->pcid]);
}
}
I'm new to Yii framework. Any help is much appreciated.
EDIT
The only thing I want to do is to update only this field (current record/view) into database instead of update the whole field.
You must set action in your form with id, it will work
Modal::begin([
'header' => '<h3>Update Payment Reference</h3>',
'toggleButton' => ['label' => 'Pay','class' => 'btn btn-success'],
]); ?>
<?php $form = ActiveForm::begin([
'action' => ['controller/pay','id'=>$id],
]); ?>
<?= $form->field($model, 'pcpayreference')->textInput(['maxlength' => true]) ?>
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php Modal::end();
I think this is the problem regarding csrf validation, just make sure in your config about enableCsrfValidation :
just put this function in your controller
public function beforeAction($action) {
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
Let me know please.

yii2 file upload error- Call to a member function saveAs() on null

I've learned a little bit about yii2 framework, but I've got an error which I can't solve. I'm trying to add a image to signup form.
view:
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'voornaam')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'bedrijf') ?>
<?= $form->field($model, 'telefoon') ?>
<?= $form->field($model, 'username')?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
controller
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
model:
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$imageName = $user->username;
$user->file = UploadedFile::getInstance($user,'file');
$user->file->saveAs( 'uploads/'.$imageName.'.'.$model->file->extension );
$user->picture = 'uploads/'.$imageName.'.'.$model->file->extension;
$user->voornaam = $this->voornaam;
$user->bedrijf = $this->bedrijf;
$user->telefoon = $this->telefoon;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
}
I'm getting the error:
Call to a member function saveAs() on null
What did I do wrong?
(I'm using the advanced template).
you should use $this instead of $user or you should add
$user=$this
because simply $user is new instance and it's field are empty !
It looks like you are mentioning wrong file path, you must mention rootpath for save function
for example
$user->file->saveAs(\Yii::getAlias('#webroot').'/uploads/'.$imageName.'.'.$model->file->extension );
I used separate upload function to upload a file and it's worked.
my view
<?php $form = ActiveForm::begin(['id' => 'form-signup','options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, "files")->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
controller
public function actionSignup() {
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
$model->files = \yii\web\UploadedFile::getInstance($model,'files');
if ($model->upload() && $user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
and my model is
//declare variable
public $files;
//add this to your rules
[['files'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg']
//File upload function
public function upload()
{
if ($this->validate()) {
$this->files->saveAs('../web/uploads/' . $this->files->baseName. '.' .$this->files->extension);
$this->picture = '../web/uploads/' . $this->files->baseName. '.' .$this->files->extension;
return true;
} else {
return false;
}
}
public function signup()
{
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->picture = $this->picture;
$user->setPassword($this->password);
$user->generateAuthKey();
if ($user->save()) {
return $user;
}
else{
return null;
}
}
Just sharing you my solution, change the path to uploads folder to ../uploads/
In your model try changing saveAs function as shown below
$user->file->saveAs( '../uploads/'.$imageName.'.'.$model->file->extension );
I am a beginner in yii2, I faced a problem when i tried the file upload code from
https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload,
this solved my problem

Yii2 different form fields on create and on update scenario

In my Model I have created different scenarios. I have one form which is rendered bu both create and update method. The form fields are as follows
Form.php
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model, $options = ['header'=>'', 'class'=>'pull-left errorDiv']); ?>
<?= $form->field($model, 'user_fname')->textInput(['class'=>'form-control']);?>
<?= $form->field($model, 'user_lname')->textInput(['class'=>'form-control']); ?>
<?= $form->field($model,'user_email')->textInput(['class'=>'form-control']); ?>
<?= $form->field($model, 'user_password_hash')->passwordInput([]); ?>
<?= $form->field($model, 'user_password_hash_repeat')->passwordInput(['class'=>'form-control']); ?>
<?php $items = ArrayHelper::map(SimAuthAssignment::find()->all(),'item_name' ,'item_name');?>
<?= $form->field($mode, 'item_name')->dropDownList($items,[]);?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
On using update scenario I want only my email, firstname and last name to be rendered from the form.
const SCENARIO_REGISTER = 'signup';
const SCENARIO_CREATE = 'create';
const SCENARIO_UPDATE = 'update';
public function scenarios()
{
return [
self::SCENARIO_REGISTER => ['user_email', 'user_password_hash', 'user_fname', 'user_lname', 'agree','!user_password_hash_repeat','required'],
self::SCENARIO_CREATE => ['user_email', 'user_password_hash', 'user_fname', 'user_lname','!user_password_hash_repeat','required'],
self::SCENARIO_UPDATE => ['user_email', 'user_fname', 'user_lname', 'required'],
];
}
public static function tableName()
{
return 'sim_user';
}
And in my controller update method I am using scenario as below code.
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = SimUser::SCENARIO_UPDATE;
// var_dump($model->scenario); exit();
$mode = \app\modules\auth\models\SimAuthAssignment::find()->where(['user_id' => $id])->one();
if ($model->load(Yii::$app->request->post())&& $mode->load(Yii::$app->request->post())) {
$model->save();
return $this->redirect(['view', 'id' => $model->user_id]);
} else {
return $this->renderAjax('update', [
'model' => $model,
'mode' => $mode,
]);
}
}
I want to get only the email, firstname and lastname form fields to be rendered in the form when I edit. I want to ignore the others fields in the form when I edit. What am I missing here? Thanks!!
You are using an activeForm with all the inputField .. so all the fields are submit .. if you want only email, firstname and lastname
you should use another view with onnly these fields
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model, $options = ['header'=>'', 'class'=>'pull-left errorDiv']); ?>
<?= $form->field($model, 'user_fname')->textInput(['class'=>'form-control']);?>
<?= $form->field($model, 'user_lname')->textInput(['class'=>'form-control']); ?>
<?= $form->field($model,'user_email')->textInput(['class'=>'form-control']); ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
The scenario then check only the fields you have ruled and the submit return only the data you need
You can use the $model->isNewRecord functionality
if(!$model->isNewRecord) {
echo $form->field('Your-field')->textInput(['class' => 'form-control');
}
If I got you right you want to hide some input elements depends on your form scenario.
So, this can be easily achieved using the following code:
<?php if ($model->isUpdating()) { ?>
<?= $form->field($model, 'user_fname')->textInput(['class' => 'form-control']); ?>
<?= $form->field($model, 'user_lname')->textInput(['class' => 'form-control']); ?>
<?= $form->field($model, 'user_email')->textInput(['class' => 'form-control']); ?>
<?php } ?>
<?php if ($model->isRegistration()) { ?>
<?= $form->field($model, 'user_password_hash')->passwordInput([]); ?>
<?= $form->field($model, 'user_password_hash_repeat')->passwordInput(['class' => 'form-control']); ?>
<?php $items = ArrayHelper::map(SimAuthAssignment::find()->all(), 'item_name', 'item_name'); ?>
<?= $form->field($mode, 'item_name')->dropDownList($items, []); ?>
<?php } ?>
According to this, add the following code to the form model:
public function isUpdating() : bool {
return $this->scenario === self::SCENARIO_REGISTER;
}
public function isRegistration() : bool {
return $this->scenario === self::SCENARIO_UPDATE;
}

select2 and Pjax not work together in yii2

when i use pjax in yii2. selec2 widget stops working. while select2 working alone. (not working together)
im using select2 widgets and pjax together. but when submit form with pjax. in new form, select2 not work. (just show loading img). pls help me
what is problem?
I want to use both at the same time.
select2 extention page
in view:
<?php
use yii\helpers\Hrml;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model app\models\Vitrin */
?>
<?php Pjax::begin(); ?>
<?php
if($model->getProductTypeSetting()=='both')
{
echo $this->render('_form', [
'model' => $model,
]);
}
?>
<?php Pjax::end(); ?>
in _form:
<!-- BEGIN PAGE CONTENT-->
<?= Html::beginForm(['vitrin/index', 'id' => $id], 'post'['data-pjax' => '']); ?>
<?= Html::activeInput('text', $model, 'name', ['class' => $username]) ?>
<?= Html::submitButton('Submit', ['class' => 'submit']) ?>
<?= Html::endForm() ?>
<!-- END PAGE CONTENT-->
in controller:
if(Yii::$app->request->post('productType'))
{
$model->productType = $_POST['productType'];
if($model->productType=='physical')
{
return $this->renderAjax('_formProduct', ['products' => $this->getProductName()]);
}
else
throw new \yii\web\HttpException(406, Yii::t('app', 'Your request is invalid.'));
}
in _formProduct:
<!-- BEGIN PAGE CONTENT-->
<?= Html::beginForm(['vitrin/index', 'id' => $id], 'post', ['data-pjax' => '']); ?>
<?php
echo Select2::widget([
'name' => 'name',
'data' => [1 => "First", 2 => "Second", 3 => "Third", 4 => "Fourth", 5 => "Fifth"],
'options' => [
'placeholder' => 'Select a type ...',
],
]);
?>
<?= Html::submitButton('Submit', ['class' => 'submit']) ?>
<?= Html::endForm() ?>
<!-- END PAGE CONTENT-->
and AppAssets class:
class AppAsset extends AssetBundle
{
public $basePath = '#webroot/themes/backend';
public $baseUrl = '#web/themes/backend/assets_t';
public $css = [
'bootstrap-rtl/css/bootstrap-rtl.min.css',
'bootstrap-rtl/css/bootstrap-responsive-rtl.min.css',
'font-awesome/css/font-awesome.css',
'fancybox/source/jquery.fancybox.css',
'uniform/css/uniform.default.css',
];
public $js = [
'bootstrap-rtl/js/bootstrap.min.js',
'js/jquery.blockui.js',
'uniform/jquery.uniform.min.js',
];
when submit _form with pjax. in _formProduct, select2 not work. (just show loading img).
Generally, when I use Pjax, other Js codes are deactivated.
In your view header:
use kartik\select2\Select2Asset;
Select2Asset::register($this);
Also make sure you have the latest Select2 widget.

Yii2 Pjax not working

I want to refresh the gridview using Pjax but somehow it is not working. Here is the code:
_search.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;
$this->registerJs("
$('#btnAjaxSearch').click(function(){
$.ajax({
type: 'get',
data: $('.bank-search form').serializeArray(),
success: function (data) {
$.pjax.reload({container:\"#bank\"});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
return false;
});
", \yii\web\View::POS_END, 'bank-search');
?>
<div class="bank-search">
<?php Pjax::begin(['id' => 'bank-form']); ?>
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'bank_name') ?>
<?= $form->field($model, 'state') ?>
<?= $form->field($model, 'district') ?>
<?= $form->field($model, 'city') ?>
<div class="form-group">
<?= Html::Button('Search', ['class' => 'btn btn-primary','id' => 'btnAjaxSearch']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
</div>
index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
$this->title = 'Banks';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="bank-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Bank', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(['id' => 'bank']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'bank_name',
'state',
'district',
'city',
// 'branch',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
</div>
Controller
/**
* Lists all Bank models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new BankSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Simple search is working but Pjax is not. I am new to Yii2 so any help would be appreciated. Thank you.
Thanks Edin. It helped me to solved the problem. Here is what I did. It might help someone facing the same problem.
As Edin mentioned you need to pass the url along with the search parameters to the Pjax in order to refresh the gridview.
Here's my edited code :
$js = <<<JS
// get the form id and set the event
$('#bank-form-id').on('beforeSubmit', function(e) {
var form = $(this);
if(form.find('.has-error').length) {
return false;
}
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function(response) {
var csrf = yii.getCsrfToken();
var bank_name = $('#banksearch-bank_name').val();
var state = $('#banksearch-state').val();
var district = $('#banksearch-district').val();
var city = $('#banksearch-city').val();
var url = form.attr('action')+ '&_csrf='+csrf+'&BankSearch[bank_name]='+bank_name+'&BankSearch[state]='+state+'&BankSearch[district]='+district+'&BankSearch[city]='+city;
$.pjax.reload({url: url, container:'#bank'});
}
});
}).on('submit', function(e){
e.preventDefault();
});
JS;
$this->registerJs($js);
The way Pjax is working is by sending another request with special headers. When pjax request is detected only html required to update container is returned from server. Line
$.pjax.reload({container:\"#bank\"});
will send another request, and inside actionIndex queryParams will be empty.
You can solve this by storing search parameters to session or by specifing pjax url with parameters in query string.
Try following:
var url = urlWithFilters();
$.pjax({url: url, container: '#bank'});
In this case you don't need to create own ajax call, just create url with with filters.