Related
I've taken the "auth" controller and copied it and renamed it as "site". I have renamed the references to views etc. to "site". When I go to www.mysite/index.php/site/create_user the form loads fine. However on hitting submit I get redirected to www.mysite.com/index.php/site/login and nothing is added to the database. Can anyone tell me why this does not work? My site controller is below:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Site extends CI_Controller {
//
//Authentication
//
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->library(array('ion_auth','form_validation'));
$this->load->helper(array('url','language'));
$this->form_validation->set_error_delimiters($this->config->item('error_start_delimiter', 'ion_auth'), $this->config->item('error_end_delimiter', 'ion_auth'));
$this->lang->load('auth');
}
//Function to log the user in
function login()
{
$this->data['title'] = "Login";
//validate form input
$this->form_validation->set_rules('identity', 'Identity', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == true)
{
// check to see if the user is logging in
// check for "remember me"
$remember = (bool) $this->input->post('remember');
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
{
//if the login is successful
//redirect them back to the home page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('/', 'refresh');
}
else
{
// if the login was un-successful
// redirect them back to the login page
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect('site/login', 'refresh'); // use redirects instead of loading views for compatibility with MY_Controller libraries
}
}
else
{
// the user is not logging in so display the login page
// set the flash data error message if there is one
$this->data['message'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('message');
$this->data['identity'] = array('name' => 'identity',
'id' => 'identity',
'type' => 'text',
'value' => $this->form_validation->set_value('identity'),
);
$this->data['password'] = array('name' => 'password',
'id' => 'password',
'type' => 'password',
);
$this->_render_page('site/login', $this->data);
}
}
//Function to log the user out
function logout()
{
$this->data['title'] = "Logout";
// log the user out
$logout = $this->ion_auth->logout();
// redirect them to the login page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('site/login', 'refresh');
}
//Function to create a user
function create_user()
{
$this->data['title'] = "Create User";
if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
{
//redirect('site/login', 'refresh');
}
$tables = $this->config->item('tables','ion_auth');
// validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('create_user_validation_fname_label'), 'required');
$this->form_validation->set_rules('last_name', $this->lang->line('create_user_validation_lname_label'), 'required');
$this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email|is_unique['.$tables['users'].'.email]');
$this->form_validation->set_rules('phone', $this->lang->line('create_user_validation_phone_label'), 'required');
$this->form_validation->set_rules('company', $this->lang->line('create_user_validation_company_label'), 'required');
$this->form_validation->set_rules('password', $this->lang->line('create_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('create_user_validation_password_confirm_label'), 'required');
if ($this->form_validation->run() == true)
{
$username = strtolower($this->input->post('first_name')) . ' ' . strtolower($this->input->post('last_name'));
$email = strtolower($this->input->post('email'));
$password = $this->input->post('password');
$additional_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'phone' => $this->input->post('phone'),
);
}
if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email, $additional_data))
{
// check to see if we are creating the user
// redirect them back to the admin page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect("site", 'refresh');
}
else
{
// display the create user form
// set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name'),
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name'),
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email'),
);
$this->data['company'] = array(
'name' => 'company',
'id' => 'company',
'type' => 'text',
'value' => $this->form_validation->set_value('company'),
);
$this->data['phone'] = array(
'name' => 'phone',
'id' => 'phone',
'type' => 'text',
'value' => $this->form_validation->set_value('phone'),
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password',
'value' => $this->form_validation->set_value('password'),
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password',
'value' => $this->form_validation->set_value('password_confirm'),
);
$this->_render_page('site/create_user', $this->data);
}
}
//Function to render the page
function _render_page($view, $data=null, $returnhtml=false)//I think this makes more sense
{
$this->viewdata = (empty($data)) ? $this->data: $data;
$view_html = $this->load->view($view, $this->viewdata, $returnhtml);
if ($returnhtml) return $view_html;//This will return html on 3rd argument being true
}
}
This exact code works when in the auth controller. When in the site controller I make it so you must login and you must be an admin to make a user (i.e. uncommenting out this line //redirect('site/login', 'refresh');) then it also works, but for some reason when that line is commented it works in the auth controller but not the site controller.
Any help is much appreciated. I've tried to figure it out but can't see why it works in one and not the other (and why it works in site but only as an admin when that code is uncommented and not at all when it is commented, whilst in auth it works in either case).
Thanks in advance.
The reason you get redirected is one of two reasons.
First : $this->_render_page('site/login', $this->data);
When you hit the submit button it is still pointing to the login controller.
Second : if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
The create user function in the Auth controller is for admins only, You will have to // out the code or you will be redirected to the login page due to not being logged and not being an admin.
try this:
//$this->_render_page('site/login', $this->data);
//if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin())
By marking out these two lines you should be able to veiw and submit your page without being redirected.
:)
I am working on magneto 1.7 version.In this I created a extension. Now, I need to upload multiple images from a form which I created.
I have a browser button in a form Now I need to upload multiple images from that button in a single time.
Can anyone help me?
Below is my form:
protected function _prepareForm() {
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('book_form', array('legend' => Mage::helper('test')->__('Book Content')));
$fieldset->addField('title', 'text', array(
'label' => Mage::helper('test')->__('Title'),
'class' => 'required-entry',
'required' => true,
'name' => 'title[]',
));
$categoryArray = Mage::getSingleton('test/category')->getOptionArray();
$fieldset->addField('category_id', 'select', array(
'label' => Mage::helper('test')->__('Category'),
'required' => true,
'class' => 'required-entry',
'name' => 'category_id[]',
'values' => $categoryArray,
));
**$fieldset->addField('image', 'file', array(
'label' => Mage::helper('test')->__('Image'),
'name' => 'image[]',
'multiple' => 'multiple',
'mulitple' => true,
));**
$fieldset->addField('priority', 'text', array(
'label' => Mage::helper('lookbook')->__('Order of Display'),
'name' => 'priority[]',
));
$fieldset->addField('hiddenData', 'hidden', array(
'class' => Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK) . '_' . Mage::registry('book_data')->getId(),
));
$statusArray = Mage::getSingleton('lookbook/status')->getOptionArray();
$fieldset->addField('publish', 'select', array(
'label' => Mage::helper('lookbook')->__('Status'),
'name' => 'publish[]',
'values' => $statusArray,
));
if (Mage::getSingleton('adminhtml/session')->getBookData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getBookData());
Mage::getSingleton('adminhtml/session')->setBookData(null);
} elseif (Mage::registry('book_data')) {
$form->setValues(Mage::registry('book_data')->getData());
}
return parent::_prepareForm();
}
Take a look in Mage_Adminhtml_controllers_Catalog
You'll find references to the media_image attribute
|| $attribute->getFrontend()->getInputType() == 'media_image'
You can follow the examples in adminhtml for grid's that allow multiple image uploading for the front end. On the backend side you either need your own resource models, or a backend source model declared for the attribute which can follow the backend and frontend models of the catalog images... in those classes you'll find examples of how the backend model deals with saving the images.
form.phtml
<form action="<?php echo Mage::getBaseUrl()."multipleimageupload/index/save"; ?>" method="POST" enctype="multipart/form-data">
<input type="file" name="filename[]" multiple="multiple">
<input type="submit" name="save">
</form>
**
Action
**
public function saveAction(){
$count= count($_FILES['filename']['name']);
for ($i=0; $i < $count; $i++) {
if(isset($_FILES['filename']['name'][$i]) and (file_exists($_FILES['filename']['tmp_name'][$i]))){
try{
// $_FILES['filename']['name'][$i];
$path = Mage::getBaseDir('media') . DS . 'multipleimageupload' . DS;
// $uploader = new Varien_File_Uploader('filename');
$uploader = new Varien_File_Uploader(
array(
'name' => $_FILES['filename']['name'][$i],
'type' => $_FILES['filename']['type'][$i],
'tmp_name' => $_FILES['filename']['tmp_name'][$i],
'error' => $_FILES['filename']['error'][$i],
'size' => $_FILES['filename']['size'][$i]
)
);
$uploader->setAllowedExtensions(array('jpg','png','gif','jpeg'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$destFile = $path.$_FILES['filename']['name'][$i];
$filename = $uploader->getNewFileName($destFile);
$uploader->save($path, $filename);
$data['img'] = $_FILES['filename']['name'][$i];
}catch(Exception $e) {
// echo "<pre>";
// print_r($e);
}
}else{
if(isset($data['filename']['delete'][$i]) && $postData['filename']['delete'][$i] == 1)
$data['filename'] = '';
else
unset($data['filename'][$i]);
}
}
}
I have one view wich has 2 forms one for login and one for registration as following :
signup.ctp //my view
<div>
<?php
echo $this->Form->create("Tbluser");
echo $this->Form->hidden('formsent', array('value' => 'signup'));
echo $this->Form->input('username' ,array('label'=>'Username'));
echo $this->Form->input('password' ,array('label'=>'Password','type' => 'password'));
echo $this->Form->input('email' ,array('label'=>'Email'));
echo $this->Form->end('Register');
?>
</div>
<div>
<?php
echo $this->Form->create("Tbluser"); ?>
echo $this->Form->hidden('formsent', array('value' => 'login'));
echo $this->Form->input('username' ,array('label'=>"Username :"));
echo $this->Form->input('password' ,array('label'=>"Password :",'type' => 'password'));
echo $this->Form->end('Login');
?>
<div>
The model I'm using for both forms is as following :
<?php
class Tbluser extends AppModel{
public $validate = array(
'username'=>array(
array(
'rule'=>'alphaNumeric',
'allowEmpty'=>false,
'message'=>'Invalide Username!'
),
array(
'rule' => array('minLength', '4'),
'message' => 'Username has to be more than 3 chars'
),
array(
'rule'=>'isUnique',
'message'=>'Username already taken!'
)
),
'password' => array(
array(
'rule' => 'alphaNumeric',
'allowEmpty'=>false,
'message' => 'Password must be AlphaNumeric!'
),
array(
'rule' => array('minLength', '4'),
'message' => 'Username has to be more that 3 chars'
)
),
'email'=>array(
array(
'rule'=>array('email',true),
'required'=>true,
'allowEmpty'=>false,
'message'=>'Invalide email adress!'
),
array(
'rule'=>'isUnique',
'message'=>'Mail adress already taken!'
)
)
);
}
?>
The controller I'm using is as following :
<?php
class TblusersController extends AppController
{
public $uses = array(
'Tbluser'
);
public function signup()
{
if ($this->request->is('post')) {
if ('signup' === $this->request->data['Tbluser']['formsent']) {
// Registration part.
}else if('login' === $this->request->data['Tbluser']['formsent']){
//Login part
}
}
}
?>
My AppController looks like :
<?php
class AppController extends Controller {
public $helpers = array('Form', 'Html');
public $components = array('Session','Cookie','Auth'=>array(
'authenticate'=>array(
'Form' => array(
'userModel' => 'Tblforumuser',
'fields' => array(
'username' => 'username',
'password' => 'password'
)
)
)
));
}
?>
Right now if I fill wrong data into the signup form and submit it the validation occurs but also in the login form fields so How can I set the validation only to apply to that signup form and not to both forms? Thanks.
It looks like all validation is being invoked on every read and write because you are telling your model to run all validation without restriction. A better way to handle this would be a separate model for each form.
By creating two new models userLogin and userRegister that extend Tbluser, you can set specific validation rules for each form. You could do something like :
View/Tbluser/signup.ctp
<div>
<?php
echo $this->Form->create("userRegister");
echo $this->Form->hidden('formsent', array('value' => 'signup'));
echo $this->Form->input('username' ,array('label'=>'Username'));
echo $this->Form->input('password' ,array('label'=>'Password','type' => 'password'));
echo $this->Form->input('email' ,array('label'=>'Email'));
echo $this->Form->end('Register');
?>
</div>
<div>
<?php
echo $this->Form->create("userLogin"); ?>
echo $this->Form->hidden('formsent', array('value' => 'login'));
echo $this->Form->input('username' ,array('label'=>"Username :"));
echo $this->Form->input('password' ,array('label'=>"Password :",'type' => 'password'));
echo $this->Form->end('Login');
?>
<div>
Here, since we're using two separate models with each $this->Form-create(); helper, only the validation in the specified model will be run. Your models will contain only the validation that applies to the form assigned to it:
Model/userRegister.php
class userRegister extends Tbluser{
public $validate = array(
'username'=>array(
array(
'rule'=>'alphaNumeric',
'allowEmpty'=>false,
'message'=>'Invalide Username!'
),
array(
'rule' => array('minLength', '4'),
'message' => 'Username has to be more than 3 chars'
),
array(
'rule'=>'isUnique',
'message'=>'Username already taken!'
)
),
'password' => array(
array(
'rule' => 'alphaNumeric',
'allowEmpty'=>false,
'message' => 'Password must be AlphaNumeric!'
),
array(
'rule' => array('minLength', '4'),
'message' => 'Username has to be more that 3 chars'
)
),
'email'=>array(
array(
'rule'=>array('email',true),
'required'=>true,
'allowEmpty'=>false,
'message'=>'Invalide email adress!'
),
array(
'rule'=>'isUnique',
'message'=>'Mail adress already taken!'
)
)
);
}
Model/userLogin.php
class userLogin extends Tbluser{
public $validate = array(
'username'=>array(
array(
'rule'=>'alphaNumeric',
'allowEmpty'=>false,
'message'=>'Invalide Username!'
),
array(
'rule' => array('minLength', '4'),
'message' => 'Username has to be more than 3 chars'
),
array(
'rule'=>'isUnique',
'message'=>'Username already taken!'
)
),
'password' => array(
array(
'rule' => 'alphaNumeric',
'allowEmpty'=>false,
'message' => 'Password must be AlphaNumeric!'
),
array(
'rule' => array('minLength', '4'),
'message' => 'Username has to be more that 3 chars'
)
)
);
}
Then in your signup(); method, you will want to load the two new models you just created accordingly:
Controller/TblusersController.php
class TblusersController extends AppController {
public $uses = array(
'Tblforumuser'
);
public function signup() {
$this->loadModel('userLogin');
$this->loadModel('userRegistration');
if ($this->request->is('post')) {
if ('signup' === $this->request->data['Tblforumuser']['formsent']) {
// Registration part.
}else if('login' === $this->request->data['Tblforumuser']['formsent']){
//Login part
}
}
}
Hope this helps
I've been struggling with this for the last hour or so, wondering if some fresh eyes can help.
Model
class User extends AppModel {
public $name = 'User';
public $validate = array(
'email' => array(
'valid' => array(
'rule' => 'email',
'message' => 'The email is not valid'
),
'required' => array(
'rule' => 'notEmpty',
'message' => 'Please enter an email'
)
)
);
}
Controller
class UserController extends AppController {
var $uses = array('User');
function index(){
$users = $this->User->find('all');
$this->set(compact('users'));
}
public function add() {
$this->set('title_for_layout', 'Add new user');
if(isset($this->data) && !empty($this->data)) {
$this->User->set($this->data);
$this->log($this->User->invalidFields(), "debug");
if($this->User->validates()){
if ($this->User->save($this->data)) {
$this->Session->setFlash("Added " . $this->data['User']['name']);
$this->redirect('index');
}
} else {
$this->Session->setFlash('There are errors with your form submit, please see below.');
}
}
}
}
View
<?php
echo $this->Form->create('User');
echo $this->Form->input('name', array('label' => 'Name'));
echo "<div class='clear'></div>";
echo $this->Form->input('email', array('label' => 'Email'));
echo "<div class='clear'></div>";
echo $this->Form->button('Reset', array('type' => 'reset'));
echo $this->Form->button('Add Useer', array('type' => 'submit'));
echo $this->Form->end();
?>
But I never get invalid fields for email? Have I missed something glaring?
If it makes any difference, this is a plugin Im developing so it doesnt sit directly in app/ but in app/Plugins
Thanks
EDIT: So I've been struggling with this for a while now, and still no joy. One thing I have noticed though, when I print out the model details (using var_dump($this->User) ), the [validate] array is empty. For example:
[validate] => Array
(
)
[validationErrors] => Array
(
)
Im presuming this is what the issue is, even though I have declared my $validate array, its somehow being overwritten? Anyone come across this before? Any solutions?
public $validate = array(
'email' => array(
'valid' => array(
'rule' => array('email'),
'message' => 'The email is not valid'
),
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Please enter an email',
'allowEmpty' => false
)
)
);
Try adding rules as array and adding 'allowEmpty' key set to false on the required validation.
Damn! So simple. If I read the cookbook properly at http://book.cakephp.org/1.3/en/view/1114/Plugin-Models it would have told me that
If you need to reference a model within your plugin, you need to include the plugin name with the model name, separated with a dot.
Thus..
var $uses = array('Plugin.User');
works.. Hope this helps someone else!
I am having an issue trying to display the form validation error on the view using a callback validation function. If the user selects 'Yes' for the vehicle option, the form should check for other mandatory fields related to that vehicle option field.
In my controller I have a simple function that outputs the form and gets data back from the form:
function new_customer_record()
{
if ($this->form_validation->run() == FALSE)
{
// data array has values to be passed to the customer_form_view
$this->load->view('customer_form_view',$data);
}else{
//get data from the post method and save it to the database
}
}
In the config folder, I have a file called from_validation.php that has the array filled with validation rules and the callback function as shown below:
$config = array (
'employee/new_record' => array(
array (
'field' => 'first_name',
'label' => 'First Name',
'rules' => 'required',
),
array (
'field' => 'vehicleOwn',
'label' => 'Own a vehicle',
'rules' => 'required|callback_checkVehicleInfo',
),
),
);
function checkVehicleInfo($str){
if ($str == "Yes"){
$config = array ( 'employee/new_record' => array(
array (
'field' => 'vehicle_model',
'label' => 'Vehicle Model',
'rules' => 'required'
),
array (
'field' => 'vehicle_rego',
'label' => 'Vehicle Rego',
'rules' => 'required'
),
array (
'field' => 'vehicle_type',
'label' => 'Vehicle Type',
'rules' => 'required'
),
),
);
$this->form_validation->set_message('checkVehicleInfo','Please enter your vehicle information');
return FALSE;
}else{
return TRUE;
}
}
In the view, i have something similar to this for each field that has 'required' validation rule - other fields work fine except the vehicle mandatory fields (in the callback function):
<?php $vehicle_model = #field($this->validation->vehicle_model, $customer- >vehicle_model); ?>
<tr>
<td><label>Vehicle Model</label></td>
<td><input name="vehicle_model" type="text" value="<?php echo ($edit=== true)? $vehicle_model :set_value('vehicle_model'); ?>" size="20" maxlength="20">
<?php echo form_error('vehicle_model'); ?></td>
</tr>
But I am not getting any error messages displayed, the validations is not working either.
Right after new_customer_record() function, you should add the callback function (not in config, but put checkVehicleInfo function in your controller).