Yii2 Basic Clear input form after submit button - forms

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();
}

Related

CodeIgniter 4: Call to member function on null where post request is valid in var_dump()

** Very new to CodeIgniter so please be kind! **
I have an issue with my two user authentication forms: users/register.php and users/login.php where I cannot pass the post input to functions in my model.
As of now, I'm getting the error Call to member function addUser() on null on the registration form and a validation error on the login form that states the username/password don't match any credentials in the database. Both seem to stem from post being null although it is not.
I have done a var_dump on $login which is defined as $login = $this->request->getPost() as well as inspected the request in Firefox Developers Browser to find all the post data correctly displayed. I am stumped. Why can't I pass this array to my model?
Here is a screenshot of the post request for login.php (the same can be said for registration.php and is not included).
These are my routes:
// Login and Registration
$routes->match(['get', 'post'], 'users/register', 'Users::register');
$routes->match(['get', 'post'], 'users/login', 'Users::login', ["filter" => "noauth"]);
Here is my model UserModel.php in its entirety:
class UserModel extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'username';
protected $useAutoIncrement = false;
protected $insertID = 0;
protected $returnType = 'object';
protected $useSoftDelete = false;
protected $allowedFields = [
'username',
'password',
'id',
'role',
'profile_image',
'profile_views',
'last_login',
'about_me',
'age',
'gender',
'occupation',
'hometown',
'country',
'fav_shape',
'fav_color',
'created',
'modified',
];
// Dates
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created';
protected $modifiedField = 'modified';
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = ['beforeInsert'];
public function __construct()
{
parent::__construct();
}
protected function beforeInsert(array $data)
{
$data = $this->passwordHash($data);
return $data;
}
protected function passwordHash(array $data)
{
if (isset($data['password'])) {
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
}
return $data;
}
public function lastLogin($username)
{
$this->builder()
->where('username', $username)
->update('last_login', date('Y-m-d H:i:s'));
}
public function addUser($newUser)
{
$builder = $this->builder()
->set($newUser)
->insert();
if ($builder->affected_rows() == 1) {
return TRUE;
} else {
return FALSE;
}
}
public function getUser($username)
{
$builder = $this->builder()
->where(['username' => $username])
->limit(1);
if ($builder->countAllResults() === 1) {
return $builder->get()->getRow();
} else {
return FALSE;
}
}
}
Here are excerpts from my controller Users.php:
class Users extends BaseController
{
protected $userModel;
public function __construct()
{
$userModel = new UserModel();
}
public function login()
{
$validation = \Config\Services::validation();
// Set session variable
$session = session();
if ($this->request->getMethod() === 'post' && ! empty($_POST)) {
$validation->getRuleGroup('login');
$validation->setRuleGroup('login');
$validation->withRequest($this->request)->run();
$recaptchaResponse = trim($this->request->getVar('g-recaptcha-response'));
$userIp = $this->request->getIPAddress();
$secret = env('recaptcha2_secretkey');
$credential = [
'secret' => $secret,
'response' => $recaptchaResponse,
'remoteip' => $userIp,
];
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($verify, CURLOPT_POST, TRUE);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($credential));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($verify);
$status = json_decode($response, TRUE);
curl_close($verify);
if (empty($validation->getErrors()) && $status['success']) {
$login = $this->request->getPost();
$user = $this->userModel->getUser($login['username']);
// Storing session values
$this->setUserSession($user);
// Storing success message
$session->setFlashdata('success', 'You have successfully logged in!');
// Update last login datetime
$this->userModel->lastLogin($login['username']);
// Redirecting to dashboard after login
if ($user['role'] == 1) {
return redirect()->to('admin/dashboard');
} elseif ($user['role'] == 0) {
return redirect()->to('members/dashboard');
}
} else {
$data = [
'title' => 'Login',
'errors' => $validation->getErrors(),
];
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
}
} else {
$data = [
'title' => 'Login',
];
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
}
}
/**
* Sets session with user id, username, isLoggedIn, and role for use in member/admin site
* #param model user data
* #return boole if session was set successfully
*/
private function setUserSession($user)
{
$data = [
'id' => $user->id,
'username' => $user->username,
'profile_image' => $user->profile_image,
'isLoggedIn' => true,
'role' => $user->role,
];
if (session()->set($data)) {
return true;
} else {
return false;
}
}
public function register()
{
$validation = \Config\Services::validation();
if ($this->request->getMethod() == 'post' && ! empty($_POST)) {
$validation->getRuleGroup('registration');
$validation->setRuleGroup('registration');
$validation->withRequest($this->request)->run();
if (empty($validation->getErrors())) {
$newUser = $this->request->getPost();
if ($this->userModel->addUser($newUser)) {
$this->session->setFlashdata('success', 'Successful Registration');
$data['title'] = 'Login';
echo view('templates/index_header', $data);
echo view('users/login');
echo view('templates/footer', $data);
} else {
$this->session->setFlashdata('error', 'Something went wrong with your registration! Please try again.');
}
} else {
$data = [];
$data = [
'title' => 'Register',
'script' => 'js/click_link',
'errors' => $validation->getErrors(),
];
echo view('templates/index_header', $data);
echo view('users/register', $data);
echo view('templates/footer', $data);
}
} else {
$data = [
'title' => 'Register',
'script' => 'js/click_link',
];
echo view('templates/index_header', $data);
echo view('users/register', $data);
echo view('templates/footer', $data);
}
}
}
These are my validation rules in Config\Validation:
/**
* Registration
*/
public $registration = [
'username' => 'required|is_unique[users.username,username]|min_length[5]|max_length[25]|alpha_dash|badWordsFilter[username]',
'password' => 'required|min_length[8]|max_length[255]|regex_match[/^(?=.*[!##$%^&*-])(?=.*[0-9])(?=.*[A-Z]).{8,255}$/]',
'pass_confirm' => 'required|matches[password]',
'about_me' => 'permit_empty|max_length[250]|alpha_numeric_punct|badWordsFilter[about_me]',
'occupation' => 'permit_empty|max_length[50]|alpha_space|badWordsFilter[occupation]',
'hometown' => 'permit_empty|max_length[50]|alpha_space|badWordsFilter[hometown]',
'age' => 'permit_empty|less_than[100]|greater_than[0]|numeric',
'country' => 'permit_empty',
];
/**
* Password Verification
*/
public $login = [
'password' => 'required|validateUser[username,password]',
];
This is my custom rule to authenticate username and password credentials User_rules:
class User_rules
{
/**
* Checks if input username exists in database and then checks whether the input password matches the hash for that username
* #param string $str is the input password
* #param string $fields are the associated form fields that are being used
* #param array $data is an array containing the values for the fields indexed by field names
* #return boolean true or false depending on if the user exists and the password matches the hashed password stored in the database
*/
public function validateUser(string $str, string $fields, array $data)
{
$userModel = new UserModel();
$user = $userModel->getUser($data['username']);
if(!$user) {
return FALSE;
}
return password_verify($data['password'], $user->password);
}
Lastly, my view for login.php:
<div class='form-container'>
<?= form_open('users/login',['autocomplete' => FALSE]); ?>
<div class='form-header'>
<h2>Login</h2>
</div>
<div class='form-body'>
<div class='form-row'>
<div class='input-container'>
<i class='fas fa-user'></i>
<?php $attributes = [
'type' => 'text',
'name' => 'username',
'class' => 'input-field',
'id' => 'username',
'placeholder' => 'Username',
'required' => TRUE,
]; ?>
<?= form_input($attributes); ?>
</div>
</div>
<div class='form-row'>
<div class='input-container'>
<i class='fas fa-lock'></i>
<?php $attributes = [
'type' => 'password',
'name' => 'password',
'class' => 'input-field',
'placeholder' => 'Password',
'required' => TRUE,
]; ?>
<?= form_input($attributes); ?>
</div`>
</div>
</div>
<div class='captcha-container'>
<div class='g-recaptcha' data-sitekey='<?= env('recaptcha2_sitekey'); ?>'></div>
</div>
<div class='form-footer'>
<?php $submit = [
'name' => 'loginSubmit',
'value' => 'Login',
'class' => 'submit-btn',
];?>
<?= form_submit($submit); ?>
</div>
<h4 style='text-align: center'>Not a member yet? Register
<a href= <?= site_url('users/register'); ?> title = 'Register'> HERE</a>
</h4>
<?= form_close(); ?>
</div>
It was a stupid mistake. Someone on the codeigniter forum answered my question here: CodeIgniter Forum
basically in my constructor I needed $this->userModel = new UserModel(); instead of $userModel = new UserModel();.

Dropdownlist Field Form not saved in DB

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'

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.