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>
Related
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.
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
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.
I have some sample code with 2 tabs. One shows a "form" and the other a "list" (Sample 1.5-1), I want to combine them.
I want to show the "form" tab with a "list" view at the bottom (after submit button). I am getting stuck on how to show this.
Inside IndexController, in the ->getRequest->isPost() area, I try to create and fill up the $list (same as the "list" tab example code):
$list=$this->_getListRandom();
$this->view->list = $list;
Then inside of form.phtml, I append:
<h1>My Report Data></h1>
<?php echo $this->list; ?>
I can see the "My Report Data" text in the web page, so I know I am getting to the right area in the code!
But, I get an error from pm_View_Helper_render::renderList() that it must be an instance of pm_View_List_Simple.
I am trying to create both a pm_Form_Simple and pm_View_List_Simple in the same $this, but not
sure if it is allowed or how to do it.
Thanks for any suggestions!
<?php
class IndexController extends pm_Controller_Action
{
public function init()
{
parent::init();
// Init title for all actions
$this->view->pageTitle = 'Example Module';
// Init tabs for all actions
$this->view->tabs = array(
array(
'title' => 'Form',
'action' => 'form',
),
array(
'title' => 'List',
'action' => 'list',
),
);
}
public function indexAction()
{
// Default action will be formAction
$this->_forward('form');
}
public function formAction()
{
// Init form here
$form = new pm_Form_Simple();
$form->addElement('text', 'exampleText', array(
'label' => 'Example Text',
'value' => pm_Settings::get('exampleText'),
'required' => true,
'validators' => array(
array('NotEmpty', true),
),
));
$form->addControlButtons(array(
'cancelLink' => pm_Context::getModulesListUrl(),
));
if ($this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost())) {
// Form proccessing here
pm_Settings::set('exampleText', $form->getValue('exampleText'));
$this->_status->addMessage('info', 'Data was successfully saved.');
# Create the LIST
$list = $this->_getListRandom();
$this->view->list = $list;
$this->_helper->json(array('redirect' => pm_Context::getBaseUrl()));
}
$this->view->form = $form;
}
public function listAction()
{
$list = $this->_getListRandom();
// List object for pm_View_Helper_RenderList
$this->view->list = $list;
}
public function listDataAction()
{
$list = $this->_getListRandom();
// Json data from pm_View_List_Simple
$this->_helper->json($list->fetchData());
}
private function _getListRandom()
{
$data = array();
#$iconPath = pm_Context::getBaseUrl() . 'images/icon_16.gif';
for ($i = 0; $i < 15; $i++) {
$data[] = array(
'column-1' => '' . (string)rand() . '',
'column-2' => (string)rand(),
);
}
$list = new pm_View_List_Simple($this->view, $this->_request);
$list->setData($data);
$list->setColumns(array(
'column-1' => array(
'title' => 'Random with link',
'noEscape' => true,
),
'column-2' => array(
'title' => 'Random with image',
'noEscape' => true,
),
));
// Take into account listDataAction corresponds to the URL /list-data/
$list->setDataUrl(array('action' => 'list-data'));
return $list;
}
}
Please, try https://mega.co.nz/#!NxtyzbyS!JQqFdh7ruESQU_pgmhM6vi8yVFZQRTH-sPDeQcAOFws
Following files are changed:
\example-1.5-2\plib\views\scripts\index\form.phtml:
<?php echo $this->renderTabs($this->tabs); ?>
<?php echo $this->test; ?>
<?php echo $this->form; ?>
<?php echo $this->renderList($this->list); ?>
\example-1.5-2\plib\controllers\IndexController.php:
public function formAction() {
...
...
...
$list = $this->_getListRandom();
// List object for pm_View_Helper_RenderList
$this->view->list = $list;
}
and here the result:
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'));