Onsubmit call function in yii - yii

I want to call function when submit form in yii. In my form I enabled validateOnSubmit.
when in call function form Onsubmit mean it will call function in twice.
My Coding,
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'question-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => true,
'enableClientValidation' => false,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange' => false,
),
'htmlOptions' => array('onsubmit' => 'return checkmultiple()',),
));
?>
<div class="form-group">
<?php echo $form->labelEx($model, 'question_title'); ?>
<?php echo $form->textField($model, 'question_title', array('size' => 50, 'maxlength' => 250, 'class' => 'form-control')); ?>
<?php echo $form->error($model, 'question_title'); ?>
</div>
<?php if ($tileAssigned == Yii::app()->const->FLAG_ZERO) { ?>
<div class="form-group">
<?php echo $form->labelEx($model, 'type', array('label' => 'Is Multiple Choice')); ?>
<?php echo $form->radioButtonList($model, 'type', $yesnoList, array('separator' => '', 'onchange' => 'questionTypeChange(this.value);', 'class' => '')); ?>
<?php echo $form->error($model, 'type'); ?>
</div>
I am calling function checkmultiple mean it will call twice.
function checkmultiple()
{
}

Related

How to get last insert record - Yii 2

I am making application to create barcode
in my application, i want to create Barang but in issue slip i want issue slip filled automatically from the last issue slip
what can i do to fix it?
this is my view
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model backend\models\Barang */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="barang-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'rm_code')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'nama_barang')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'berat')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'issue_slip')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<div class="row">
<?= $form->field($model, 'berat')->textInput(['maxlength' => true]) ?>
<?php echo \Yii::$app->db->getLastInsertId('{{barang}}');?>
</div>
In controller before render
public function actionCreate()
{
$model = new Barang();
$modelForSlip = Barang::find()->orderBy(['id'=> SORT_DESC])->one();
$model->issue_slip = $modelForSlip->issue_slip;
if ($model->load(Yii::$app->request->post())){
$model->waktu = date('Y-m-d h:m:s');
$model->user = \Yii::$app->user->identity->username;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
//$model->issue_slip= \Yii::$app->db->getLastInsertId();
}
}
Let say this is your create function:
public function actionCreate()
{
$model = new Modal();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['update', 'id' => $model->Id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
then redirect to new page with last inserted ID
Now make you update function like this
public function actionUpdate($id)
{
$model2 = Model::findOne($id);
$model = new Modal();
$model->issue_slip = $model2['issue_slip'];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->Id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
In YII2 you can get last inserted record after save() function easily
like
$model->save();
echo $model->Id
or whatever column you want to get
instead of issue_slip you can use whatever column you want

How to know form submit sucessfully in yii

i want to submit button disable when form submitted sucessfully, because user click submit button so many times when page loading so its saved the same records so many times.so i want to decided to when form submit sucessfully mean disable that submit button.i am also using aftervalidate function but it can't correct form submit successfull.
My Coding:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'question-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => true,
'enableClientValidation' => false,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange' => false,
'afterValidate' => 'js:buttondisable',
),
));
?>
<div class="form-group">
<?php echo $form->labelEx($model, 'question_title'); ?>
<?php echo $form->textField($model, 'question_title', array('size' => 50, 'maxlength' => 250, 'class' => 'form-control')); ?>
<?php echo $form->error($model, 'question_title'); ?>
</div>
<?php if ($tileAssigned == Yii::app()->const->FLAG_ZERO) { ?>
<div class="form-group">
<?php echo $form->labelEx($model, 'type', array('label' => 'Is Multiple Choice')); ?>
<?php echo $form->radioButtonList($model, 'type', $yesnoList, array('separator' => '', 'onchange' => 'questionTypeChange(this.value);', 'class' => '')); ?>
<?php echo $form->error($model, 'type'); ?>
</div>
But After validation function calling when validation done in every time,but i want to form submit sucessfully at this time disable button.

Yii combine yiistrap and a languages array

This is my array that prints fields for each language
<?php foreach (Yii::app()->params['translatedLanguages'] as $l => $lang) :
if($l === Yii::app()->params['defaultLanguage']) $suffix = '';
else $suffix = '_'.$l;
?>
<fieldset>
<legend><?php echo $lang; ?></legend>
<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title'.$suffix,array('size'=>60,'maxlength'=>255)); ?>
<?php echo $form->error($model,'title'.$suffix); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'content'); ?>
<?php echo $form->textArea($model,'content'.$suffix); ?>
<?php echo $form->error($model,'content'.$suffix); ?>
</div>
</fieldset>
<?php endforeach; ?>
This is the yiistrap code for the tabs
http://www.getyiistrap.com/site/widgets#tabs
<?php $this->widget('bootstrap.widgets.TbTabs', array(
'placement' => 'below',
'tabs' => array(
array('label' => 'Home', 'content' => 'home test', 'active' => true),
array('label' => 'Profile', 'content' => 'profile test.'),
),
)); ?>
How can I replace the content (e.g. home test) with the fields from my form?
So in the end I have a tab for each language (like opencart)
This is the code for the tabs in my view
<?php $tabs = array(); ?>
<?php foreach (Yii::app()->params['translatedLanguages'] as $l => $lang) :
if($l === Yii::app()->params['defaultLanguage']) $suffix = '';
else $suffix = '_'.$l;
?>
<?php $tabs[] = array('label' => $lang, 'view' => '_fields', 'viewData' => array('form' => $form, 'model' => $model, 'suffix' => $suffix)); ?>
<?php endforeach; ?>
<?php $this->widget('bootstrap.widgets.TbTabs', array(
'tabs' => $tabs,
'viewData' => array('form' => $form, 'model' => $model, 'suffix' => $suffix),
)); ?>
And I added another view _fields.php
<?php echo $form->textFieldControlGroup($model,'title'.$suffix,array('span'=>5,'maxlength'=>128)); ?>
<?php echo $form->textAreaControlGroup($model,'content'.$suffix,array('rows'=>6,'span'=>8)); ?>
and I changed this in TbTabs.php ($tabOptions['viewData'])
protected function normalizeTabs($tabs)
{
$controller = $this->getController();
if (isset($controller)) {
foreach ($tabs as &$tabOptions) {
$items = TbArray::getValue('items', $tabOptions, array());
if (!empty($items)) {
$tabOptions['items'] = $this->normalizeTabs($items);
} else {
if (isset($tabOptions['view'])) {
$view = TbArray::popValue('view', $tabOptions);
if ($controller->getViewFile($view) !== false) {
$tabOptions['content'] = $controller->renderPartial($view, $tabOptions['viewData'], true);
}
}
}
}
}
return $tabs;
}

yii modal dialog login

I've been looking all over the internet and I can't seem to find the solution to just a simple login via header. I tried all sorts of way. The problem I have right now just reloads every time i hit login. It's only when I go to ?r=site/login it'll let me login. Is there some kind of controller for headers!??! Not sure what is wrong anymore.
Right now i have this in my header:
<?php $this->beginWidget(
'bootstrap.widgets.TbModal',
array('id' => 'login')
); ?>
<?php
$model=new LoginForm;
$this->renderPartial('//site/login', array('model'=>$model));
?>
<?php $this->endWidget(); ?>
//stuff here
<?php $this->widget(
'bootstrap.widgets.TbButton',
array(
'label' => 'Signin',
'type' => 'warning',
'htmlOptions' => array(
'data-toggle' => 'modal',
'data-target' => '#login',
),
)
);
?>
And then in site/login:
<div class="spacing">
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<div class="form" id="login-form">
<div class="login-container">
<div class="login-header">
<h1 title="login">Sign In</h1>
</div>
<div class="login-form">
<div class="input-position">
<?php echo $form->labelEx($model,'Email',array('class'=>'span3','style'=>'text-align:left')); ?>
<?php echo $form->textField($model,'email', array('class'=>'span3')); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="input-position">
<?php echo $form->labelEx($model,'password',array('class'=>'span3','style'=>'text-align:left')); ?>
<?php echo $form->passwordField($model,'password',array('class'=>'span3',)); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="input-position ">
<div class="rememberMe">
<?php echo $form->checkBox($model,'rememberMe'); ?>
<?php echo $form->label($model,'rememberMe'); ?>
<?php echo $form->error($model,'rememberMe'); ?>
</div>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Login'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
</div>
</div>
</div>
</div>
controller
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
As per my understanding, please keep your login script inside some loop like this to escape it from reloading every time.
if(Yii::app()->user->isGuest and (Yii::app()->controller->id=='site' and Yii::app()->controller->action->id = 'login')){
$this->beginWidget('bootstrap.widgets.TbModal', array('id' => 'login'));
---
$this->endWidget();
}else{
// keep some log out or other script here.
}
Here is the login what i have implemented on Modal login style:
Component/Header:
<?php
Yii::import('zii.widgets.CPortlet');
class Header extends CPortlet
{
protected function renderContent()
{
$this->render('Header');
}
}
Components/view/Header.php
<?php if(Yii::app()->user->isGuest){?>
<?php echo TbHtml::link('<i class="sign-in"></i>Sign in', '#', array(
'data-toggle' => 'modal',
'data-target' => '#loginModal',
));?>
<?php } else{ echo 'Hi!'.$user; } ?>
In View/Layout/Main.php
<?php
$model = new LoginForm;
$this->widget('bootstrap.widgets.TbModal', array(
'id' => 'loginModal',
'header' => '<h3 id="loginModal">Sign In</h3>',
'content'=> $this->renderPartial('userlogin',array('model'=>$model),true),
'remote' => $this->createUrl('site/userlogin'),
'onShow'=>'function(){$("#login-form")[0].reset(); }',
'show'=>false,)); ?>
View/Site/Userlogin.php
<?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'login-form',
//'helpType'=>'help-none',
'action'=>Yii::app()->createUrl('userlogin'),
//'enableAjaxValidation' => false,
'enableClientValidation'=>true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange'=>false,
'afterValidate' => 'js:function(form, data, hasError) {
if (!hasError){
str = $("#login-form").serialize() + "&ajax=login-form";
$.ajax({
type: "POST",
url: "' . Yii::app()->createUrl('site/userlogin') . '",
data: str,
dataType: "json",
beforeSend : function() {
$("#login").attr("disabled",true);
},
success: function(data, status) {
if(data.authenticated)
{
window.location = data.redirectUrl;
}
else
{
$.each(data, function(key, value) {
var div = "#"+key+"_em_";
$(div).text(value);
$(div).show();
});
$("#login").attr("disabled",false);
}
},
});
return false;
}
}',
),
));?>
<?php echo $form->textFieldControlGroup($model,'username',array('span'=>5,'maxlength'=>255,'required'=>true)); ?>
<?php echo $form->passwordFieldControlGroup($model,'password',array('span'=>5,'maxlength'=>255,'required'=>true)); ?>
<?php echo TbHtml::submitbutton('Sign In',array('class'=>'btn btn-primary')); ?>
<?php $this->endWidget(); ?>
This will Authenticate via Ajax
SiteController:
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
$errors = CActiveForm::validate($model);
if ($errors != '[]')
{
echo $errors;
Yii::app()->end();
}
}
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if ($model->validate() && $model->login()) {
if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
$user_id = Yii::app()->user->id;
$arr = array();
$record = Users::model()->findByPk($user_id);
if ($record) {
echo CJSON::encode(array( 'authenticated' => true,
'redirectUrl' => CController::createUrl('users/trainerprofile'),
"id" => $record->id,));
Yii::app()->end();
}
}

