Setting default values to a form on codeigniter - sql

Sorry dudes, this is my first question, i've been dwelling your site for a little while and learnt a lot, but now i have a problem myself that couldn't find an answer, the thing is that i have a form that's filled in two diferent views, one to select a course that will be edited on the second one, the second one should have all the fields already filled with those that equals them on the database, i know that setting default values should be done using the set_value function defining a second parameter but it isn't working, everything else seems fine...
THIS IS MY FIRST VIEW
<?php echo link_tag('assets/css/nuevocurso.css');?>
<div id="infoMessage"><?php echo $message ?></div>
<section class="container">
<div class="register">
<h1>Ingrese el código del curso que desea modificar.</h1>
<?php echo form_open("curso/modificarcurso");?>
<p> <i>Código</i> <br /> <?php echo form_input($codigo);?> </p>
<p class="submit"><?php echo form_submit('commit', "Registrarse");?></p>
<?php echo form_close();?>
</div>
</section>
<br/>
THIS IS MY SECOND VIEW
<?php echo link_tag('assets/css/nuevocurso.css');?>
<div id="infoMessage"><?php echo $message ?></div>
<section class="container">
<div class="register">
<h1>Modifique los atributos de curso que desee.</h1>
<?php echo form_open("curso/gestionarcurso");?>
<p> <i>Nombre</i> <br /> <?php echo form_input($nombre);?> </p>
<p> <i>Descripcion</i> <br /> <?php echo form_textarea($descripcion);?> </p>
<p> <i>Codigo</i> <br /> <?php echo form_input($codigo);?> </p>
<p> <i>Alias</i> <br /> <?php echo form_input($alias);?> </p>
<p> <i>Programa</i> <br /> <?php echo form_textarea($programa);?> </p>
<p class="submit"><?php echo form_submit('commit', "Registrarse");?></p>
<?php echo form_close();?>
</div>
</section>
<br/>
AND THIS MY CONTROLLER
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Modificarcurso extends CI_Controller
{
public function index()
{
$this->load->database();
$this->load->library('ion_auth');
$this->load->model('nuevocurso_model');
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('codigo', 'Código', 'required|xss_clean');
$user = $this->ion_auth->user()->row();
if ($this->form_validation->run() == true)
{
$codigo = $this->input->post('codigo');
echo $codigo;
$flag = $this->db->query("SELECT codigo FROM curso WHERE codigo = '".$codigo."'");
$flag = $flag->result_array();
var_dump($flag);
if ($user->es_admin == 1 && !empty($flag))
{
echo "chupala maraco";
$this->data['codigo']= $codigo;
$this->data['tipo'] = "admin";
$this->manage($this->data);
}
$flag = $this->db->query("SELECT codigo FROM dicta_curso_profesor WHERE rut = '".$user->rut."' AND codigo = '".$codigo."'");
$flag = $flag->result_array();
if ((!empty($flag))&&($user->es_admin!=1)&&($user->es_profesor==1))
{
$this->data['codigo'] = $codigo;
$this->data['tipo'] = "profesor";
$this->manage($this->data);
}
if ($this->db->affected_rows()>0)
{
$this->data['message'] = 'EEEEEXITO';
}
else
{
$this->data['message'] = 'HAHAHAHAHA';
}
}
$this->data['codigo'] = array(
'name' => 'codigo',
'id' => 'codigo',
'type' => 'text',
'value' => $this->form_validation->set_value('codigo'));
echo $user->es_admin;
echo $user->es_profesor;
$this->load->view('home/header_view');
$this->load->view('curso/gestionarcursoredirect',$this->data);
$this->load->view('home/footer_view');
}
public function manage($datos)
{
$this->load->database();
$this->load->helper('html');
$this->load->helper('form');
$this->load->library('form_validation');
$user = $this->ion_auth->user();
$this->form_validation->set_rules('nombre','Nombre','required|xss_clean');
$this->form_validation->set_rules('alias','Alias','required|xss_clean');
$this->form_validation->set_rules('codigo','Codigo','required|xss_clean');
$this->form_validation->set_rules('descripcion','Codigo','required|xss_clean');
if ($this->form_validation->run() == true)
{
$nombre = $this->input->post('nombre');
$alias = $this->input->post('alias');
$descripcion = $this->input->post('descripcion');
$codigo = $this->input->post('codigo');
$rutprofesor = $this->input->post('profesor');
$flag = $this->db->query("SELECT nombre, codigo FROM curso WHERE curso.nombre = '".$nombre."' OR curso.codigo = '".$codigo."'");
$flag = $flag->result_array();
if (empty($flag))
{
$query = $this->db->query("INSERT INTO curso (nombre, alias, codigo, descripcion) VALUES ('".$nombre."','".$alias."','".$codigo."','".$descripcion."')");
$query = $this->db->query("INSERT INTO dicta_curso_profesor (rut, codigo) VALUES ('".$rutprofesor."','".$codigo."')");
}
if ($this->db->affected_rows()>0)
{
$this->data['message'] = 'EEEEEXITO';
}
else
{
$this->data['message'] = 'HAHAHAHAHA';
}
}
$codigo = $this->input->post('codigo');
$curso = $this->db->query("SELECT * FROM curso WHERE curso.codigo = '".$codigo."'");
$curso = $curso->result_array();
var_dump($curso);
echo $curso[0]['nombre'];
$this->data['nombre'] = array(
'name' => 'nombre',
'id' => 'nombre',
'type' => 'text',
'value' => $this->form_validation->set_value('nombre', $curso[0]["nombre"]),
);
$this->data['descripcion'] = array(
'name' => 'descripcion',
'id' => 'descripcion',
'type' => 'text',
'value' => $this->form_validation->set_value('descripcion', $curso[0]['descripcion']),
'maxlength' => '300',
'rows' => '5',
'cols' => '35',
);
$this->data['codigo'] = array(
'name' => 'codigo',
'id' => 'codigo',
'type' => 'text',
'value' => $this->form_validation->set_value('codigo', $curso[0]['codigo']),
'maxlength' => '8',
);
$this->data['programa'] = array(
'name' => 'programa',
'id' => 'programa',
'type' => 'text',
'value' => $this->form_validation->set_value('programa', $curso[0]["programa"]),
);
$this->data['alias'] = array(
'name' => 'alias',
'id' => 'alias',
'type' => 'text',
'value'=> $this->form_validation->set_value('alias', $curso[0]["alias"]),
'maxlength' => '14',
);
$this->data['profesores'] = $this->nuevocurso_model->get_profesores();
$this->load->view('home/header_view');
$this->load->view('curso/gestionarcurso',$this->data);
$this->load->view('home/footer_view');
}
}
the set_value are in the last function called manage on the controller, those are not working, don't worry about the model, i'm not yet using the only function stored in it.
Thank you, people, stackoverflow is amazing!

