Dropdownlist Field Form not saved in DB - forms

I'm new in Yii2 Framework. I have a problem, I'm trying to make register form but after register, the role is not saved to database.
This is the form.
This is my table for role:
This is the view code, register.php:
<h2>Sign Up : </h2>
<div class="user-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($model, 'user_kind')->dropdownList(
ArrayHelper::map(CtKindUser::find()->all(), 'id','kindUser'), [
'prompt' => 'Choose Category',]); ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-primary' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
This is the controller.
public function actionRegister()
{
$model = new User();
$modelLogin = new LoginForm();
if($modelLogin->load(Yii::$app->request->post())&& $modelLogin->login()){
return $this->goHome();
}
if ($model->load(Yii::$app->request->post())) {
$model->id = $model->generateRandomString();
$hash = Yii::$app->getSecurity()->generatePasswordHash($model->password);
$model->password = $hash;
$model->activated = 1;
$model->createdAt = date("Y-m-d").' '.date("h:i:s a");
$model->user_kind = '';
$model->save();
return $this->redirect(['/site/index']);
// return $this->redirect(['/site/index']);
} else {
return $this->render('register', [
'model' => $model,
'modelLogin' => $modelLogin,
]);
}
And this is the models.
public function rules()
{
return [
[['username', 'email', 'password'], 'required'],
[['activated'], 'integer'],
[['profile_name'], 'string', 'max' => 250],
[['id', 'user_kind'], 'string', 'max' => 35],
[['username', 'email'], 'string', 'max' => 50],
[['createdAt', 'updatedAt'], 'string', 'max' => 30],
[['user_kind'], 'string', 'max' => 45],
[['user_kind'], 'exist', 'skipOnError' => true, 'targetClass' => CtKindUser::className(), 'targetAttribute' => ['user_kind' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => 'Username',
'profile_name' => '',
'email' => 'Email',
'password' => 'Password',
'category' => 'Category',
'createdAt' => 'Created At',
'updatedAt' => 'Updated At',
'activated' => 'Activated',
'user_kind' => 'Jenis Pengguna',
];
}
public function getUserKind()
{
return $this->hasOne(CtKindUser::className(), ['id' => 'user_kind']);
}
Someone, can help me. What is actually the problem?
Thanks.

Check how you are sending your dropdownList:
<?= $form->field($model, 'user_kind')->dropdownList(['1' =>'Event Organizer', '2' =>'Tenant'],['prompt'=>'Select Category'])?>
with the values of 1 and 2 and on your contoller:
if ($model->user_kind =='Event Organizer' || $model->user_kind =='Osjfnas8sjaasnaskfowlkvmssjswT' )
you are comparing with some values that never will be send 'Event Organizer' and 'Osjfnas8sjaasnaskfowlkvmssjswT'

Related

Yii2 Basic Clear input form after submit button

I created a modal to create post and another one to create gallery inside another view and it work perfect but after I click submit my form keeps the data entered even if I refresh the page it's still have the data entered, is it possible to clear form after submit
My view code of post is :
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $ly_addPost app\models\Posts */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="posts-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($ly_addPost, 'Post_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($ly_addPost, 'Post_text')->textarea(['rows' => 6]) ?>
<?= $form->field($ly_addPost, 'Post_file')->textInput(['maxlength' => true]) ?>
<?= $form->field($ly_addPost, 'Permission_id')->dropdownList([$ly_addPost->Permission_id]);?>
<div class="form-group">
<?= Html::submitButton('Create' , ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My controller has two create from from two different view one for post and another one for gallery
my controller code is :
public function actionView($id)
{
$ly_addPost = new Posts();
$ly_addGallery = new Galleries();
//$ly_addAudio = new Audios();
//$ly_addVideo = new Videos();
$ly_addPost->Channel_id = $id;
$ly_addGallery->Channel_id = $id;
$ly_addPost->Userid = Yii::$app->user->id;
$ly_addGallery->Userid = Yii::$app->user->id;
// for permission post
$ly_addPost->Permission_id = Permission::find()
->select(['Permission_type'])
->indexBy('Permission_id')
->column();
// for permission galery
$ly_addGallery->Permission_id = Permission::find()
->select(['Permission_type'])
->indexBy('Permission_id')
->column();
if ($ly_addPost->load(Yii::$app->request->post()) ) {
$ly_addPost->Post_id = Yii::$app->params['ly_randCttid'];
$ly_addPost->Post_uid = Yii::$app->params['ly_randCttid'];
$ly_addPost->save();
return $this->render('view', [
'model' => $this->findModel($id),
'ly_addPost' => $ly_addPost,
'ly_addGallery' => $ly_addGallery,
]);
exit();
}
else if ($ly_addGallery->load(Yii::$app->request->post()) ) {
$ly_addGallery_id = Yii::$app->params['ly_randCttid'];
$ly_addGallery_uid = Yii::$app->params['ly_randCttid'];
$ly_addGallery->save();
return $this->render('view', [
'model' => $this->findModel($id),
'ly_addPost' => $ly_addPost,
'ly_addGallery' => $ly_addGallery,
]);
exit();
} else {
return $this->render('view', [
'model' => $this->findModel($id),
'ly_addPost' => $ly_addPost,
'ly_addGallery' => $ly_addGallery,
]);
}
}
you have to clear $ly_addPost before rendering
} else {
foreach ($ly_addPost as $key => $value) {
$ly_addPost->$key = null; //set to null instead of unsetting
} // this foreach clear all variable of $ly_addPost;
return $this->render('view', [
'model' => $this->findModel($id),
'ly_addPost' => $ly_addPost,
'ly_addGallery' => $ly_addGallery,
]);
}
I fixed by changing
return $this->render('view', [
'model' => $this->findModel($id),
'ly_addPost' => $ly_addPost,
'ly_addGallery' => $ly_addGallery,
]);
exit();
To
return $this->refresh();
Now my code in controller is
if ($ly_addPost->load(Yii::$app->request->post()) ) {
$ly_addPost->Post_id = Yii::$app->params['ly_randCttid'];
$ly_addPost->Post_uid = Yii::$app->params['ly_randCttid'];
$ly_addPost->save();
return $this->refresh();
}

cakephp 2 validation error messages do not display

here is my model
Contacts.php
<?php
App::uses('AppModel', 'Model');
App::uses('Validation', 'Utility');
/**
* Base Application model
*
* #package Croogo
* #link http://www.croogo.org
*/
//$validate = new Validator();
// 'alphaNumeric' => array(
// 'required' => true,
// 'allowEmpty' => false,
class Contacts extends AppModel {
var $name = 'Contacts';
var $useTable = false;
var $validate = array(
'ContactsAddress' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'The address is required'),
'ContactsEmail' => array(
'rule' => array('email', true),
'required' => true,
'message' => 'A valid email is required'
),
'ContactsPhone' => array(
'rule' => array('phone', null, 'us'),
'message' => 'A valid phone numbe is required'
)
);
//}
}
ContactsController.php
App::uses('AppController', 'Controller');
App::uses('Validation', 'Utility');
class ContactsController extends AppController {
public $helpers = array('Form', 'Html', 'Session', 'Js', 'Time');
public $uses = array('Contacts');
/**
* This controller does not use a model
*
* #var array
*/
//public $uses = array();
//public $uses = array('Contact');
//use Cake\Validation\Validator;
/**
* Displays a view
*
* #return void
* #throws NotFoundException When the view file could not be found
* or MissingViewException in debug mode.
*/
public function index() {
$this->Contacts->set($this->request->data);
if($this->request->is('post')) {
//if ($this->Contact->validation()) {
if ($this->Contacts->validates()) {
// return
$this->Contacts->save();
$this->redirect('/contacts/confirm');
} else {
CakeLog::write('debug', 'ErrorCheck');
// $errors = $this->Contacts->validationErrors;
//$this->Session->setflash($this->Contacts->validationErrors);
//$this->redirect('/contacts');
//CakeLog::write('debug', $errors['ContactsAddress'][0]);
// Debugger::dump($errors);
}
}
}
the view file
index.ctp
<!--Navigation Background Part Starts -->
<div id="navigation-bg">
<!--Navigation Part Starts -->
<div id="navigation">
<ul class="mainMenu">
<li>Home</li>
<li>About</li>
<li class="noBg">Contact</li>
</ul>
<br class="spacer" />
</div>
<!--Navigation Part Ends -->
</div>
<div id="ourCompany-bg">
<div class="requestForm">
<p class="formHeader">Meeting Location</p>
<?php echo $this->Form->create(false); ?>
<!--, array('url' => false)-->
<!-- array('action' => 'confirm'))); ?> -->
<?php //echo $this->Form->create(false, array('url' => array('action' => 'index'))); ?>
<?php $today = date('d')+1; ?>
<?php $formmonth = date('m'); ?>
<?php echo $this->Form->input('name', array(
'label' => array('text' => 'Name: '))); ?>
<span class="errorMessage"> <?php //echo $this->validationErrors['Contacts']['ContactsAddress'][0];?></span>
<?php echo $this->Form->input('address', array(
'label' => array('text' => 'Address of meeting: '))); ?>
<?php CakeLog::write('debug', $this->validationErrors['Contacts']['ContactsAddress'][0]); ?>
as you can see i have been trying a lot of different things. I have been trying to figure this out for a couple of weeks with no progress.
I would appreciate any light that someone could shed on my delimma
apparently one of the most significant factors is having the model name as the first attribute in Form->create. Since i did not want to post to a database I used false which i mistakenly thought meant no SQL update. Once i put the model name as the first attribute it worked as documented. The way to validate with no database is to put $userTable=false in the model.
Hope this helps somebody.

how to redirect to the same page after loging in from that page in cakephp 3.0

this is my login method in UsersController.php
public function login()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
$auth = $this->Auth->identify();
if ($auth) {
$this->Auth->setUser($auth);
//return $this->redirect($this->Auth->redirectUrl());
return $this->redirect(['controller' => 'Blogs', 'action' => 'index']);
}
$this->Flash->error(__('Invalid credentials.'));
}
$this->set(compact('user'));
}
In AppController.php
public function beforeFilter(Event $event)
{
/*if($this->here != '/users'){
$this->Session->write('Auth.redirect', $this->here);
} */
$this->Auth->allow(['controller' => 'Blogs','action' => 'index', 'view']);
}
I am new to cakephp. please someone help me. thank you
this is my controller
public function login()
{
//print_r($this->request->data);
echo $lasturl=Router::url( $this->here, true ); //login from view page starts here
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
$auth = $this->Auth->identify();
if ($auth) {
$this->Auth->setUser($auth);
$this->redirect($this->request->data['lasturl']);
//return $this->redirect(['controller' => 'Blogs', 'action' => 'index']);
//return $this->redirect($this->request->session()->read($lasturl));
}
}
$this->set(compact('user'));
}
this is my view file
<div class="login_comment">
<?= $this->Flash->render('auth') ?>
<?php echo $this->Form->create('Users', array('url' => array('controller' => 'Users', 'action' => 'login')));
?>
<fieldset>
<legend><?= __('Please Login to Comment for this Post') ?></legend>
<?= $this->Form->input('username') ?>
<?= $this->Form->input('password') ?>
<?= $this->Form->input('lasturl',array('type'=>'hidden','value'=>$lasturl)) ?>
</fieldset>
<?= $this->Form->button(__('Login')); ?>
<?= $this->Form->end() ?>
You can add loginRedirect Auth component config in AppController.php
$this->loadComponent('Auth', [
'authorize' => ['Controller'], // Added this line
'loginRedirect' => [
'controller' =>Blogs',
'action' => 'index'
]
]);
It should work now.
fOR details you can check
Auth config

