Client side validation in not working - php

I am working client side validation in yii2 but it is not working for me.
View File
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\captcha\Captcha;
?>
<ul class="breadcrumb">
<li>Home</li>
<li>Pages</li>
<li class="active">Login</li>
</ul>
<!-- BEGIN SIDEBAR & CONTENT -->
<div class="row margin-bottom-40">
<!-- BEGIN SIDEBAR -->
<!--<div class="sidebar col-md-3 col-sm-3">
<ul class="list-group margin-bottom-25 sidebar-menu">
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Register</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Restore Password</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> My account</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Address book</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Wish list</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Returns</li>
<li class="list-group-item clearfix"><i class="fa fa-angle-right"></i> Newsletter</li>
</ul>
</div>-->
<!-- END SIDEBAR -->
<!-- BEGIN CONTENT -->
<div class="col-md-9 col-sm-9">
<h1>Login</h1>
<div class="content-form-page">
<div class="row">
<div class="col-md-7 col-sm-7">
<?php $form = ActiveForm::begin(['id' => 'login-form','class' => 'form-horizontal form-without-legend']); ?>
<?php echo $form->errorSummary($model); ?>
<div class="form-group">
<label for="email" class="col-lg-4 control-label">Email <span class="require">*</span></label>
<div class="col-lg-8">
<?= $form->field($model, 'username',['template' => "{input}"])->textInput(array('placeholder' => 'Username','class'=>'form-control validate[required]')); ?>
</div>
</div>
<div class="form-group">
<label for="password" class="col-lg-4 control-label">Password <span class="require">*</span></label>
<div class="col-lg-8">
<?= $form->field($model, 'password',['template' => "{input}"])->passwordInput(array('class'=>'form-control validate[required]','placeholder'=>'Password')); ?>
<!--<input type="text" class="form-control" id="password">-->
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0">
Forget Password?
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0 padding-top-20">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
<!--<button type="submit" class="btn btn-primary">Login</button>-->
</div>
</div>
<div class="row">
<div class="col-lg-8 col-md-offset-4 padding-left-0 padding-top-10 padding-right-30">
<hr>
<div class="login-socio">
<p class="text-muted">or login using:</p>
<ul class="social-icons">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
<!--</form>-->
</div>
<!--<div class="col-md-4 col-sm-4 pull-right">
<div class="form-info">
<h2><em>Important</em> Information</h2>
<p>Duis autem vel eum iriure at dolor vulputate velit esse vel molestie at dolore.</p>
<button type="button" class="btn btn-default">More details</button>
</div>
</div>-->
</div>
</div>
</div>
<!-- END CONTENT -->
</div>
<!-- END SIDEBAR & CONTENT -->
Colntroller File
<?php
namespace frontend\controllers;
use frontend\models\Users;
use backend\models\SmsData;
use backend\models\SmsDataSearch;
use Yii;
use frontend\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\ArrayDataProvider;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login','index', 'error','register'],
'allow' => true,
],
[
'actions' => ['logout','report','create','delete'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
// 'logout' => ['post'],
],
],
];
}
/**
* #inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex()
{
return $this->render('index');
}
public function actionRegister()
{
$model = new Users();
if($model->load(Yii::$app->request->post()))
{
$model->status='0';
$model->is_delete='0';
$model->created_by='1';
$model->password=md5($_POST['Users']['password']);
$model->created_date=date('Y-m-d h:i:s');
$model->role_type='1';
$model->save();
Yii::$app->session->setFlash('success', 'You Have Successfully Register');
return $this->redirect(array('login'));
}
return $this->render('register',['model'=>$model]);
}
public function actionLogin()
{
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
$data=Yii::$app->db->createCommand("select * from `users` where user_id = '".Yii::$app->user->getId()."'")->queryAll();
if($data[0]['role_type'] == '1')
{
Yii::$app->session->setFlash('success', 'You Have Successfully LogIn');
return $this->redirect(array('report'));
}
elseif($data[0]['role_type'] =='0')
{
Yii::$app->session->setFlash('success', 'You Have Successfully LogIn');
$url=Yii::$app->urlManager->createUrl('users/index');
return $this->redirect($url);
}
} else {
return $this->render('login',[
'model' => $model,
]);
}
}
public function actionReport()
{
$model= new SmsData();
if($model->load(Yii::$app->request->post()))
{
$fromdate=date('Y-m-d',strtotime($_POST['SmsData']['fromDate']));
$todate = date('Y-m-d',strtotime($_POST['SmsData']['toDate']));
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND s.message_id != '9999' AND date(s.created_date) >= '".$fromdate."' AND date(s.created_date) <= '".$todate."'";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
$model->fromDate=$_POST['SmsData']['fromDate'];
$model->toDate=$_POST['SmsData']['toDate'];
return $this->render('report',['dataProvider'=>$provider,'model'=>$model]);
}
else
{
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND s.message_id != '9999' ";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('report',['dataProvider'=>$provider,'model'=>$model]);
}
}
public function actionCreate()
{
$model = new SmsData();
if($model->load(Yii::$app->request->post())) {
$clientID=\frontend\models\Users::findOne(Yii::$app->user->getId());
$model->created_by = Yii::$app->user->getId();
$model->created_date= date('Y-m-d',strtotime($_POST['SmsData']['created_date']));
$model->rating = $_POST['SmsData']['rating'];
$model->text = $_POST['SmsData']['text'];
$model->message_id = 9999;
$model->client_id = $clientID->unique_id;
$model->save();
Yii::$app->session->setFlash('success', 'Data Inserted Successfully');
return $this->redirect(array('create'));
} else {
$query="SELECT s.*,r.description as ratingtext FROM sms_data s
INNER JOIN users u ON u.unique_id = s.client_id
LEFT JOIN rating r ON r.rating = s.rating
WHERE u.user_id = '".Yii::$app->user->getId()."' AND message_id = 9999
AND s.is_delete = 0 AND s.status = 1";
$data=Yii::$app->db->createCommand($query)->queryAll();
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('create',['model'=>$model,'dataProvider'=>$provider]);
}
}
public function actionDelete($id) {
$model = new SmsData();
$command = Yii::$app->db->createCommand('UPDATE sms_data SET is_delete = 1 WHERE sms_id='.$id);
$command->execute();
Yii::$app->session->setFlash('success', 'Deleted Successfully ');
return $this->redirect(array('create'));
}
public function actionLogout()
{
Yii::$app->user->logout();
Yii::$app->session->setFlash('success', 'You Have Successfully Logout');
return $this->goHome();
}
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending email.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
public function actionAbout()
{
return $this->render('about');
}
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,
]);
}
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->getSession()->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->getSession()->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->getSession()->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
}
Model :
<?php
namespace frontend\models;
use frontend\models\Users;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
private $_id = false;
private $_name;
/**
* #inheritdoc
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*/
public function validatePassword()
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError('password', 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* #return boolean whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = Users::findByUsername($this->username);
}
return $this->_user;
}
public function getId()
{
if ($this->_id === false) {
$this->_id = $this->user_id;
}
return $this->_id;
}
}
What i need to do for client side validation ? Server side validation is working for me.