The CodeIgniter form helper expects two arguments if you want to set the value, example:
echo form_input('nombre', $nombre);
As the manual says: "You can minimally pass the field name and value in the first and second parameter"
http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html

Will it work in your view like this:
echo form_input(array('name' => 'codigo', 'id' => 'codigo'), set_value('codigo', 'YOUR_VALUE'));

Related

Yii2: Images stored in different tables

Here my controller:
$model = new VehicleType();
if ($model->load(Yii::$app->request->post())) {
if($model->validate()){
$model->save();
$id = $model->id;
$model->file = UploadedFile::getInstance($model, 'file');
if($model->file){
$id = $model->id;
$imageName = "vehicletype_".$id.'_'.getdate()[0];
$model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);
$station = VehicleType::findOne($id);
$station->image = '#web/uploads/'.$imageName.'.'.$model->file->extension;
$station->save();
}
return $this->redirect(['vehicletype/index']);
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
My view:
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'station-form', 'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'description')->textarea() ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
My model:
public function rules()
{
return [
[['description'], 'string'],
[['record_status'], 'integer'],
[['name', 'image'], 'string', 'max' => 255]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'description' => 'Description',
'image' => 'Image',
'record_status' => 'Record Status',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getVehicles()
{
return $this->hasMany(Vehicles::className(), ['vehicle_type_id' => 'id']);
}
}
With this I can upload only one picture/post, I want one post to have multiple pictures, so I create a new table call 'Image' to stored my pictures and have a one-to-many relationship.
But I run into a problem, how can I add data to 2 tables from just 1 form
I'm using Yii2 basic template
Thanks
Step 1
First create two variables in your vehicletype model.
public $uploadedImages;
public $imageforNewtable = array();
Step 2
Make sure to mention this imageforNewtable variable in your model rule.
[['imageforNewtable'], 'image', 'extensions' => 'png, jpg, JPEG'],
Step 3
In your form:
<?php $form = ActiveForm::begin(['id' => 'station-form', 'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'imageforNewtable[]')->fileInput(['accept' => 'image/*']); ?>
Step 4
In Your Controller:
$model->uploadedImages = UploadedFile::getInstances($model,'imageforNewtable');
// Make sure to put "Instances" (plural of Instance) for uploading multiple images
$model->imageforNewtable = array(); // To avoid blank entries as we have entries in $_FILES not in $_POST.
foreach ($model->uploadedImages as $singleImage)
{
$model->imageforNewtable[] = time() . '_' . $singleImage->name;
}
Now bulk insert data in Images table :
$bulkInsertforimages = array(); //defined benchInsert array for images
$columnsArray = ['blog_id', 'image']; //Column names in which bulk insert will take place.
if ($model->imageforNewtable != '') {
foreach ($model->imageforNewtable as $singleData) {
$bulkInsertforimages[] = [
'blog_id' => $model->id,
'image' => $singleData,
];
}
}
if (count($bulkInsertforimages) > 0) {
$command = \Yii::$app->db->createCommand();
$command->batchInsert('YOUR_IMAGE_TABLE', $columnsArray, $bulkInsertforimages)->execute();
}

Drupal 7 - Keep me logged in and customizing the error messages

Can anybody help me in implementing Drupal 7 'Keep me logged in' feature and customize the error messages in login form.
In page--front.tpl.php i used <?php print front_login();?> for the login form and front_login() function is in template.php.
template.php functions are
<?php
function front_login() {
global $user;
if ($user->uid == 0) {
$form = drupal_get_form('front_login_form');
return theme('status_messages').render($form);
} else {
return '<div id="loginbar">' . t('Welcome back ') . ucwords($user->name) . '</div>';
}
}
function front_login_form($form, &$form_state) {
global $base_url;
$form['#id'] = 'login';
$haveAccount = '<div class="title"><span>Already have an account?</span><br>Log In Here</div>';
$forgot = '<div class="forgot">Forgot your password?</div>';
$form['#validate'] = user_login_default_validators();
$form['#submit'][] = 'front_login_form_submit';
$form['name'] = array(
'#type' => 'textfield',
'#id' => 'user_login',
'#prefix' => $haveAccount . '<div class="inputholder"><div class="icon glyphicon glyphicon-user"></div>',
'#suffix' => '</div>',
'#required' => TRUE,
'#attributes' => array('class' => array('footerinput'), 'placeholder' => array(t('Username'))),
);
$form['pass'] = array(
'#type' => 'password',
'#id' => 'pwd_login',
'#prefix' => '<div class="inputholder"><div class="icon"><img src="' . $base_url . '/' . drupal_get_path('theme', 'foodnet') . '/images/icon-2.png"></div>',
'#suffix' => "</div>",
'#required' => TRUE,
'#attributes' => array('class' => array('footerinput'), 'placeholder' => array(t('Password'))),
);
$form['keep_logged'] = array(
'#type' => 'checkbox',
'#title' => t('Keep me logged in'),
'#default_value' => 1,
'#prefix' => '<div class="row">
<div class="col-md-6">
<div class="checkbox"><label>',
'#suffix' => '</label></div>
</div>'
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#id' => 'but_login',
'#name' => 'but_login',
'#value' => t('Log In »'),
'#prefix' => '<div class="col-md-6"><div class="loginBtn">',
'#suffix' => '</div></div> </div>' . $forgot
);
$form['actions']['submit']['#attributes']['class'][] = 'btn';
$form['actions']['submit']['#attributes']['class'][] = 'btn-yellow';
$form['actions']['submit']['#attributes']['class'][] = 'btn-lg';
$form['actions']['submit']['#attributes']['class'][] = 'col-md-12';
return $form;
}
function front_login_form_submit($form, &$form_state) {
global $user;
$user = user_load($form_state['uid']);
$form_state['redirect'] = 'profile';
user_login_finalize($form_state);
if($form_state['values']['keep_logged'] ==0){
ini_set('session.cookie_lifetime', 0);
foreach ($_COOKIE as $key => $value) {
setcookie($key, $value, 0);
}
setcookie('_fnet_keepLogged', 0, time()+200000);
}else{
ini_set('session.cookie_lifetime', 2000000);
setcookie('_fnet_keepLogged', 1, time()+200000);
}
}
The login functionality works fine but I cannot customize the error messages. I have to set the errors inside the form. Please help.
When user click the 'Keep me logged in' checkbox I set '_fnet_keepLogged' cookie to 1, else to 0. I know that the default expiration of cookie in drupal is 23 days. I need to change that according to the value of '_fnet_keepLogged' cookie. Please help for this.
Thanks in advance.

registration form post field as empty

i'm using Yii-user, and have made some modification to the user/views/user/registration.php file.
for some reason even when i fill in firstname and lastname, it still says i left those fields empty. any idea why?
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'registration-form',
'type'=>'vertical',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
<?php echo $form->textField($model,'email', array('class' => 'input-block-level', 'placeholder' => $model->getAttributeLabel('email'))); ?>
<?php echo $form->passwordField($model,'password', array('class' => 'input-block-level', 'placeholder' => $model->getAttributeLabel('password'))); ?>
<?php echo $form->passwordField($model,'verifyPassword', array('class' => 'input-block-level', 'placeholder' => $model->getAttributeLabel('verifyPassword'))); ?>
<p class="text-seperator"> about you </p>
<?php echo $form->textField($profile,'firstname', array('class' => 'input-block-level', 'placeholder' => $model->getAttributeLabel('firstname'), 'maxlength'=> 255)); ?>
<?php echo $form->textField($profile,'lastname', array('class' => 'input-block-level', 'placeholder' => $model->getAttributeLabel('lastname'), 'maxlength'=> 255)); ?>
and in my user/models/registrationform.php i have this
class RegistrationForm extends User {
public $firstname; //added
public $lastname; //added
public $verifyPassword;
public $verifyCode;
public function rules() {
$rules = array(
array('firstname, lastname, password, verifyPassword, email', 'required'),
array('firstname', 'length', 'max'=>225, 'min' => 3,'message' => UserModule::t("Incorrect First Name (length between 3 and 225 characters).")),
array('lastname', 'length', 'max'=>225, 'min' => 3,'message' => UserModule::t("Incorrect Last Name (length between 3 and 225 characters).")),
.........
}
}
to fill up firstname and last name using the original code they used this...
$profileFields=Profile::getFields();
if ($profileFields) {
foreach($profileFields as $field) {
?>
<!--div class="row"-->
<?php echo $form->labelEx($profile,$field->varname); ?>
<?php
if ($widgetEdit = $field->widgetEdit($profile)) {
echo $widgetEdit;
} elseif ($field->range) {
echo $form->dropDownList($profile,$field->varname,Profile::range($field->range));
} elseif ($field->field_type=="TEXT") {
echo$form->textArea($profile,$field->varname,array('rows'=>6, 'cols'=>50));
} else {
echo $field->varname.'<br />';
echo $form->textField($profile,$field->varname,array('size'=>60,'maxlength'=>(($field->field_size)?$field->field_size:255)));
}
?>
<?php echo $form->error($profile,$field->varname); ?>
<!--/div-->
<?php
}
}
I think you need to change this,
you have passed $model in here:
<?php echo $form->textField($model,'email', array('class' => 'input-block-level', 'placeholder' => $model->getAttributeLabel('email'))); ?>
but you have given $profile here:
<?php echo $form->textField($profile,'firstname', array('class' => 'input-block-level', 'placeholder' => $model->getAttributeLabel('firstname'), 'maxlength'=> 255)); ?>
if you check out the generated html, you will notice that the generated input has different name!
i'm not sure why this works (would be great is someone could explain in detail)
but the issue was here..
public function rules() {
$rules = array(
array('firstname, lastname, password, verifyPassword, email', 'required'),
array('firstname', 'length', 'max'=>225, 'min' => 3,'message' => UserModule::t("Incorrect First Name (length between 3 and 225 characters).")),
array('lastname', 'length', 'max'=>225, 'min' => 3,'message' => UserModule::t("Incorrect Last Name (length between 3 and 225 characters).")),
.........
}
}
firstname, lastname when this is removed it works. and it still is set as required.

change placeholder text from array

I'm using the yii-user extension and i'm trying the add proper label to the 'placeholder' attribute. really new to Yii so still trying to get the grasp of things.
I've added the attributeLabels() method in the class in the models folder.
class RegistrationForm extends User {
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'email'=>'Email Address',
'firstname'=>'First Name',
'lastname' => 'Last Name',
'verifyPassword' = 'Retype Password'
);
}
}
Here is my code in my /views/ folder
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
'id'=>'registration-form',
'type'=>'vertical',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
));
<?php echo $form->textField($model,'email', array('class' => 'input-block-level', 'placeholder' => 'email')); ?>
<?php echo $form->passwordField($model,'password', array('class' => 'input-block-level', 'placeholder' => 'password')); ?>
<?php echo $form->passwordField($model,'verifyPassword', array('class' => 'input-block-level', 'placeholder' => 'verifyPassword')); ?>
<?php
$profileFields=Profile::getFields();
if ($profileFields) {
foreach($profileFields as $field) {
if ($widgetEdit = $field->widgetEdit($profile)) {
//echo $widgetEdit;
} elseif ($field->range) {
echo $form->dropDownList($profile,$field->varname,Profile::range($field->range),array('class' => 'input-block-level'));
} elseif ($field->field_type=="TEXT") {
echo $form->textArea($profile,$field->varname,array('rows'=>6, 'cols'=>50));
} else {
//echo $field->varname;
if ($field->varname == 'firstname')
{
$placeholder = 'First Name';
}
else if ($field->varname == 'lastname')
{
$placeholder = 'Last Name';
}
else
{
$placeholder = $field->varname;
}
echo $form->textField($profile,$field->varname,array('size'=>60,'maxlength'=>(($field->field_size)?$field->field_size:255),'class' => 'input-block-level', 'placeholder' => $placeholder));
}
echo $form->error($profile,$field->varname);
}
}
?>
how would i make attributeLabels() work on my echo $form->textField($profile,$field->varname,array('size'=>60,'maxlength'=>(($field->field_size)?$field->field_size:255),'class' => 'input-block-level', 'placeholder' => $placeholder)); ?
You can get the text label for the specified attribute with getAttributeLabel() like:
$model->getAttributeLabel('verifyPassword');
E.x:
<?php echo $form->passwordField($model,'verifyPassword',
array('class' => 'input-block-level',
'placeholder' => $model->getAttributeLabel('verifyPassword')));
?>
you don't have to edit class RegistrationForm extends User
open protected/modules/user/model/User.php
add add/edit your custom labels in the attributeLabels() method
public function attributeLabels()
{
return array(
'id' => UserModule::t("Id"),
'username'=>UserModule::t("username"),
'password'=>UserModule::t("Password"),
'verifyPassword'=>UserModule::t("Retype Password"),
'firstname'=>UserModule::t("First Name"), //ADDED
'lastname'=>UserModule::t("Last Name"), // ADDED
'email'=>UserModule::t("Email Address"), //EDITED
'verifyCode'=>UserModule::t("Verification Code"),
'activkey' => UserModule::t("Activation Key"),
'createtime' => UserModule::t("Registration Date"),
'create_at' => UserModule::t("Registration Date"),
'lastvisit_at' => UserModule::t("Last Visit"),
'superuser' => UserModule::t("Superuser"),
'status' => UserModule::t("Status"),
);
}
and to get the label to show in your view file. use this
<?php echo $form->passwordField($model,'verifyPassword',
array('class' => 'input-block-level',
'placeholder' => $model->getAttributeLabel('email')));
?>

Strange CakePHP 2.0 auth login issue

Ok, so I was having a very interesting issue with CakePHP 1.3, in that even if I used the correct information to try to log in, it wouldn't work. I've now upgraded the same app to Cakephp 2.0, and I'm having a very different issue. Basically now, regardless of what information I put in when I'm logging in, it will log in. Even if the database is empty. No idea why this is happening...
Here's my code:
View:
<div id="login">
<p>Please log in! <a id="register" href="register" alt="Register">Register</a></p>
<hr class="login"/>
<?php
echo $this->Session->flash('auth');
echo $this->Form->create('User');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo "<hr class=\"login\"/>";
echo $this->Form->end('Login');
echo $this->Session->flash('flash_registration');
echo "<pre>"; print_r($this->request->data); echo "</pre>";
echo $this->Html->link('Log-Out', 'logout');
?>
</div>
Model:
<?php
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
var $name = 'User';
var $validate = array(
'name' => array(
'custom_rule' => array(
'rule' => '/^[A-Za-z\s]*$/i',
'message' => 'Please enter an acceptable name'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
),
'dob' => array(
'rule' => array('date', 'ymd'),
'message' => 'Enter a valid date',
),
'phone' => array(
'numbers' => array(
'rule' => 'numeric',
'message' => 'Numbers only, no dashes or spaces'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
),
'username' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'message' => 'Letters and numbers only'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
),
'e-mail' => array(
'email' => array(
'rule' => 'email',
'message' => 'Please enter a valid e-mail address'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
),
'password_enter' => array(
'length' => array(
'rule' => array('between', 8, 16),
'message' => 'Password must be between 8 and 16 characters'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
),
'password_confirm' => array(
'identicalFieldValues' => array(
'rule' => array('identicalFieldValues', 'password_enter'),
'message' => 'Passwords do not match'
),
'length' => array(
'rule' => array('between', 8, 16),
'message' => 'Password must be between 8 and 16 characters'
),
'notEmpty' => array(
'rule' => array('notEmpty'),
'message' => 'This field is required'
)
)
);
function identicalFieldValues( $field=array(), $compare_field=null ){
foreach( $field as $key => $value ){
$v1 = $value;
$v2 = $this->data[$this->name][ $compare_field ];
if($v1 !== $v2) {
return FALSE;
} else {
return TRUE;
}
}
}
function beforeValidate(){
$this->data['User']['dob'] = $this->data['User']['dob'];
return true;
}
function beforeSave(){
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password_enter']);
$this->data['User']['activated'] = FALSE;
return TRUE;
}
}
?>
Controller:
<?php
class UsersController extends AppController {
var $name = 'Users';
var $uses = array("User");
var $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'pages', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
)
);
var $helpers = array('Form', 'Session', 'Html');
function beforeFilter(){
// Basic setup
$this->Auth->authenticate = array('Form');
$this->Auth->allow('register', 'activate');
}
function index() {
}
function login() {
$this->Auth->login($this->request->data);
$this->set('title_for_layout', "Welcome to Sound-On.com!");
$this->layout = 'user_functions';
if ($this->Auth->user()) {
echo "Logged in!";
} else {
echo "Not logged in!";
}
}
function logout() {
$this->redirect($this->Auth->logout());
}
function register(){
$this->set('title_for_layout', "Register Here!");
$this->layout = 'user_functions';
$date = date('Y');
if (!empty($this->data)) {
$user_check = $this->User->find('first', array('conditions' => array('username' => $this->data['User']['username'])));
$email_check = $this->User->find('first', array('conditions' => array('e-mail' => $this->data['User']['e-mail'])));
if (empty($user_check)) {
if(empty($email_check)){
if ($this->User->save($this->data)) {
$uuid_string = $this->data['User']['activation_hash'];
$email = <<<EOT
<html>
<head>
<title>Welcome to Sound-On.com!</title>
</head>
<body>
<p>
<h1>Welcome to Sound-on.com!</h1>
<p>You have successfully registered! To activate your account and start sounding on, please click Here! <br/>If the link is not clickable, please copy and paste the link below into your browser address bar.</p>
http://www.sound-on.com/activate?uid=$uuid_string
<p style="">Thank you for registering!</p>
<p>Your friendly Sound-On registration robot</p>
<p>If you did not register or wish to remove your account, please click here.</p>
<p style="font-size:8pt;color:#707070">© Copyright $date Sound-on.com. All rights Reserved.</p>
</p>
</body
</html>
EOT;
$to = $this->data['User']['e-mail'];
$subject = 'Welcome to Sound-On.com!';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: registration#Sound-On.com';
if (mail($to, $subject, $email, $headers)) {
$this->redirect('/');
}
} else {
//$this->Session->setFlash('<p class="register_flash">Something went wrong. Please try again.</p>', 'flash_registration');
//$this->flash('', '/');
}
} else {
//email exists
}
} else {
//username exists
}
}
}
function activate(){
$this->set('title_for_layout', "Register Here!");
$this->layout = 'user_functions';
if (!empty($_GET)) {
$activate = $this->User->updateAll(array('activated' => 1), array('activation_hash' => $_GET['uuid']));
if ($activate) {
$this->set('message', '<p id="activation_message">Your account has been successfully activated! Please click here to proceed to login!</p>');
}
}
}
}
?>
Thanks in advance!
If you send data to the Auth->login() function it will log in with the data.
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in
You need to use something like this.
public function login() {
if ($this->request->is('post')) {
if (!$this->Auth->login()) {
$this->Session->setFlash('Your username or password was incorrect.');
} else {
$this->Session->setFlash('You are now logged in.');
//redirect
}
}
}