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.
Related
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'
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();
}
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
At first I was just having problem in showing my forms then I edited the set_include_path in index.php of my project, but it did not help so I removed the path of forms from the set_include_path and resumed my old code but now it is jus showing a blanck page on each module. Here is my Bootstarp
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
public $frontController= null;
public $root='';
public $layout=null;
public $config = null;
public function run(){
$this->setUpEnvironment();
$this->prepare();
$response = $this->frontController->dispatch();
$this->sendResponse($response);
}
public function setUpEnvironment(){
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', true);
date_default_timezone_set('Asia/Kuala_Lumpur');
$this->root = dirname(dirname(__FILE__));
echo $this->root."hello";
}
public function setUpConfiguration(){
$this->config = new Zend_Config_Ini($this->root.'/application/configs/application.ini');
}
public function prepare(){
$this->setupEnvironment();
//Zend_Loader::registerAutoload();
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
$this->setupRegistry();
$this->setupConfiguration();
$this->setupFrontController();
$this->startSession();
$this->setupView('default');//current theme direcotry
//$this->setupLanguage();
}
public function setupFrontController(){
Zend_Loader::loadClass('Zend_Controller_Front');
$this->frontController = Zend_Controller_Front::getInstance();
$this->frontController->throwExceptions(true);
$this->frontController->returnResponse(true);
$this->frontController ->setParam('noErrorHandler', true);
//echo $this->root;
$this->frontController->setControllerDirectory(array(
'default' => $this->root .'/application/default/controllers/',
'admin' => $this->root .'/application/admin/controllers/',
//'vendor' => $this->root .'/application/vendor/controllers/',
));
}
public function setupView($crt_theme)
{
$view = new Zend_View;
$view->setEncoding('UTF-8');
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
$view->setScriptPath($this->root .'/application/default/views/scripts/'.$crt_theme);
$view->setHelperPath($this->root .'/application/default/views/helpers');
$this->layout = Zend_Layout::startMvc(
array(
'layoutPath' => $this->root . '/application/layouts',
'layout' => 'layout'
)
);
$this->registry->set("theme", $crt_theme);
}
public function setupRegistry()
{
$this->registry = Zend_Registry::getInstance();
$this->registry->set('config', $this->config);
$this->registry->set('frontController',$this->frontController);
}
public function startSession(){
Zend_Session::start();
}
public function sendResponse(Zend_Controller_Response_Http $response)
{
$response->setHeader('Content-Type', 'text/html; charset=UTF-8', true);
$response->sendResponse();
}
}
I've made two modules admin and default and made a form in application/forms/Admin/LoginForm.php
<?php
class Application_Form_Admin_LoginForm extends Zend_Form{
public function init(){
$this->setMethod('post')
->setAction('/admin/index');
$this->addElement(
'text', 'username', array(
'label' => 'Username:',
'required' => true,
'filters' => array('StringTrim'),
));
$this->addElement('password', 'password', array(
'label' => 'Password:',
'required' => true,
));
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Login',
));
}
}
Here's my IndexController in admin module
<?php
class Admin_IndexController extends Zend_Controller_Action
{
public function init()
{
// echo "Hello";
$this->layout = Zend_Layout::startMvc(
array(
'layoutPath' => APPLICATION_PATH . '/layouts',
'layout' => 'layout'
)
);
//var_dump($this->layout);
//$this->view->('header.phtml');
}
public function indexAction()
{
$form = new Application_Form_Admin_LoginForm();
/*$form->setMethod('post');
$form->addElement(
'text', 'username', array(
'label' => 'Username:',
'required' => true,
'filters' => array('StringTrim'),
));
$form->addElement('password', 'password', array(
'label' => 'Password:',
'required' => true,
));
$form->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Login',
));
*/
$this->view->login = $form;
// $this->view->show = "I'm in admin index controller";
/*if((!isset($this->_request->getParam('username')))&&(!isset($this->_request->getParam('password'))))
{
}
else{
$username = $this->_request()->getPost('username');
echo $username;
}
*/
}
}
and here is my index.phtml in index folder of application/admin/views/scripts/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<style>
body{
background-color:grey;
}
#login{
background-color:#FFF;
width:350px;
height:200px;
border:1px solid black;
-moz-border-radius:10px;
border-radius:10px;
}
</style>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<center>
<h1>Please Login</h1>
<div id="login">
<?php
echo $this->login;
//echo $this->show;
?>
</center>
</div>
</body>
</html>
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'));