cakephp 2 validation error messages do not display - cakephp-2.5

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.

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'

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

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

zend showing blank page

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>