This is not a bug! You have to use ActiveForm::validate() for send errors back the browser as it formats the attributes same as ActiveForm renders
if (Yii::$app->request->isAjax && $model->load($_POST))
{
Yii::$app->response->format = 'json';
return \yii\widgets\ActiveForm::validate($model);
}

To enable AJAX validation for the whole form, you have to set the
yii\widgets\ActiveForm::enableAjaxValidation
property to be true and specify id to be a unique form identifier:
$form = ActiveForm::begin([
'id' => 'register-form',
'enableClientValidation' => true,
'options' => [
'validateOnSubmit' => true,
'class' => 'form'
],
])
;

Related

Login Modal Yii

I have a login page, but I need it to be via a modal. When I try to set the login code to the modal:
This is the login:
<section id="wrapper" class="login-register">
<div class="login-box">
<div class="white-box">
<img class="logo" src="<?= $url ?>assets/images/logo_redondo.png" alt="iniciar sesión" srcset="">
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'layout' => 'horizontal',
'fieldConfig' => [
'template' => "{label}\n<div class=\"col-lg-12\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
'labelOptions' => ['class' => 'col-lg-1 control-label'],
],
]); ?>
<?= $form->field($model, 'email')->textInput(['autofocus' => true])->label("Correo Electronico ") ?>
<?= $form->field($model, 'password')->passwordInput()->label("Contraseña") ?>
<div class="form-group">
<div class="col-lg-12 ">
<?= Html::submitButton('Iniciar Sesion', ['class' => 'btn btn-primary btn-lg btn-block', 'name' => 'login-button']) ?>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 ">
<a style="width: 100%;" href="<?= $url ?>" class="btn btn-fill-out">Volver a la Pagina</a>
</div>
<br>
<div class="col-md-12">
<a style="width: 100%;" href="<?= Url::toRoute(['site/register']) ?>" class="btn btn-fill-out">Regístrarse</a>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</section>
Controller:
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
}
$model->password = '';
return $this->renderPartial('login', [
'model' => $model,
]);
}
and the model:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*
* #property User|null $user This property is read-only.
*
*/
class LoginForm extends Model
{
public $email;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* #return array the validation rules.
*/
public function rules()
{
return [
// username and password are both required
[['email', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* #param string $attribute the attribute currently being validated
* #param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
* #return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
public function getUser()
{
if ($this->_user === false) {
$this->_user = User::findByEmail($this->email);
}
return $this->_user;
}
}
How can I place it on a modal? The idea is that when the user clicks on the user icon, the modal will run and show the same fields that he has in the login. I tried to place the login code inside the modal, but the page doesn't work.
Try it:
frontend/controllers/SiteController.php file example with default login action:
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
return $this->render('login', [
'model' => $model,
]);
}
}
public function actionLoginAjax()
{
if (Yii::$app->request->isAjax) {
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
$model->password = '';
return $this->renderAjax('_form_login', [
'model' => $model,
]);
}
}
return $this->redirect(['login']);
}
frontend/views/login.php file example:
<?php
/* #var $this yii\web\View */
/* #var $form yii\bootstrap\ActiveForm */
/* #var $model \common\models\LoginForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;
$this->title = 'Contact';
$this->params['breadcrumbs'][] = $this->title;
\yii\bootstrap\Modal::begin([
'id' => 'modal-login',
'header' => '<h5 class="modal-title">Login</h5>',
'size' => \yii\bootstrap\Modal::SIZE_LARGE,
]);
\yii\bootstrap\Modal::end();
$js = <<<JS
$(function() {
$('.send-login').click(function(e) {
e.preventDefault();
$('#modal-login').modal('show').find('.modal-body').load($(this).attr('href'));
});
});
JS;
$this->registerJs($js);
?>
<div class="site-login">
<h1><?= Html::encode($this->title) ?></h1>
<?= Html::a('Login', [
'site/login-ajax',
], ['class' => ' btn btn-success send-login']); ?>
<p>Please fill out the following fields to login:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div style="color:#999;margin:1em 0">
If you forgot your password you can <?= Html::a('reset it', ['site/request-password-reset']) ?>.
<br>
Need new verification email? <?= Html::a('Resend', ['site/resend-verification-email']) ?>
</div>
<div class="form-group">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
_form_login.php file in the same directory login.php and example below.
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;
/**
* #var $this \yii\web\View
*/
$js = <<<JS
$("document").ready(function(){
//this will work with mulitpart data or regular form
$('#login-form').submit(function(e) {
e.preventDefault();
var form = document.getElementById('login-form');
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: new FormData(form),
mimeType: 'multipart/form-data',
contentType: false,
cache: false,
processData: false,
dataType: 'json',
success: function(data) {
//if there are serverside errors then ajax show them on the page
if (data.errors) {
$.each(data.errors, function(key, val) {
var el = $('#' + key);
el.parent('.form-group').addClass('has-error');
el.next('.help-block').html(val);
});
} else {
//reload pjax and close boostrap modal
//$('#modal').modal('hide');
}
}
});
});
});
JS;
$this->registerJs($js);
?>
<?php Pjax::begin(['id' => 'pjax-create', 'enablePushState' => false]) ?>
<?php $form = ActiveForm::begin(['id' => 'login-form', 'options' => ['data-pjax' => true]]); ?>
<?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div class="form-group">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary', 'name' => 'login-button']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::end() ?>
frontend/models/LoginForm.php file without any changes:
<?php
namespace common\models;
use Yii;
use yii\base\Model;
/**
* Login form
*/
class LoginForm extends Model
{
public $username;
public $password;
public $rememberMe = true;
private $_user;
/**
* {#inheritdoc}
*/
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* #param string $attribute the attribute currently being validated
* #param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
/**
* Logs in a user using the provided username and password.
*
* #return bool whether the user is logged in successfully
*/
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
* #return User|null
*/
protected function getUser()
{
if ($this->_user === null) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}

Laravel 5.2 Upload Image to uploads folder while user registration

I am trying to save uploaded image to uploads folder as well as database at the time of user registration, the image name is successfully saved to the database along with user details like name, address, email and etc. I am new to laravel. Please can any one suggest me, thank you.
Please find below is my register.blade.php
#extends('layouts.site')
#section('content')
<div class="login-content">
<a class="hiddenanchor" id="signup">
</a>
<a class="hiddenanchor" id="signin">
</a>
#include('layouts.site-navigation')
#include('errors.errors')
<div class="login_wrapper">
<div class="animate form login_form">
<section class="login_content">
<!-- <form> -->
<h1>Registration Form
</h1>
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm", 'files'=>'true')) !!}
<div>
</div>
<div>
{{ Form::text('username', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("username"),
'ng-model'=>'username',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.username.$touched &&
registrationForm.username.$invalid}',
'ng-minlength' => '4',
)) }}
</div>
<div>
{{ Form::text('rollnumber', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("roll number"),
'ng-minlength' => '2',
)) }}
<div>
{{ Form::text('branch', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("branch"),
'ng-minlength' => '2',
)) }}
</div>
<div>
{{ Form::text('phone', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("phone"),
'ng-model'=>'phone',
'ng-pattern' => getRegexPattern('phone'),
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.phone.$touched &&
registrationForm.phone.$invalid}',
'ng-minlength' => '10',
)) }}
</div>
<div>
<select id="make" name="place" class="form-control">
<option value="" disabled selected>Interested Work Place
</option>
<option value="Yemmiganur">Yemmiganur
</option>
<option value="Raichur">Raichur
</option>
</select>
</div>
<br>
<div>
Interested To Work In Night Shift:
<input type="radio" name="night_shift" value="Yes" > Yes
<input type="radio" name="night_shift" value="No"> No
</div>
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">New to site?
<a href="#signup" class="to_register"> Next
</a>
</p>
<div class="clearfix">
</div>
</div>
<br>
<a href="{{URL_USERS_LOGIN}}">
<p class="text-center">{{getPhrase('i_am_having_account')}}
</p>
</a>
</div>
</section>
<div id="register" class="animate form registration_form">
<section class="login_content">
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm")) !!}
<!-- <form> -->
<h1>Registration Form
</h1>
<div>
{{ Form::email('email', $value = null , $attributes =
array('class'=>'form-control formclass',
'placeholder' => getPhrase("email"),
'ng-model'=>'email',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.email.$touched &&
registrationForm.email.$invalid}',
)) }}
</div>
<div>
{{ Form::password('password', $attributes = array('class'=>'form-
control formclass instruction-call',
'placeholder' => getPhrase("password"),
'ng-model'=>'registration.password',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.password.$touched &&
registrationForm.password.$invalid}',
'ng-minlength' => 5
)) }}
</div>
<div>
{{ Form::password('password_confirmation', $attributes =
array('class'=>'form-control formclass instruction-call',
'placeholder' => getPhrase("password_confirmation"),
'ng-model'=>'registration.password_confirmation',
'required'=> 'true',
'ng-class'=>'{"has-error":
registrationForm.password_confirmation.$touched &&
registrationForm.password_confirmation.$invalid}',
'ng-minlength' => 5,
'compare-to' =>"registration.password"
)) }}
{{ Form::text('aadhar_number', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => "UID (Aadhaar)",
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.aadhar_number.$touched
&& registrationForm.aadhar_number.$invalid}',
'ng-minlength' => '12',
)) }}
<br>
</div>
<fieldset class="form-group" >
<input type="file" class="form-control" name="image"
accept=".png,.jpg,.jpeg" id="image_input">
</fieldset>
<?php $parent_module = getSetting('parent', 'module'); ?>
#if(!$parent_module)
<input type="hidden" name="is_student" value="0">
#else
<div class="row">
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_an_admin')}}
</label>
</div>
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_a_student')}}
</label>
</div>
</div>
#endif
<div class="text-center buttons">
<button type="submit" class="btn btn-default submit"
ng-disabled='!registrationForm.$valid'>
{{getPhrase('register_now')}}
</button>
</div>
{!! Form::close() !!}
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">Already a member ?
<a href="#signin" class="to_register"> Previous
</a>
</p>
<div class="clearfix">
</div>
</div>
</section>
</div>
</div>
#stop
#section('footer_scripts')
#include('common.validations')
#stop
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use \Auth;
use Socialite;
use Exception;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
protected $dbuser = '';
protected $provider = '';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|max:255|unique:users',
// 'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'aadhar_number' => 'required|max:12|unique:users',
'password' => 'required|min:6|confirmed',
'image' => 'bail',
'place' => 'required',
'night_shift' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data )
{
$type = 'student';
if($data['is_student'])
$type = 'parent';
$role = getRoleData($type);
$user = new User();
$user->username = $data['username'];
$user->rollnumber = $data['rollnumber'];
$user->branch = $data['branch'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->role_id = $role;
$user->image = $data['image'];
$user->place = $data['place'];
$user->night_shift = $data['night_shift'];
$user->phone = $data['phone'];
$user->aadhar_number = $data['aadhar_number'];
$user->slug = $user->makeSlug($user->username);
$user->save();
$user->roles()->attach($user->role_id);
try{
$this->sendPushNotification($user);
sendEmail('registration', array('user_name'=>$user->name,
'username'=>$data['username'], 'to_email' => $user->email,
'password'=>$data['password'], 'aadhar_number' => $user->aadhar_number));
}
catch(Exception $ex)
{
}
flash('success','record_added_successfully', 'success');
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
return $user;
}
public function sendPushNotification($user)
{
if(getSetting('push_notifications', 'module')) {
if(getSetting('default', 'push_notifications')=='pusher') {
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
}
else {
$this->sendOneSignalMessage('New Registration');
}
}
}
/**
* This is method is override from Authenticate Users class
* This validates the user with username or email with the sent password
* #param Request $request [description]
* #return [type] [description]
*/
protected function processUpload(Request $request, User $user)
{
if(env('DEMO_MODE')) {
return 'demo';
}
if ($request->hasFile('image')) {
$imageObject = new ImageSettings();
$destinationPath = $imageObject->getProfilePicsPath();
$destinationPathThumb = $imageObject->getProfilePicsThumbnailpath();
$fileName = $user->id.'.'.$request->image->guessClientExtension();
;
$request->file('image')->move($destinationPath, $fileName);
$user->image = $fileName;
Image::make($destinationPath.$fileName)->fit($imageObject-
>getProfilePicSize())->save($destinationPath.$fileName);
Image::make($destinationPath.$fileName)->fit($imageObject-
>getThumbnailSize())->save($destinationPathThumb.$fileName);
$user->save();
}
}
public function postLogin(Request $request)
{
$login_status = FALSE;
if (Auth::attempt(['aadhar_number' => $request->email, 'password' =>
$request->password])) {
// return redirect(PREFIX);
$login_status = TRUE;
}
elseif (Auth::attempt(['email'=> $request->email, 'password' =>
$request->password])) {
$login_status = TRUE;
}
if(!$login_status)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Check if the logged in user is parent or student
* if parent check if admin enabled the parent module
* if not enabled show the message to user and logout the user
*/
if($login_status) {
if(checkRole(getUserGrade(7))) {
if(!getSetting('parent', 'module')) {
return redirect(URL_PARENT_LOGOUT);
}
}
}
/**
* The logged in user is student/admin/owner
*/
if($login_status)
{
return redirect(PREFIX);
}
}
/**
* Redirect the user to the GitHub authentication page.
*
* #return Response
*/
public function redirectToProvider($logintype)
{
if(!getSetting($logintype.'_login', 'module'))
{
flash('Ooops..!', $logintype.'_login_is_disabled','error');
return redirect(PREFIX);
}
$this->provider = $logintype;
return Socialite::driver($this->provider)->redirect();
}
/**
* Obtain the user information from GitHub.
*
* #return Response
*/
public function handleProviderCallback($logintype)
{
try{
$user = Socialite::driver($logintype);
if(!$user)
{
return redirect(PREFIX);
}
$user = $user->user();
if($user)
{
if($this->checkIsUserAvailable($user)) {
Auth::login($this->dbuser, true);
flash('Success...!', 'log_in_success', 'success');
return redirect(PREFIX);
}
flash('Ooops...!', 'faiiled_to_login', 'error');
return redirect(PREFIX);
}
}
catch (Exception $ex)
{
return redirect(PREFIX);
}
}
public function checkIsUserAvailable($user)
{
$id = $user->getId();
$nickname = $user->getNickname();
$name = $user->getName();
$email = $user->getEmail();
$avatar = $user->getAvatar();
$this->dbuser = User::where('email', '=',$email)->first();
if($this->dbuser) {
//User already available return true
return TRUE;
}
$newUser = array(
'name' => $name,
'email'=>$email,
);
$newUser = (object)$newUser;
$userObj = new User();
$this->dbuser = $userObj->registerWithSocialLogin($newUser);
$this->dbuser = User::where('slug','=',$this->dbuser->slug)->first();
// $this->sendPushNotification($this->dbuser);
return TRUE;
}
public function socialLoginCancelled(Request $request)
{
return redirect(PREFIX);
}
}
First, you should urgently consider updating Laravel to newer versions.
Second, I think you are missing enctype="multipart/form-data" accept-charset="UTF-8" in your form tag