Yii - How to display display captcha in CPortlet?

I'm using portlet to display contact form - the very same as is on static page which comes generated as standard. I'm using the same ContactForm model. The form displays but captcha is not displaying and reports "CCaptchaValidator.action "captcha" is invalid. Unable to find such an action in the current controller."
I'm new to yii so it takes awfully lot of time to figure everything out. Any quick advice what I shell do to make it working?
Best!
Yii::import('zii.widgets.CPortlet');
class ContactFormCard extends CPortlet
{
public $title='Contact';
protected function renderContent()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
$this->controller->refresh();
}
$this->render('contactFormCard',array('model'=>$model));
}
public function actions()
{
return array(
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
);
}
}
and in portlet view:
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
<?php echo $form->error($model,'verifyCode'); ?>
</div>
<?php endif; ?>
In you SiteController.php add:
public function actions() {
return array(
'captcha' => array(
'class' => 'CCaptchaAction',
'backColor' => 0xFFFFFF,
),
// [...]
);
}
In you ContactForm.php add:
public function rules() {
return array(
// [...]
array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements(), 'message' => Yii::t('formsErros', 'Código de verificação incorreto.')),
// [...]
);
}
In you view.php
<!-- [...] -->
<?php if(CCaptcha::checkRequirements()): ?>
<div class="captcha">
<?=$form->labelEx($contactFormModel, 'verifyCode')?>
<?php $this->widget('CCaptcha', array('clickableImage' => true, 'showRefreshButton' => true, 'imageOptions' => array('id' => 'captchaContactForm', 'class' => 'clickableCursor'), 'buttonLabel' => '')); ?>
<?=$form->textField($contactFormModel, 'verifyCode', array('class' => 'verticalAlignBottom'))?>
<?=$form->error($contactFormModel, 'verifyCode')?>
</div>
<?php endif; ?>
<!-- [...] -->