Yii2 multiple forms in a single action

Which is the right way to handle multiple forms in a single action?
Here is my models/MembersBans.php
<?php
namespace app\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use app\models\Members;
class MembersBans extends \yii\db\ActiveRecord {
public $username;
public static function tableName() {
return '{{%members_bans}}';
}
public static function primaryKey() {
return array('ban_id');
}
public function behaviors() {
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'date_added',
'updatedAtAttribute' => 'last_updated',
],
];
}
public function rules() {
return [
[['ban_id', 'ban_memberid', 'date_added', 'last_updated'], 'integer'],
[['username', 'end_date'], 'safe'],
['end_date', 'date', 'format' => 'yyyy-mm-dd'],
[['ban_ip'], 'string', 'max' => 40],
[['reason'], 'string', 'max' => 255]
];
}
public function attributeLabels() {
return [
'ban_id' => Yii::t('app', 'ID на бана'),
'ban_memberid' => Yii::t('app', 'Потребителско ID'),
'username' => 'Потребителско име',
'ban_ip' => Yii::t('app', 'IP адрес'),
'end_date' => Yii::t('app', 'Дата на изтичане'),
'reason' => Yii::t('app', 'Причина за бана'),
'date_added' => Yii::t('app', 'Дата на добавяне'),
];
}
public function getMemberBans() {
$bans = $this->find()->where('ban_memberid');
return $bans;
}
public function getIpBans() {
$bans = $this->find()->where('ban_ip');
return $bans;
}
public function getMember() {
return $this->hasOne(Members::className(), ['member_id' => 'ban_memberid']);
}
public function banMember() {
$memberInfo = Members::findByUsername($this->username);
if ($memberInfo) {
$this->ban_memberid = $memberInfo->member_id;
if ($this->save()) {
Yii::$app->session->setFlash('alert-success', 'Потребителят беше успешно блокиран.');
} else {
Yii::$app->session->setFlash('alert-error', 'Възникна грешка при блокирането на потребителя.');
}
} else {
Yii::$app->session->setFlash('alert-error', 'Не съществува потребител с това потребителско име.');
}
}
public function banIp() {
if ($this->save()) {
Yii::$app->session->setFlash('alert-success', 'IP адресът беше успешно блокиран.');
} else {
Yii::$app->session->setFlash('alert-error', 'Възникна грешка при блокирането на IP адреса.');
}
}
}
My controllers/MembersBansController.php:
public function actionList() {
$membersBans = new MembersBans();
if ($membersBans->load(Yii::$app->request->post('banMember'))) {
$membersBans->banMember();
}
if ($membersBans->load(Yii::$app->request->post('banIp'))) {
$membersBans->banIp();
}
return $this->render('list', [
'membersBans' => $membersBans,
]);
}
views/members-bans/list:
<div class="the-box">
<?php
$activeForm = ActiveForm::begin([
'id' => 'banMember',
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'validateOnSubmit' => true,
'validateOnChange' => true,
'validateOnType' => true,
])
?>
<?= $activeForm->field($membersBans, 'username', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете потребителско име']);
?>
<?= $activeForm->field($membersBans, 'end_date', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control datepicker', 'placeholder' => 'Въведете период на бана']);
?>
<?= $activeForm->field($membersBans, 'reason', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете причина за бана']);
?>
<div class="form-group">
<?= Html::submitButton('Добави', ['type' => 'submit', 'class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end()?>
</div>
<div class="the-box">
<?php
$activeForm = ActiveForm::begin([
'id' => 'banIp',
'enableClientValidation' => true,
'enableAjaxValidation' => true,
'validateOnSubmit' => true,
'validateOnChange' => true,
'validateOnType' => true,
])
?>
<?= $activeForm->field($membersBans, 'ban_ip', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете IP адрес или цяла мрежа']);
?>
<?= $activeForm->field($membersBans, 'end_date', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control datepicker', 'placeholder' => 'Въведете период на бана']);
?>
<?= $activeForm->field($membersBans, 'reason', [
'template' => '{label}{input}{hint}{error}'
])->textInput(['class' => 'form-control', 'placeholder' => 'Въведете причина за бана']);
?>
<div class="form-group">
<?= Html::submitButton('Добави', ['type' => 'submit', 'class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end() ?>
</div>
And it doesn't seem to work. Any ideas?
Id in ActiveForm does't mean id in $_POST. You should use:
$membersBans->load(Yii::$app->request->post())
or
$membersBans->load(Yii::$app->request->post('MembersBans'))
for load attributes from form.
For example multiple forms from CeBe (http://www.yiiframework.com/forum/index.php/topic/53935-solved-subforms/page__p__248184#entry248184)
public function actionCreate()
{
$user = new User;
$profile = new Profile;
if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && Model::validateMultiple([$user, $profile])) {
$user->save(false); // skip validation as model is already validated
$profile->user_id = $user->id; // no need for validation rule on user_id as you set it yourself
$profile-save(false);
return $this->redirect(['view', 'id' => $user->id]);
} else {
return $this->render('create', [
'user' => $user,
'profile' => $profile,
]);
}
}
In your action you use one model. I think you should extends MembersBans to MembersBansIp class. And your action:
public function actionList() {
$membersBans = new MembersBans();
$membersBansIp = new MembersBansIp();
if ($membersBans->load(Yii::$app->request->post())) {
$membersBans->banMember();
}
if ($membersBansIp->load(Yii::$app->request->post())) {
$membersBansIp->banIp();
}
return $this->render('list', [
'membersBans' => $membersBans,
'membersBansIp' => $membersBansIp,
]);
}
In view:
<?php
$activeForm = ActiveForm::begin([
'id' => 'banMember',
])
?>
<?= $activeForm->field($membersBans, 'fieldMembersBans') ?>
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>
<?php
$activeForm = ActiveForm::begin([
'id' => 'banMemberIp',
])
?>
<?= $activeForm->field($membersBansIp, 'usernameMembersBansIp') ?>
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>
EDIT
I put your code. He is work. https://yadi.sk/i/y7PkwGUPekjPD https://yadi.sk/i/h8dCYQz3ekk2B
But I change controller to this
$membersBans = new MembersBans();
if ($membersBans->load(Yii::$app->request->post())) {
$membersBans->banMember();
}
if ($membersBans->load(Yii::$app->request->post())) {
$membersBans->banIp();
}
And in model change Members to User, because I have not Members objects:
$memberInfo = User::findByUsername($this->username);
if ($memberInfo) {
$this->ban_memberid = $memberInfo->id;
Resume: your code is worked. Change controller, how I written up.

Register form doesn't work

I got RegisterController.php and inside of it I got:
class RegisterController extends AppController {
public $name = 'Register';
public $components = array('Session');
public function index() {
if ($this->request->is('account')) {
// if ($this->Post->save($this->request->data)) {
echo "got it";
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
// }
}
}
}
My /View/Register/index.tcp file:
<?php
echo $this->Form->create('Account');
echo $this->Form->input('username');
echo $this->Form->input('password');
$options = array(
'label' => 'Register',
'class' => 'submit'
);
echo $this->Form->end($options);
?>
And my /Model/Account.php file:
<?php
class Account extends AppModel {
public $name = 'Account';
public $validate = array(
'username' => array(
'rule' => 'notEmpty'
),
'password' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Can not be empty.'
),
'minLength' => array(
'rule' => array('minLength', '8'),
'message' => 'Min. 8 chars.'
)
)
);
}
?>
The problem is that, I'm clicking on the submit button, and nothing happends. It should at least check for validation.
Where is the error?
Should work if you add the action in options:
echo $this->Form->create('Account', array('action' => 'your/url'));