Im have a problem in Yii.
Example:
There are CRUDs for Customers and for Joboffers. I want to click on a create button on the Customer-Index that redirect me to the Joboffer-Create-Form where the ID from the Employee wich i clicked on is accessable. Any tips that send me on the right way?
<?php
/* #var $this yii\web\View */
/* #var $searchModel app\models\CustomersSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
use yii\helpers\Html;
use yii\helpers\Url;
use kartik\export\ExportMenu;
use kartik\grid\GridView;
$this->title = Yii::t('app', 'Customers');
$this->params['breadcrumbs'][] = $this->title;
$search = "$('.search-button').click(function(){
$('.search-form').toggle(1000);
return false;
});";
$this->registerJs($search);
?>
<div class="customers-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a(Yii::t('app', 'Create Customers'), ['create'], ['class' => 'btn btn-success']) ?>
<?= Html::a(Yii::t('app', 'Advance Search'), '#', ['class' => 'btn btn-info search-button']) ?>
</p>
<div class="search-form" style="display:none">
<?= $this->render('_search', ['model' => $searchModel]); ?>
</div>
<?php
$gridColumn = [
'id_kunde',
[
'label' => 'Kunde',
'attribute' => 'id_kunde',
'format' => 'raw',
'value' => function($model){
if($model->webseite == "") {
return '<div>'.$model->firma.'<br>'.$model->created_at.'<br>'.$model->contactPeople->vorname.' '.$model->contactPeople->nachname.'<br>'.$model->contactPeople->geschaeftsadresse_email_1.'<br>'.$model->contactPeople->geschaeftsadresse_mobil.'</div>';
} else {
return '<div>'.$model->firma.'<br>'.Html::a('<small class="btn btn-sm btn-primary">'.$model->webseite.'</small>', $model->webseite, ['target'=>'_blank'], ['class' => 'btn btn-danger']).'<br>'.$model->contactPeople->vorname.' '.$model->contactPeople->nachname.'<br>'.$model->contactPeople->geschaeftsadresse_email_1.'<br>'.$model->contactPeople->geschaeftsadresse_mobil.'</div>';
}
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => \yii\helpers\ArrayHelper::map(\app\models\Customers::find()->asArray()->all(), 'id_kunde', 'firma'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Kunden auswählen', 'id' => 'grid-customers-search-id_ansprwechpartner']
],
[
'attribute' => 'id_mitarbeiter',
'label' => Yii::t('app', 'Id Mitarbeiter'),
'value' => function($model){
return $model->mitarbeiter->id_mitarbeiter;
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => \yii\helpers\ArrayHelper::map(\app\models\Employee::find()->asArray()->all(), 'id_mitarbeiter', 'id_mitarbeiter'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Pers tbl employee', 'id' => 'grid-customers-search-id_mitarbeiter']
],
'interner_hinweis',
['attribute' => 'lock', 'visible' => false],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{create}',
'contentOptions'=>['style'=>'width: 25px;'],
'buttons' => [
'create' => function ($url, $index, $key) {
return Html::a('<span class="glyphicon glyphicon-copy"></span>', Url::to(['joboffer/create', 'id' => $this->id_kunde]), ['title' => 'Create Joboffer']);
},
],
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '{save-as-new} {view} {update} {delete}',
'buttons' => [
'save-as-new' => function ($url) {
return Html::a('<span class="glyphicon glyphicon-copy"></span>', $url, ['title' => 'Save As New']);
},
],
],
];
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumn,
'pjax' => true,
'pjaxSettings' => ['options' => ['id' => 'kv-pjax-container-customers']],
// your toolbar can include the additional full export menu
'toolbar' => [
'{export}',
ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumn,
'target' => ExportMenu::TARGET_BLANK,
'fontAwesome' => true,
'dropdownOptions' => [
'label' => 'Full',
'class' => 'btn btn-default',
'itemsBefore' => [
'<li class="dropdown-header">Export All Data</li>',
],
],
]) ,
],
]); ?>
</div>
<?php
namespace app\controllers;
use Yii;
use app\models\Customers;
use app\models\CustomersSearch;
use app\models\Joboffer;
use app\models\JobofferSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* CustomersController implements the CRUD actions for Customers model.
*/
class CustomersController extends Controller
{
public $param = '';
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
'access' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['joboffer','index', 'view', 'create', 'update', 'delete', 'pdf', 'save-as-new', 'add-application', 'add-contact-person', 'add-job-suggestion', 'add-joboffer'],
'roles' => ['#']
],
[
'allow' => false
]
]
]
];
}
/**
* Lists all Customers models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new CustomersSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Customers model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
$model = $this->findModel($id);
$providerApplication = new \yii\data\ArrayDataProvider([
'allModels' => $model->applications,
]);
$providerContactPerson = new \yii\data\ArrayDataProvider([
'allModels' => $model->contactPeople,
]);
$providerJobSuggestion = new \yii\data\ArrayDataProvider([
'allModels' => $model->jobSuggestions,
]);
$providerJoboffer = new \yii\data\ArrayDataProvider([
'allModels' => $model->joboffers,
]);
return $this->render('view', [
'model' => $this->findModel($id),
'providerApplication' => $providerApplication,
'providerContactPerson' => $providerContactPerson,
'providerJobSuggestion' => $providerJobSuggestion,
'providerJoboffer' => $providerJoboffer,
]);
}
/**
* Creates a new Customers model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Customers();
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id_kunde]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing Customers model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
if (Yii::$app->request->post('_asnew') == '1') {
$model = new Customers();
}else{
$model = $this->findModel($id);
}
if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
return $this->redirect(['view', 'id' => $model->id_kunde]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Customers model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->deleteWithRelated();
return $this->redirect(['index']);
}
/**
*
* Export Customers information into PDF format.
* #param integer $id
* #return mixed
*/
public function actionPdf($id) {
$model = $this->findModel($id);
$providerApplication = new \yii\data\ArrayDataProvider([
'allModels' => $model->applications,
]);
$providerContactPerson = new \yii\data\ArrayDataProvider([
'allModels' => $model->contactPeople,
]);
$providerJobSuggestion = new \yii\data\ArrayDataProvider([
'allModels' => $model->jobSuggestions,
]);
$providerJoboffer = new \yii\data\ArrayDataProvider([
'allModels' => $model->joboffers,
]);
$content = $this->renderAjax('_pdf', [
'model' => $model,
'providerApplication' => $providerApplication,
'providerContactPerson' => $providerContactPerson,
'providerJobSuggestion' => $providerJobSuggestion,
'providerJoboffer' => $providerJoboffer,
]);
$pdf = new \kartik\mpdf\Pdf([
'mode' => \kartik\mpdf\Pdf::MODE_CORE,
'format' => \kartik\mpdf\Pdf::FORMAT_A4,
'orientation' => \kartik\mpdf\Pdf::ORIENT_PORTRAIT,
'destination' => \kartik\mpdf\Pdf::DEST_BROWSER,
'content' => $content,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
'cssInline' => '.kv-heading-1{font-size:18px}',
'options' => ['title' => \Yii::$app->name],
'methods' => [
'SetHeader' => [\Yii::$app->name],
'SetFooter' => ['{PAGENO}'],
]
]);
return $pdf->render();
}
/**
* Creates a new Customers model by another data,
* so user don't need to input all field from scratch.
* If creation is successful, the browser will be redirected to the 'view' page.
*
* #param type $id
* #return type
*/
public function actionSaveAsNew($id) {
$model = new Customers();
if (Yii::$app->request->post('_asnew') != '1') {
$model = $this->findModel($id);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id_kunde]);
} else {
return $this->render('saveAsNew', [
'model' => $model,
]);
}
}
/**
* Finds the Customers model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Customers the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Customers::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for Application
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddApplication()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('Application');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formApplication', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for ContactPerson
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddContactPerson()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('ContactPerson');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formContactPerson', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for JobSuggestion
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddJobSuggestion()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('JobSuggestion');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formJobSuggestion', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
/**
* Action to load a tabular form grid
* for Joboffer
* #author Yohanes Candrajaya <moo.tensai#gmail.com>
* #author Jiwantoro Ndaru <jiwanndaru#gmail.com>
*
* #return mixed
*/
public function actionAddJoboffer()
{
if (Yii::$app->request->isAjax) {
$row = Yii::$app->request->post('Joboffer');
if((Yii::$app->request->post('isNewRecord') && Yii::$app->request->post('_action') == 'load' && empty($row)) || Yii::$app->request->post('_action') == 'add')
$row[] = [];
return $this->renderAjax('_formJoboffer', ['row' => $row]);
} else {
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
}
}
You should use the function for returning the HTML code
function ($url, $model, $key) {
// return the button HTML code
}
this way
[
'class' => 'yii\grid\ActionColumn',
'template' => '{create}',
'contentOptions'=>['style'=>'width: 25px;'],
'buttons' => [
'create' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-copy"></span>',
Url::to(['joboffer/create',
'id' => $model->id_kunde]), ['title' => 'Create Joboffer']);
},
],
],
Related
I try to save many to many relations inside loop here is the code
$user = User::firstOrCreate(
[
'username' => $member->username,
'email' => $member->email
],
[
'password' => $member->password,
'name' => $member->fullname,
'email' => $member->email,
'firstname' => $member->firstname,
'lastname' => $member->lastname,
'username' => $member->username,
'active' => $member->active
]
);
if ($user) {
$user->account()->firstOrCreate([
'user_id' => $user->id,
],
[
'address' => $member->address,
'phone' => $member->phone,
'web' => $member->web,
'company' => $member->company,
'company_email' => $member->company_email,
'company_phone' => $member->company_phone,
'fax' => $member->fax,
'company_fax' => $member->company_fax,
'has_newsletter' => $member->newsletter,
'published' => $member->listing,
'zip' => $member->zip,
'association_id' => $member->association_id,
'affiliate_id' => $member->affiliate_id,
]);
if ($member->activity_group_ids) {
$user->account()->occupations()->snyc(explode(',',$member->activity_group_ids));
}
$user->assignRole('member');
}
but I keep getting Call to undefined method Illuminate\Database\Eloquent\Relations\HasOne::occupations()
my models:
User
/**
* #return HasOne
*/
public function account()
{
return $this->hasOne(Member::class);
}
Member
/**
* #return BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* #return BelongsToMany
*/
public function occupations()
{
return $this->belongsToMany(OccupationGroup::class, 'members_occupational_groups', 'member_id', 'occupation_group_id');
}
OccupationGroup
/**
* #return BelongsToMany
*/
public function members()
{
return $this->belongsToMany(Member::class, 'members_occupational_groups', 'occupation_group_id', 'member_id');
}
What is wrong in this case?
i want to add profile avatar in frontend/web/site/signup but there is an error
it said
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: frontend\models\SignupForm::save()
this is the signup.php on frontend/views/site/signup.php
<?php
/* #var $this yii\web\View */
/* #var $form yii\bootstrap\ActiveForm */
/* #var $model \frontend\models\SignupForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-signup">
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the following fields to signup:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-signup'],['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'first_name')->textInput(['placeholder' => "First Name"]) ?>
<?= $form->field($model, 'last_name')->textInput(['placeholder' => "Last Name"]) ?>
<?= $form->field($model, 'username')->textInput(['placeholder' => "Username"]) ?>
<?= $form->field($model, 'email')->textInput(['placeholder' => "Email"]) ?>
<?= $form->field($model, 'password')->passwordInput(['placeholder' => "Password"]) ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
this is the SiteController.php
<?php namespace frontend\controllers;
use Yii; use yii\base\InvalidParamException; use yii\web\BadRequestHttpException; use yii\web\Controller; use yii\web\UploadedFile; use yii\filters\VerbFilter; use yii\filters\AccessControl; use common\models\LoginForm; use frontend\models\PasswordResetRequestForm; use frontend\models\ResetPasswordForm; use frontend\models\SignupForm; use frontend\models\ContactForm;
/** * Site controller */ class SiteController extends Controller {
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'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,
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* #return mixed
*/
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 {
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logs out the current user.
*
* #return mixed
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* #return mixed
*/
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 your message.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
/**
* Displays about page.
*
* #return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
/**
* Signs user up.
*
* #return mixed
*/
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
//upload file
$path = Yii::getAlias('#frontend') .'/web/upload/';
$imageName = $model->username;
$model->file = UploadedFile::getInstance($model,'file');
$model->file->saveAs( 'uploads/img/user'.$imageName.'.'.$model->file->extension );
$model->file->saveAs( $path.$imageName.'.'.$model->file->extension );
//save in database
$model->avatar = 'uploads/'.$imageName.'.'.$model->file->extension;
$model->save();
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}else{
return $this->render('signup', [
'model' => $model,
]);
}
}
/**
* Requests password reset.
*
* #return mixed
*/
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
/**
* Resets password.
*
* #param string $token
* #return mixed
* #throws BadRequestHttpException
*/
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->session->setFlash('success', 'New password saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
} }
<?php
namespace frontend\controllers;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
/**
* Site controller
*/
class SiteController extends Controller
and this is the SignupForm.php on frontend/models/SignupForm.php
<?php
namespace frontend\models;
use yii\base\Model;
use common\models\User;
/**
* Signup form
*/
class SignupForm extends Model
{
public $first_name;
public $last_name;
public $username;
public $email;
public $password;
public $avatar;
public $file;
/**
* #inheritdoc
*/
public function rules()
{
return [
['first_name', 'required'],
['last_name', 'required'],
[['file'],'file', 'extensions'=>'jpg, gif, png'],
['username', 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
/**
* Signs user up.
*
* #return User|null the saved model or null if saving fails
*/
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->first_name = $this->first_name;
$user->first_name = $this->first_name;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->avatar = $this->file;
return $user->save() ? $user : null;
}
}
In your controller SiteController, in action actionSignup() youre using:
$model->save()
Your model doesn't extends ActiveRecord class, so it don't have method save().
Remove this $model->save() from controller, youre saving user anyway in method signup().
I am using ajax validation for unique field and it's not working.
In my usercontroller it works but in this sitecontroller doesn't.
Can anyone help me for this?
This is my Controller
<?php
namespace frontend\controllers;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\User;
use frontend\models\UserSeacrh;
use frontend\models\ContactForm;
use yii\widgets\ActiveForm;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* Displays homepage.
*
* #return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* #return mixed
*/
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 {
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Displays contact page.
*
* #return mixed
*/
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,
]);
}
}
/**
* Displays about page.
*
* #return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
/**
* Signs user up.
*
* #return mixed
*/
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 actionValidation()
{
$model = new User();
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
{
Yii::$app->response->format = 'json';
return ActiveForm::validate($model);
}
}
/**
* Requests password reset.
*
* #return mixed
*/
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
/**
* Resets password.
*
* #param string $token
* #return mixed
* #throws BadRequestHttpException
*/
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->session->setFlash('success', 'New password was saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
}
This is my model
<?php
namespace frontend\models;
use Yii;
/**
* This is the model class for table "user".
*
* #property integer $id
* #property string $username
* #property string $name
* #property string $lastname
* #property string $email
* #property integer $phone
* #property string $notes
* #property string $company
* #property string $password_hash
* #property string $auth_key
* #property integer $status
* #property integer $created_at
* #property integer $updated_at
* #property string $country
* #property string $state
* #property string $city
* #property string $language
* #property integer $salary
* #property string $hiredate
* #property string $birthday
* #property string $address
* #property string $dismission
*/
class User extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'user';
}
public function fields()
{
return [
'id','status'
];
}
/**
* #inheritdoc
*/
public function rules()
{
return [
['username', 'unique'],
[['username', 'name', 'lastname', 'email', 'phone', 'password_hash'], 'required'],
[['phone', 'status', 'created_at', 'updated_at', 'salary'], 'integer'],
[['hiredate', 'birthday', 'dismission'], 'safe'],
[['username', 'name', 'lastname', 'email', 'notes', 'company', 'password_hash', 'auth_key', 'country', 'state', 'city', 'language', 'address'], 'string', 'max' => 100],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'name' => 'Name',
'lastname' => 'Lastname',
'email' => 'Email',
'phone' => 'Phone',
'notes' => 'Notes',
'company' => 'Company',
'password_hash' => 'Password Hash',
'auth_key' => 'Auth Key',
'status' => 'Status',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'country' => 'Country',
'state' => 'State',
'city' => 'City',
'language' => 'Language',
'salary' => 'Salary',
'hiredate' => 'Hiredate',
'birthday' => 'Birthday',
'address' => 'Address',
'dismission' => 'Dismission',
];
}
}
This is my view
<?php
/* #var $this yii\web\View */
/* #var $form yii\bootstrap\ActiveForm */
/* #var $model \frontend\models\SignupForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\helpers\ArrayHelper;
use frontend\models\Countries;
use frontend\models\States;
use frontend\models\Cities;
use yii\helpers\Url;
$this->title = 'Signup';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-signup">
<h1><?= Html::encode($this->title) ?></h1>
<p>Please fill out the following fields to signup:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'enableAjaxValidation' => true, 'validationUrl' => Url::toRoute('site/validation')]); ?>
<?= $form->field($model, 'username')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'name')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'lastname')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'phone')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'company')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'password_hash')->passwordInput()->label('Password') ?>
<?= $form->field($model, 'country')->dropDownList(ArrayHelper::map(Countries::find()->all(),'id','name'),
[
'prompt' => 'Страна',
'onchange' => '
$.post( "../states/lists?id='.'"+$(this).val(), function( data ) {
$( "select#signupform-state" ).html( data );
});'
]); ?>
<?= $form->field($model, 'state')->dropDownList([],
[
'prompt' => 'Регион',
'onchange' => '
$.post( "../cities/lists?id='.'"+$(this).val(), function( data ) {
$( "select#signupform-city" ).html( data );
});'
]); ?>
<?= $form->field($model, 'city')->dropDownList([],[ 'prompt' => 'Город' ]); ?>
<?= $form->field($model, 'language')->dropDownList([
'1' => 'Русский',
'2' => 'English',
'3' => 'Turkce',
]); ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
SiteController.php
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return \yii\bootstrap\ActiveForm::validate($model);
}
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
SignUpForm.php
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 255],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
];
}
/**
* Signs user up.
*
* #return User|null the saved model or null if saving fails
*/
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
}
signup.php
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'enableAjaxValidation' => true]); ?>
Ajax validation is not triggered, need help finding what is wrong with my code, struggle took long enough to make me seek help here so please help. There is some commented code, that was used while trying to make it work. Getting 500 internal server error:
{"name":"Exception","message":"Attribute name must contain word
characters only."
UserController
public function actionRegister()
{
$model = new Users();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
$model->scenario = 'ajax';
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::error($model);
$model->validate();
return ActiveForm::validate($model);
//both ways not working the way it should
//return $model->validate();
}
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->register()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('register', [
'model' => $model,
]);
}
register.php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
<?php $form = ActiveForm::begin(['id' => 'form-signsup',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
'id' => 'ajax'
]); ?>
<?= $form->field($model, 'UserName') ?>
<?= $form->field($model, 'Name', ['enableAjaxValidation' => true]) ?>
<?= $form->field($model, 'LastName', ['enableAjaxValidation' => true]) ?>
<?= $form->field($model, 'Email') ?>
<?= $form->field($model, 'PasswordHash', ['enableAjaxValidation' => true])->passwordInput() ?>
<?= $form->field($model, 'repeatPassword', ['enableAjaxValidation' => true])->passwordInput() ?>
<?= Html::submitButton('Register', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
Users.php
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\base\Model;
use yii\web\Response;
use yii\widgets\ActiveForm;
class Users extends ActiveRecord implements IdentityInterface
{
public $rememberMe;
public $repeatPassword;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'users';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['UserName', 'PasswordHash', 'Name', 'LastName', 'Email'], 'required'],
[['Name', 'LastName'], 'validateLetters', 'skipOnError' => false, 'on'=>'ajax'],
[['repeatPassword'], 'validatePasswordRepeat', 'skipOnEmpty' => false, 'on'=>'ajax'],
[['IsEnabled'], 'boolean'],
[['rememberMe'], 'boolean'],
[['UserName', 'Name', 'LastName'], 'string', 'max' => 50],
[['Email'], 'email', 'message'=>'Netinkamai įvestas el. paštas.'],
[['PasswordHash', 'repeatPassword' ], 'string', 'max' => 20],
[['Email'], 'string', 'max' => 80]
];
}
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['ajax'] = ['Name', 'LastName', 'repeatPassword', 'PasswordHash'];//Scenario Values Only Accepted
//$scenarios['default'] = ['Name','LastName', 'passwordRepeat', 'PasswordHash', 'Email'];
return $scenarios;
// return [
// ['some_scenario' => ['UserName', 'PasswordHash', 'Name', 'LastName', 'Email', 'IsEnabled']],
// ];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'Id' => 'ID',
'UserName' => 'Prisijungimo vardas',
'PasswordHash' => 'Slaptažodis',
'Name' => 'Vardas',
'LastName' => 'Pavardė',
'Email' => 'El. paštas',
'IsEnabled' => 'Is Enabled',
'rememberMe' => 'Prisiminti?',
'AuthKey' => 'Authentication key',
'repeatPassword' => 'Pakartoti slaptažodį',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUserRoles()
{
return $this->hasMany(UserRole::className(), ['User_ID' => 'Id']);
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePasswordRepeat($attribute)
{
//if(!($this->$attribute == $this->PasswordHash)){
// $this->clearErrors();
$this->addError($this->repeatPassword, 'Slaptažodis nesutampa.');
return $this->addError($this->repeatPassword, 'Slaptažodis nesutampa.');
// }
//$this->addError($attribute, 'Slaptažodis nesutampa.');
// return Yii::$app->security->validatePassword($attribute, $this->PasswordHash);
//return Yii::$app->security->validatePassword($attribute, $this->PasswordHash);
}
/**
* Validates name / last name string so it has no numbers or random symbols
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validateLetters($attribute)
{
Yii::error($attribute);Yii::error($this->$attribute);
if(!preg_match('/^[a-zA-ZąčęėįšųūžĄČĘĖĮŠŲŪŽ]+$/', $this->$attribute)){
$this->addError($attribute, 'Galima naudoti tik raides.');
}
}
public function register()
{
if ($this->validate()) {
$user = new Users();
$user->UserName = $this->UserName;
$user->Email = $this->Email;
$user->Name = $this->Name;
$user->LastName = $this->LastName;
$user->setPassword($this->PasswordHash);
if ($user->save()) {
return $user;
}
}
// var_dump($user->getErrors()); die();
}
public function login()
{
// $user = $this->getUser();
//var_dump($user);
//echo "----------------------";
//$this->PasswordHash = md5($this->PasswordHash);
//var_dump($this->PasswordHash);
// die();
// if ($this->validate()) {
// $this->PasswordHash = md5($this->PasswordHash);
// return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
// } else {
// return false;
// }
if ($this->validate()) {
//die();
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
} else {
return false;
}
}
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id]);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($UserName)
{
return static::findOne(['UserName' => $UserName]);
}
/**
* Finds user by password reset token
*
* #param string $token password reset token
* #return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* #param string $token password reset token
* #return boolean
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int) end($parts);
return $timestamp + $expire >= time();
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->AuthKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Generates password hash from password and sets it to the model
*
* #param string $password
*/
public function setPassword($password)
{
$this->PasswordHash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->AuthKey = Yii::$app->security->generateRandomString();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
Hey your code is fine but your mistake is that you provide two id for single form one is form-signsup and ajax. try using only one...:)
<?php $form = ActiveForm::begin(['id' => 'form-signsup',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
//'id' => 'ajax'
]); ?>
In your register.php change the line:
And set it true, and that's it, hope it was helpful 'form-signsup',
'enableAjaxValidation' => 'true',
]); ?>
<?= $form->field($model, 'UserName') ?>
<?= $form->field($model, 'Name') ?>
<?= $form->field($model, 'LastName') ?>
<?= $form->field($model, 'Email') ?>
<?= $form->field($model, 'PasswordHash')->passwordInput() ?>
<?= $form->field($model, 'repeatPassword')->passwordInput() ?>
<?= Html::submitButton('Register', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
I found that AJAX Validation required:
use yii\widgets\ActiveForm;
To be at the top of both the form and the controller.
Diving into this new yii 2 and Im already stuck. Im trying update a user record with a form. The original record is loading in the form, but changing the values in the form is not updating the record.
public function actionUserprofile()
{
$id = Yii::$app->user->identity->id;
$model = User::find()->where(['id' => $id])->one();
if($model->load(Yii::$app->request->post()) && $model->save())
{
Yii::$app->session->setFlash('success','You have updated your profile.');
}
return $this->render('userProfile', [
'model' => $model,
]);
}
//view form
<div>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'first_name')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'last_name')->textInput(['maxlength' => 255]) ?>
<div class="form-group">
<?= Html::submitButton('Submit',['class'=>'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
If you use User model like this https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php
You may create class Profile like that:
<?php
namespace frontend\models;
use common\models\User;
use yii\base\Model;
use Yii;
/**
* Signup form
*/
class Profile extends Model
{
public $username;
public $first_name;
public $last_name;
/**
* #inheritdoc
*/
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
[['first_name', 'last_name'], 'filter', 'filter' => 'trim'],
[['first_name', 'last_name'], 'required'],
[['first_name', 'last_name'], 'string', 'max' => 255],
];
}
/**
* Signs user up.
*
* #return User|null the saved model or null if saving fails
*/
public function profileSave()
{
if ($this->validate()) {
$user = User::findOne(Yii::$app->user->id);
$user->username = $this->username;
$user->first_name = $this->first_name;
$user->last_name = $this->last_name;
if ($user->save()) {
return $user;
}
}
return null;
}
}
And change in controller
$model = User::find()->where(['id' => $id])->one();
if($model->load(Yii::$app->request->post()) && $model->save())
to
$model = new Profile();
if($model->load(Yii::$app->request->post()) && $model->profileSave())