Saving data to db yii2

I'm trying to save data from my form to db. But when I click "submit" button nothing happened(page is refresh but my db table is blank) what I did wrong?
I'm create model which extend ActiveRecord:
class EntryForm extends \yii\db\ActiveRecord
{
public $id;
public $name;
public $email;
public $age;
public $height;
public $weight;
public $city;
public $checkboxList;
public $checkboxList1;
public $imageFiles;
public function rules()
{
return [
[['name', 'email','age','height','weight','city','checkboxList','checkboxList1'], 'required'],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg','maxFiles' => 5],
['email', 'email'],
];
}
public static function tableName()
{
return 'form';
}
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'name',
'email' => 'e-mail',
'age' => 'age',
'height' => 'height',
'weight' => 'weight',
'city' => 'city',
'checkboxList' => 'technies',
'checkboxList1' => 'english_level',
'imageFiles[0]' => 'photo_1',
'imageFiles[1]' => 'photo_2',
'imageFiles[2]' => 'photo_3',
'imageFiles[3]' => 'photo_4',
'imageFiles[4]' => 'photo_5'
];
}
public function insertFormData()
{
$entryForm = new EntryForm();
$entryForm->name = $this->name;
$entryForm->email = $this->email;
$entryForm->age = $this->age;
$entryForm->height = $this->height;
$entryForm->weight = $this->weight;
$entryForm->city = $this->city;
$entryForm->checkboxList = $this->checkboxList;
$entryForm->checkboxList1 = $this->checkboxList1;
$entryForm->imageFiles = $this->imageFiles;
return $form->save();
}
public function contact($email)
{
if ($this->validate()) {
Yii::$app->mailer->compose()
->setTo($email)
->setFrom('prozrostl#gmail.com')
->setSubject('Email from test app')
->setTextBody($this->name + $this->age + $this->height + $this->width + $this->city + $this->checkboxList + $this->checkboxList1 + $this->imageFiles)
->send();
return true;
} else {
return false;
}
}
}
then I update my view file to show the form, view it's just easy few fields and upload files button(but all information doesn't save)
<?php $form = ActiveForm::begin([
'id' => 'my-form',
'options' => ['enctype' => 'multipart/form-data']
]); ?>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'name')->textInput(['class'=>'name_class'])->input('name',['placeholder' => "Имя"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'email')->textInput()->input('email',['placeholder' => "E-mail"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'age')->textInput()->input('age',['placeholder' => "Возраст(полных лет)"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'height')->textInput()->input('height',['placeholder' => "Рост"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<?= $form->field($entryForm, 'weight')->textInput()->input('weight',['placeholder' => "Вес"])->label(false); ?>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'city')->textInput()->input('city',['placeholder' => "Город проживания"])->label(false); ?>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<p><img class="describe_images" src="computer.png"></img>Нужна ли техника в аренду</p>
</div>
<?= $form->field($entryForm, 'checkboxList')->checkboxList(['no'=>'Нет', 'yes_camera'=>'Да,только камера', 'yes_both'=>'да,компьютер и камера'])->label(false) ?>
</div>
<div class="row">
<div class="col-lg-3">
<p><img class="describe_images" src="English.png"></img>Знание английского</p>
</div>
<?= $form->field($entryForm, 'checkboxList1')->checkboxList(['starter'=>'Без знания', 'elementary'=>'Базовый', 'intermediate'=>'Средний','up-intermediate'=>'Высокий','advanced'=>'Превосходный'])->label(false) ?>
</div>
<div class="row">
<div class="col-lg-6">
<div class="col-lg-6">
<p class="add_photo"><img class="describe_images" src="photo.png"></img>Добавить фото(до 5 штук)</p>
</div>
<div class="col-lg-6">
<?= $form->field($entryForm, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>
</div>
</div>
<div class="col-lg-6 pixels-line">
<div class="preview"></div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end() ?>
and then I add that code to my controller. I created new action ActionForm and put into that code:
public function actionForm()
{
$entryForm = new EntryForm();
if ($entryForm->load(Yii::$app->request->post()) && $entryForm->insertFormData()) {
}
}
Why do you redeclare the variables in the database? you're basically telling yii to ignore the attributes on the table.
public $id;
public $name;
public $email;
public $age;
public $height;
public $weight;
public $city;
public $checkboxList;
public $checkboxList1;
public $imageFiles;
Remove the public declarations and see if it works.
Your code looks ok, so probably you have some validation errors.
In the insertFormData() method add the following to get the validation errors:
if (!$entryForm->validate()){
var_dump($entryForm->getErrors());
}
Later edit:
Your insertFormData method is basically useless because the $entryForm->load loads the data from POST.
The second problem is probably with the file upload. To get the uploaded files use UploadedFile::getInstance($model, 'imageFile'). More info here
I suggest you to create a crud using Gii (the crud generator) and then implement the file upload according to the documentation mentioned above. And in this case you will see the validation errors too.

Yii2-dynamicforms extension

I am new to yii2.0, and I'm currently creating a form po
and po_item, the problem is to update the form the modelPoItem is empty from database.
I thank those who can help me for this Home with dynamic form can be with an example. Thank you in advance
Po Controller
/**
* Updates an existing Po model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsPoItem = [new PoItem];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
'modelsPoItem' => (empty($modelsPoItem)) ? [new PoItem] : $modelsPoItem
]);
}
}
View
<div class="po-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= $form->field($model, 'po_no')->textInput(['maxlength' => 10]) ?>
<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Po Items</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsPoItem[0],
'formId' => 'dynamic-form',
'formFields' => [
'po_item_no',
'quantity',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsPoItem as $i => $modelPoItem): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Po Item</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelPoItem->isNewRecord) {
echo Html::activeHiddenInput($modelPoItem, "[{$i}]id");
}
?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelPoItem, "[{$i}]po_item_no")->textInput(['maxlength' => 128]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($modelPoItem, "[{$i}]quantity")->textInput(['maxlength' => 128]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
you should be change you update action like this:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsPoItem = $model->poItems;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$oldIDs = ArrayHelper::map($modelsPoItem, 'id', 'id');
$modelsPoItem= Model::createMultiple(PoItem::className(),$modelsPoItem);
Model::loadMultiple($modelsPoItem, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPoItem, 'id', 'id')));
// ajax validation
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ArrayHelper::merge(
ActiveForm::validateMultiple($modelsPoItem),
ActiveForm::validate($model)
);
}
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsPoItem) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
PoItem::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsPoItem as $modelPoItem) {
$modelPoItem->po_id = $model->id;
if (! ( $flag = $modelPoItem->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
return $this->render('update', [
'model' => $model,
'modelsPoItem' => (empty($modelsPoItem)) ? [new Model] : $modelsPoItem
]);
}
}

Yii Framework file input skipOnEmpty validation always fails

I am currently doing a project in PHP Yii framework.
I have a form with file input field called company_logo.For the field I have added the following rule in the model [['company_logo'],'file','skipOnEmpty'=>false]
When I upload file, it shows
Please upload a file.
even if I uploaded a file.
When I remove the
skipOnEmpty
it is uploading the file.I have researched several places for the issue.But couldn't find a solution.
The controller, view and model are given below
View - add_company.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/*Assigning the parameters to be accessible by layouts*/
foreach($layout_params as $layout_param => $value) {
$this->params[$layout_param] = $value;
}
?>
<div class="form-group">
</div>
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Add Company</h3>
</div><!-- /.box-header -->
<!-- form start -->
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<div class="box-body">
<?php if(isset($message)&&sizeof($message)): ?>
<div class="form-group">
<div class="callout callout-info alert-dismissible">
<h4><?php if(isset($message['title']))echo $message['title'];?></h4>
<p>
<?php if(isset($message['body']))echo $message['body'];?>
</p>
</div>
</div>
<?php endif;?>
<div class="form-group">
<?= $form->field($model, 'company_name')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'company_address')->textArea(array('class'=>'form-control')); ?>
</textarea>
<div class="form-group">
<?= $form->field($model, 'company_logo')->fileInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_name')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_email')->textInput(array('class'=>'form-control','type'=>'email')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_phone_number')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'admin_password')->passwordInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'retype_admin_password')->passwordInput(array('class'=>'form-control')); ?>
</div>
<div class="box-footer">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
</div><!-- /.box-body -->
<?php ActiveForm::end(); ?>
</div>
</div>
Controller - CompanyController.php
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\CompanyModel;
use yii\web\UploadedFile;
global $username;
class CompanyController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionEntry()
{
}
public function actionAdd() {
$layout_params=array(
'username'=>'admin',
'sidebar_menu1_class' =>'active',
'sidebar_menu12_class' =>'active',
'dash_title' => 'Companies',
'dash_sub_title'=>'Add new company'
);
$message = array();
$model = new CompanyModel();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
echo "hello";
$model->company_logo = UploadedFile::getInstance($model, 'company_logo');
echo "world";
if ($model->company_logo && $model->validate()) {
$model->company_logo->saveAs('uploads/' . $model->company_logo->baseName . '.' . $model->company_logo->extension);
} else {
echo "Yo Yio ture";
exit;
}
$model->add_company();
$message['title'] = 'Wow !';
$message['body'] = 'Successfully added company '.$model->company_name;
}else {
$message = $model->getErrors();
// print_r( $message );
// exit;
}
return $this->render('add-company', ['model' => $model,
'layout_params'=>$layout_params,
'message' =>$message
]);
//return $this->render('add-company',$data);
}
public function actionSave() {
//print_r($_POST);
}
public function actionIndex()
{
$data = array(
'layout_params'=>array(
'username'=>'admin',
'sidebar_menu11_class' =>'active'
)
);//
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
Model - CompanyModel.php
<?php
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;
class CompanyModel extends Model
{
public $company_name;
public $company_address;
public $company_logo;
public $admin_email;
public $admin_name;
public $admin_password;
public $retype_admin_password;
public $admin_phone_number;
public function rules()
{
return [
[['company_name'], 'required'],
[['company_address'],'required'],
[['admin_name'],'required'],
[['admin_email'],'required'],
[['admin_password'],'required'],
[['retype_admin_password'],'required'],
[['admin_phone_number'],'required'],
[['company_logo'],'file','skipOnEmpty'=>false]
];
}
public function add_company() {
Yii::$app->db->close();
Yii::$app->db->open();
$comm = Yii::$app->db->createCommand("CALL create_company('".$this->company_name."','".$this->company_address."','".$this->admin_email."','".$this->admin_phone_number."',1)");
return $comm->execute() ;
}
}
<?php
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;
class CompanyModel extends Model
{
public $company_name;
public $company_address;
public $company_logo;
public $admin_email;
public $admin_name;
public $admin_password;
public $retype_admin_password;
public $admin_phone_number;
public function rules()
{
return [
[['company_name'], 'required'],
[['company_address'],'required'],
[['admin_name'],'required'],
[['admin_email'],'required'],
[['admin_password'],'required'],
[['retype_admin_password'],'required'],
[['admin_phone_number'],'required'],
[['company_logo'],'file','skipOnEmpty'=>false],//here the comma is missing
];
}
public function add_company() {
Yii::$app->db->close();
Yii::$app->db->open();
$comm = Yii::$app->db->createCommand("CALL create_company('".$this->company_name."','".$this->company_address."','".$this->admin_email."','".$this->admin_phone_number."',1)");
return $comm->execute() ;
}
}

Categories