I have a form for editing a user record. Its updates the record for the first time but when i press the update button again, it shows me an empty screen and it unsets the picture as well. I cannot figure out what I am doign wrong
Below is my code
public function actionEditProfile($affusername = NULL) {
$this->layout = 'layout_home';
if ($this->VarifyUser($affusername) && Yii::app()->user->id) {
$model = new Users('edit'); //apply rules if user comes directly to signup page
// uncomment the following code to enable ajax-based validation
if (isset($_POST['ajax']) && $_POST['ajax'] === 'editprofile-form') {
CActiveForm::validate($model);
Yii::app()->end();
}
if (isset($_POST['Users'])) {
$the_image = CUploadedFile::getInstance($model, 'image');
if (is_object($the_image) && get_class($the_image) === 'CUploadedFile') {
$model->image = $the_image;
}
if (is_object($the_image)) {
$file_name = Yii::app()->user->id . '.' . $model->image->extensionName;
$move = $model->image->saveAs(Yii::getPathOfAlias('webroot') . '/themes/myproject/images/users/' . $file_name);
$_POST['Users']['image'] = $file_name;
}
$model->attributes = $_POST['Users'];
if ($model->validate()) {
// form inputs are valid, do something here
if ($model->updateByPk(Yii::app()->user->id, $_POST['Users'])) {
//$this->setFlashSuccess("Unable to register user, please try again");
$this->setFlashSuccess('Updated successfully, now redirecting.');
//$this->redirect($this->base_url);
} else {
$this->setFlashError("Unable to update user, please try again");
return false;
}
} else {
print_r($model->getErrors());
echo 'validation fail';
exit;
}
}
$user_data = Users::model()->getUsersByUserName($affusername); //getting user information
//print_r($user_data);
//$model=new Users('nonfb-create'); //apply rules if user comes directly to signup page
$this->render('editprofile', array('model' => $model, 'data' => $user_data,));
} else {
$this->redirect($this->base_url);
}
}
My view is
<div class="adminform_wrapp">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'editprofile-form',
'enableAjaxValidation' => false,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'enableClientValidation' => true,
'focus' => array($model, 'first_name'),
'htmlOptions' => array(
'enctype' => 'multipart/form-data'
)
));
echo $form->errorSummary($model);
?>
<!--adminform_row-->
<div class="adminform_row">
<label class="fieldname required" for="Users_First_Name">First Name: <span class="required">*</span></label>
<?php echo $form->textField($model, 'first_name', array('value' => $data['first_name'])); ?>
<?php $form->error($model, 'first_name'); ?>
</div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<label class="fieldname required" for="Users_Last_Name">Last Name: <span class="required">*</span></label>
<?php echo $form->textField($model, 'last_name', array('value' => $data['last_name'])); ?>
<?php $form->error($model, 'last_name'); ?>
</div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<label class="fieldname required" for="Users_Email">Email: <span class="required">*</span></label>
<?php echo $form->textField($model, 'email', array('value' => $data['email'])); ?>
<?php $form->error($model, 'email'); ?>
</div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<label class="fieldname required" for="Users_Phone_No">Phone No: <span class="required">*</span></label>
<?php echo $form->textField($model, 'phone_no', array('value' => $data['phone_no'])); ?>
<?php $form->error($model, 'phone_no'); ?>
</div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<label>Username:</label>
<span class="profile-username"><?php echo $data['username']; ?></span> </div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<label>Edit Profile picture:</label>
<span class="image-placeholder">
<img src="<?php echo $this->theme_baseurl . '/images/users/' . $data['image']; ?>" style="width:96px; height:96px;"/>
</span>
<div id='file_browse_wrapper'>
<?php
//echo $form->labelEx($model, 'image');
echo $form->fileField($model, 'image', array('id' => 'file_browse'));
echo $form->error($model, 'image');
?>
</div>
</div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<?php echo $form->labelEx($model, 'Address', array('class' => 'fieldname')); ?>
<?php echo $form->textField($model, 'address', array('value' => $data['address'])); ?>
<?php $form->error($model, 'address'); ?>
</div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<label class="fieldname required" for="Users_Country">Country: <span class="required">*</span></label>
<select class="error" onchange="print_state('Users_state', this.selectedIndex);" id="Users_country" name ="Users[country]"></select>
<?php $form->error($model, 'country'); ?>
</div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<label class="fieldname required" for="Users_State">State: <span class="required">*</span></label>
<select name ="Users[state]" id ="Users_state"></select>
<script language="javascript">print_state("Users_state", '', "<?php echo $data['state'] ?>");</script>
<?php $form->error($model, 'state'); ?>
</div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<label class="fieldname required" for="Users_City">City: <span class="required">*</span></label>
<?php echo $form->textField($model, 'city', array('value' => $data['city'])); ?>
<?php $form->error($model, 'city'); ?>
</div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<label class="fieldname required" for="Users_Zipcode">Zipcode: <span class="required">*</span></label>
<?php echo $form->textField($model, 'zipcode', array('value' => $data['zipcode'])); ?>
<?php $form->error($model, 'zipcode'); ?>
</div>
<!--adminform_row-->
<!--adminform_row-->
<div class="adminform_row">
<input type="submit" class="adminupdate_btn" value="Update">
<input type="reset" class="admincancel_btn" value="Cancel">
</div>
<!--adminform_row-->
<?php $this->endWidget(); ?>
</div>
An empty screen is shown usually when there is a syntactic error.
You can see the error in the apache log (usually at /var/log/apache2/error.log in linux).
As darkheir said, you should see that log file.
It was a syntax error. Also it was updating the complete row in the database where update form was sending only a few fields. I fixed by manually setting the attributes. Below is my code
if (isset($_POST['Users'])) {
//echo "<pre>";
//print_r($model->image);
// print_r($_POST);
// print_r($_FILES);
//echo "</pre>";
$the_image = CUploadedFile::getInstance($model, 'image');
if (is_object($the_image) && get_class($the_image) === 'CUploadedFile') {
$model->image = $the_image;
}
//echo "<pre>";
//print_r($_POST);
//echo "</pre>";
$first_name = $_POST['Users']['first_name'];
$last_name = $_POST['Users']['last_name'];
$email = $_POST['Users']['email'];
$phone_no = $_POST['Users']['phone_no'];
$address = $_POST['Users']['address'];
$country = $_POST['Users']['country'];
$state = $_POST['Users']['state'];
$city = $_POST['Users']['city'];
$zipcode = $_POST['Users']['zipcode'];
if (is_object($the_image)) {
$file_name = Yii::app()->user->id . '.' . $model->image->extensionName;
$model->image->saveAs(Yii::getPathOfAlias('webroot') . '/themes/karmora/images/users/' . $file_name);
$_POST['Users']['image'] = $file_name;
//$model->first_name = $_POST['Users']['first_name'];
$attributes = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'phone_no' => $phone_no,
'image' => $file_name,
'address' => $address,
'country' => $country,
'state' => $state,
'city' => $city,
'zipcode' => $zipcode
);
} else {
$attributes = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'phone_no' => $phone_no,
'address' => $address,
'country' => $country,
'state' => $state,
'city' => $city,
'zipcode' => $zipcode);
}
$model->updateByPk(Yii::app()->user->id, $attributes);
}
Related
Can anyone help me why my if code ($ this-> form_validation-> run () == FALSE) always returning FALSE even all fields are valid.
I have already loaded form_validation, url etc. the application is already working on a web server but when I deploy the application in localhost I hang on this error (from_validation always return false).
Here is my form:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$email = array(
'name' => 'email',
'id' => 'email',
'class'=> 'input',
'value' => set_value('email'),
'maxlength'=> 80,
'size' => 27,
);
$password = array(
'name' => 'password',
'id' => 'password',
'class' => 'input',
'value' => set_value('password'),
'size' => 27,
);
?>
<div class="row-fluid">
<div class="span8">
<b>Bienvenu!</b>
<p>Identifier-vous pour Accèder à Votre Compte</p>
<p>et Profiter de Nos Services en Ligne </p>
<?php $connect='users/login'; ?>
</div>
</div>
<div class="error"><strong><?=$this->session->flashdata('flashSuccess')?></strong></div>
<div class="login">
<?php $attributes = array('name' => 'loginf', 'autocomplete' => 'off' ); ?>
<?php echo form_open($connect,$attributes );?>
<div class="row-fluid">
<div class="span3">
<?php echo form_label('Adresse Email', $email['id']); ?>
</div>
<div class="span5">
<?php echo form_input($email); ?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<?php echo form_label('Mot de passe', $password['id']); ?>
</div>
<div class="span5">
<?php echo form_password($password); ?>
</div>
</div>
<div class="row-fluid">
<div class="span4">
<input class="btn" name="submit" type="submit" id="submit" value="Connexion" />
</div>
</div>
</div>
<?php echo form_close()?>
And my controller where the form_validation always returns false:
<?php
function login(){
$this->load->model('User_m');
$auto=FALSE;
$email=strtolower($this->input->post('email'));
$found="#bmc.com";
$res=strpos($email,$found) ;
if($res > 0){
$role=$this->User_model->getRole(strtolower($this->input->post('email')));
$tiers=$this->User_model->getTiers(strtolower($this->input->post('email')));
if($role=="VEND" && $tiers==""){
$auto=TRUE;
$this->form_validation->set_rules('email', 'Email Address', 'xss_clean|trim|required|valid_email');
}else{
$this->form_validation->set_rules('email', 'Email Address', 'xss_clean|trim|required|valid_email|callback_conten');
}
}else{
$this->form_validation->set_rules('email', 'Email Address', 'xss_clean|trim|required|valid_email|callback_conten');
}
$this->form_validation->set_rules('password', 'Password', 'xss_clean|trim|required|min_length[6]|max_length[20]|callback_password_check');
$this->_email = $this->input->post('email');
$s_pass=$this->security->xss_clean($this->input->post('password'));
$this->_password = sha1($this->_salt .$s_pass);
if($this->form_validation->run() == FALSE){
$this->tmpl_login['success']=NULL;
$this->tmpl_login['auth']='style="display:block"';
$this->tmpl_login['p_o']='style="display:none"';
$this->layout->view_menu_top('menul');
$this->layout->view('compte/login',$this->tmpl_login);
}else{
$this->auth->login('email');
$dv=$this->find_date_visit();
if($auto==FALSE){$this->_SendDynamiqueMessage($this->_email);}
$this->session->set_userdata('name',$this->find_name_user($this->_email));
$this->session->set_userdata('quality',$this->find_quality_user($this->_email));
$this->session->set_userdata('date_visite',$dv);
$this->session->set_userdata('email',$this->_email);
$user_agent = get_browser(null, true);
$this->db->query("insert into us_connexion values ('". $this->_email."',sysdate,'". $user_agent['platform']."','". $user_agent['parent']."')");
if(!$dv){
$this->session->set_userdata('date_visite','premier visite');
redirect('users/password');
}
redirect('users/index');
}
}
?>
PS: I used the codeigniter 2.0.2 version.
Any help please!
Thinks.
I try load form via ajax in CJuiDialog. The form was success loaded but when I submitted form or write text, form not validate and not submit.I tried set "true" fourth parameter in renderPartialbut after then dialog window didn't open. In console, I got error
$(...).dialog is not a function
In view I have this:
Yii::app()->clientScript->registerScript(
"test",
"jQuery.ajax({
type: 'POST',
url: '".$this->createUrl("/Site/ShowForm")."',
success: function(html){
$('#form-test').html(html);
});
",
CClientScript::POS_READY); ?>
<div id="form-test"></div>
<?php $this->endWidget('zii.widgets.jui.CJuiDialog');
My actions in controller:
public function actionShowForm()
{
$model = new RegistrationForm;
if(Yii::app()->request->isAjaxRequest )
return $this->renderPartial('register', array('model' => $model),false,false);
}
public function actionRegister()
{
$model = new RegistrationForm;
$this->ajaxValidate($model);
$model->attributes =$_POST['RegistrationForm'];
if($model->validate())
{
$user = new User;
$user->attributes = $model->attributes;
if($user->save())
echo 1;
}
}
and my form (register.php)
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'register-form',
//'enableClientValidation'=>true,
'enableAjaxValidation' => true,
'clientOptions' => array(
//'validateOnSubmit' => true,
'validateOnChange' => true
),
'action' => array('site/Register'),
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model, 'first_name'); ?>
<?php echo $form->textField($model, 'first_name'); ?>
<?php echo $form->error($model, 'first_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'last_name'); ?>
<?php echo $form->textField($model, 'last_name'); ?>
<?php echo $form->error($model, 'last_name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'email'); ?>
<?php echo $form->emailField($model, 'email'); ?>
<?php echo $form->error($model, 'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'password'); ?>
<?php echo $form->textField($model, 'password'); ?>
<?php echo $form->error($model, 'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'Repeat password'); ?>
<?php echo $form->textField($model, 'repeat_password'); ?>
<?php echo $form->error($model, 'repeat_password'); ?>
</div>
<div>
<?php echo $form->textField($model, 'verifyCode'); ?>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->error($model, 'verifyCode'); ?>
</div>
<div class="row buttons">
<?php
echo CHtml::ajaxSubmitButton('Register', $this->createUrl("/Site/Register"), array(
'type' => 'POST',
'dataType' => 'json',
'success' => 'js:function(data){
if(data == 1){
window.location ="' . $this->createUrl('site/index') . '"
}
}',
));
?>
</div>
<?php $this->endWidget(); ?>
How Can I fix this problem?
In your controller, where you check if the request is Ajax, you should be doing the Ajax validation in there.
I found solution! I added
Yii::app()->clientScript->scriptMap = array(
'jquery.js' => false,
'jquery.ui.js' => false,
'jquery.yiiactiveform.js' => false,
);
in my actionShowForm.
I want to update some fields in my form, after retrieving data from a db using ajax & json.
This is the code:
In my form:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'anagrafica-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'codicefiscale'); ?>
<?php echo $form->textField($model,'codicefiscale',array('size'=>20,'maxlength'=>16)); ?>
<?php echo $form->error($model,'codicefiscale'); ?>
<div id="bottone_ricerca" style="display:inline;">
<?php
echo CHtml::ajaxButton( 'Ricerca',
$this->createUrl('anagrafica/popolaAnagrafica'),
array(
'type' => 'POST',
'datatype' => 'json',
'data' => array('codfisc' => 'js:$(\'#AnagraficaForm_codicefiscale\').val()'),
'success' => 'function(response){
$("#cand").html(response);
$("#'.CHTML::activeId($model,'cognome').'").val(response.cognome);
$("#'.CHTML::activeId($model,'nome').'").val(response.nome);
$("#'.CHTML::activeId($model,'email').'").val(response.email);
}'
),
array()
);
?>
</div>
<div id="cand">
</div>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cognome'); ?>
<?php echo $form->textField($model,'cognome',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'cognome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nome'); ?>
<?php echo $form->textField($model,'nome',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'nome'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'indirizzo'); ?>
<?php echo $form->textField($model,'indirizzo',array('size'=>35,'maxlength'=>30)); ?>
<?php echo $form->error($model,'indirizzo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cap'); ?>
<?php echo $form->textField($model,'cap',array('size'=>10,'maxlength'=>5)); ?>
<?php echo $form->error($model,'cap'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'comune'); ?>
<?php echo $form->textField($model,'comune',array('size'=>25,'maxlength'=>20)); ?>
<?php echo $form->error($model,'comune'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'provincia'); ?>
<?php echo $form->textField($model,'provincia',array('size'=>5,'maxlength'=>2)); ?>
<?php echo $form->error($model,'provincia'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'telefono'); ?>
<?php echo $form->textField($model,'telefono',array('size'=>20,'maxlength'=>15)); ?>
<?php echo $form->error($model,'telefono'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Inserisci'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
In my controller:
public function actionPopolaAnagrafica()
{
$codfisc = Yii::app()->request->getParam('codfisc');
echo $codfisc;
if (Yii::app()->request->isAjaxRequest) {
if ($codfisc == '') {
echo CJSON::encode(array(
'error' => 'true',
'status' => 'Richiesta non valida.'
));
Yii::app()->end();
} else {
//$sql = "SELECT * FROM user WHERE username = ':codfisc'";
$sql = "SELECT * FROM user WHERE username = '".$codfisc . "'";
$cmd = Yii::app()->db->createCommand($sql);
//$cmd->bindParam(":codfisc", $codfisc, PDO::PARAM_STR);
$result = $cmd->queryRow();
$sql2 = $cmd->text;
if($result) {
echo CJSON::encode(array(
'error' => 'false',
'status' => 'Codice Fiscale esistente',
'username' => $result['username'],
'cognome' => $result['cognome'],
'nome' => $result['nome'],
'email' => $result['email']
)
);
Yii::app()->end();
} else {
echo CJSON::encode(array(
'error' => 'true',
'status' => 'Il codice fiscale ' . $codfisc . ' non esiste. SQL = ' . $sql2 . '.'
));
Yii::app()->end();
}
}
}
I can't update fields. The response is:
xxxyyyddxdd{"error":"false","status":"Codice Fiscale
esistente","username":"xxxyyyddxdd","cognome":"Cognome","nome":"Nome","email":"prova#email.it"}
but it should be:
{"error":"false","status":"Codice Fiscale
esistente","username":"xxxyyyddxdd","cognome":"Cognome","nome":"Nome","email":"prova#email.it"}
Where's my mistake?
Thanks
You need to remove the following line:
echo $codfisc;
(second line in function actionPopolaAnagrafica)
public function actionPopolaAnagrafica()
{
$codfisc = Yii::app()->request->getParam('codfisc');
//this LINE!!!!!!!!!!!!!!!!!!!!!!!
echo $codfisc;
Change :
'success' => 'function(response){
$("#cand").html(response);
$("#'.CHTML::activeId($model,'cognome').'").val(response.cognome);
With this :
'success' => 'function(response){
$("#cand").html(response);
var obj = jQuery.parseJSON( response );
console.log(obj.cognome);
$("#'.CHTML::activeId($model,'cognome').'").val(obj.cognome);
Parse JSON data before you put in HTML value.
Use console.log(obj.cognome); to debug value in chrome.
I passed more than 4 hours seeking where is the error. but nothing found
My view inscriresalle.php :
<div class="widget-box">
<div class="widget-title">
<span class="icon">
<i class="icon-align-justify"></i>
</span>
<h5><?php echo empty($participant_salle->id) ? 'Nouveau Agent OCP:' : 'Modification de: ' . $participant_salle->nom.' '.$participant_salle->prenom; ?></h5>
</div>
<div class="widget-content nopadding">
<div class="form-horizontal" name="basic_validate" id="basic_validate" novalidate="novalidate">
<?php echo form_open(); ?>
<div <?php if(form_error('matricule')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Matricule :</label>
<div class="controls">
<?php echo form_input('matricule', set_value('matricule', $this->input->get('matricule'))); ?>
<span class="help-inline"><?php echo form_error('matricule'); ?></span>
</div>
</div>
<div <?php if(form_error('nom')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Nom :</label>
<div class="controls">
<?php echo form_input('nom', set_value('nom', $this->input->get('nom'))); ?>
<span class="help-inline"><?php echo form_error('nom'); ?></span>
</div>
</div>
<div <?php if(form_error('prenom')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Prénom :</label>
<div class="controls">
<?php echo form_input('prenom', set_value('prenom', $this->input->get('prenom'))); ?>
<span class="help-inline"><?php echo form_error('prenom'); ?></span>
</div>
</div>
<div <?php if(form_error('beneficiaire')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Bénéficiaire :</label>
<div class="controls">
<label><?php echo form_radio('beneficiaire', 'Agent', $this->input->get('beneficiaire') == 'Agent') ?> Agent </label>
<label><?php echo form_radio('beneficiaire', 'Conjoint', $this->input->get('beneficiaire') == 'Conjoint') ?> Conjoint </label>
<label><?php echo form_radio('beneficiaire', 'Enfant', $this->input->get('beneficiaire') == 'Enfant') ?> Enfant </label>
<span class="help-inline"><?php echo form_error('beneficiaire'); ?></span>
</div>
</div>
<div <?php if(form_error('sexe')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Sexe :</label>
<div class="controls">
<label><?php echo form_radio('sexe', 'M', $this->input->get('sexe') == 'M') ?> Masculin </label>
<label><?php echo form_radio('sexe', 'F', $this->input->get('sexe') == 'F') ?> Féminin </label>
<span class="help-inline"><?php echo form_error('sexe'); ?></span>
</div>
</div>
<div <?php if(form_error('date_naissance')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Date de Naissance :</label>
<div class="controls">
<input type="text" name="date_naissance" id="date1" value="<?php echo set_value('date_naissance', $this->input->get('dateNaissance')); ?>" />
<span class="help-inline"><?php echo form_error('date_naissance'); ?></span>
</div>
</div>
<div <?php if(form_error('telephone')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Téléphone :</label>
<div class="controls">
<?php echo form_input('telephone', set_value('telephone', $participant_salle->telephone)); ?>
<span class="help-inline"><?php echo form_error('telephone'); ?></span>
</div>
</div>
<div <?php if(form_error('date_inscription_salle')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Date inscription :</label>
<div class="controls">
<input type="text" name="date_inscription_salle" id="date2" value="<?php echo set_value('date_inscription_salle', $participant_salle->date_inscription_salle); ?>" />
<span class="help-inline"><?php echo form_error('date_inscription_salle'); ?></span>
</div>
</div>
<div <?php if(form_error('salle_debut_periode')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Début période :</label>
<div class="controls">
<input type="text" name="salle_debut_periode" id="date3" value="<?php echo set_value('salle_debut_periode', $participant_salle->salle_debut_periode); ?>" />
<span class="help-inline"><?php echo form_error('salle_debut_periode'); ?></span>
</div>
</div>
<div <?php if(form_error('salle_fin_periode')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Fin période :</label>
<div class="controls">
<input type="text" name="salle_fin_periode" id="date4" value="<?php echo set_value('salle_fin_periode', $participant_salle->salle_fin_periode); ?>" />
<span class="help-inline"><?php echo form_error('salle_fin_periode'); ?></span>
<span class="help-block">
</div>
</div>
<script type="text/javascript">// <![CDATA[
var qp = new Array();
var tarif = new Array();
var datestart = document.getElementById('date3');
var dateend = document.getElementById('date4');
$(document).ready(
// a chaque changement de discipline on obtien l'id du tableau discipline.
function(){
$('#country').change(function(){ //any select change on the dropdown with id country trigger this code
$("#cities > option").remove(); //first of all clear select items
var salle_nom = $('#country').val(); // here we are taking country id of the selected one.
$.ajax({
type: "POST",
url: "http://localhost/public_html/admin/dropdown_salle/get_cities/"+salle_nom, //here we are calling our user controller and get_cities method with the country_id
dataType : "json",
success: function(disciplines) //we're calling the response json array 'cities'
{
var discipline = new Array();
for (i=0; i<disciplines.length; ++i) {
// remplisage des 3 tableaux :discipline, tarif, et qp_agent
discipline[i] = disciplines[i].discipline+' pour '+disciplines[i].categorie_tarif;
qp[i] = disciplines[i].qp_agent;
tarif[i] = disciplines[i].tarif;
}
$.each(discipline,function(id,value) //here we're doing a foeach loop round each value with id as the key and value as the value
{
var opt = $('<option />'); // here we're creating a new select option with for each value
opt.val(id);
opt.text(value);
$('#cities').append(opt); //here we will append these new select options to a dropdown with the id 'cities'
});
}
});
});
function qp(qp, id) {
return qp[id];
}
function tarif(tarif, id) {
return tarif[id];
}
$('#cities').change(function () {
var a = $(this).find('option:selected').attr('value');
//here i retrieve the qp and tarif value corresponds to my 'discipline' choosen.
var qpValue = qp(qp, a);
var tarifValue = tarif(tarif, a);
var start = datestart.value;
var end = dateend.value;
var date1 = new Date(start);
var date2 = new Date(end);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var diffMonths = Math.round(diffDays / 30);
alert('Vous avez Selectionnez '+diffMonths+' mois');
var finalresult = Math.round(diffMonths*qpValue*tarifValue);
document.getElementById("salle_montant_paye").value = finalresult;
});
});
// ]]>
</script>
<?php $countries['#'] = 'Aucun choix'; ?>
<?php
foreach ($countries as $k => $v) {
unset ($countries[$k]);
$new_key1 = $v;
$countries[$new_key1] = $v;
}
?>
<div <?php if(form_error('salle_nom')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?> >
<label class="control-label">Nom de la Salle :</label>
<div class="controls">
<?php echo form_dropdown('salle_nom', $countries , $this->input->post('salle_nom') ? $this->input->post('salle_nom') : $participant_salle->salle_nom , 'id="country"'); ?>
<span class="help-inline"><?php echo form_error('salle_nom'); ?></span>
</div>
</div>
<?php $cities['#'] = 'Aucun choix'; ?>
<div <?php if(form_error('salle_discipline')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?> >
<label class="control-label">Discipline et type:</label>
<div class="controls">
<?php echo form_dropdown('salle_discipline', $cities , $this->input->post('salle_discipline') ? $this->input->post('salle_discipline') : $participant_salle->salle_discipline , 'id="cities"'); ?>
<span class="help-inline"><?php echo form_error('salle_discipline'); ?></span>
</div>
</div>
<div <?php if(form_error('salle_montant_paye')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Montant à payé :</label>
<div class="controls">
<input type="text" name="salle_montant_paye" id="salle_montant_paye" value="<?php set_value('salle_montant_paye', $participant_salle->salle_montant_paye) ?> "></input>
<span class="help-inline"><?php echo form_error('salle_montant_paye'); ?></span>
</div>
</div>
<div <?php if(form_error('salle_versement_espec')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Versement espéce :</label>
<div class="controls">
<?php echo form_input('salle_versement_espec', set_value('salle_versement_espec', $participant_salle->salle_versement_espec)); ?>
<span class="help-inline"><?php echo form_error('salle_versement_espec'); ?></span>
</div>
</div>
<div <?php if(form_error('salle_versement_cheq')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Versement chèque :</label>
<div class="controls">
<?php echo form_input('salle_versement_cheq', set_value('salle_versement_cheq', $participant_salle->salle_versement_cheq)); ?>
<span class="help-inline"><?php echo form_error('salle_versement_cheq'); ?></span>
</div>
</div>
<div <?php if(form_error('salle_numero_cheq')) { echo 'class="control-group error"'; } else {echo 'class="control-group"';} ?>>
<label class="control-label">Numéro de chèque :</label>
<div class="controls">
<?php echo form_input('salle_numero_cheq', set_value('salle_numero_cheq', $participant_salle->salle_numero_cheq)); ?>
<span class="help-inline"><?php echo form_error('salle_numero_cheq'); ?></span>
</div>
</div>
<div class="form-actions">
<?php echo form_submit('submit', 'Enregistrer', 'class="btn btn-success"'); ?>
</div>
<?php echo form_close();?>
</div>
</div>
</div>
</br>
My controller agent.php :
public function inscriresalle ($id = NULL) {
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_salle'] = $this->participantsalle_m->get($id);
count($this->data['participant_salle']) || $this->data['errors'][] = 'Agent non trouvé';
}
else {
$this->data['participant_salle'] = $this->participantsalle_m->get_new();
}
$this->load->model('salle_m');
$this->data['countries'] = $this->salle_m->get_countries();
// Set up the form
$rules = $this->participantsalle_m->rules_participantsalle;
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->participantsalle_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_salle', 'salle_debut_periode', 'salle_fin_periode', 'salle_montant_paye', 'salle_versement_espec', 'salle_versement_cheq', 'salle_numero_cheq'));
$this->participantsalle_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresalle';
$this->load->view('admin/_layout_main', $this->data);
}
My model participantsalle_m.php :
<?php
class Participantsalle_M extends MY_Model
{
protected $_table_name = 'participants_salle';
protected $_order_by = 'id';
public $rules_participantsalle = array(
'matricule' => array(
'field' => 'matricule',
'label' => 'Matricule',
'rules' => 'trim|required|xss_clean'
),
'nom' => array(
'field' => 'nom',
'label' => 'Nom',
'rules' => 'trim|required|xss_clean'
),
'prenom' => array(
'field' => 'prenom',
'label' => 'Prénom',
'rules' => 'trim|required|xss_clean'
),
'beneficiaire' => array(
'field' => 'beneficiaire',
'label' => 'Bénéficiaire',
'rules' => 'trim|required|xss_clean'
),
'sexe' => array(
'field' => 'sexe',
'label' => 'Sexe',
'rules' => 'trim|required|xss_clean'
),
'telephone' => array(
'field' => 'telephone',
'label' => 'Téléphone',
'rules' => 'trim|xss_clean'
),
'date_naissance' => array(
'field' => 'date_naissance',
'label' => 'Date de naissance',
'rules' => 'trim|required|xss_clean'
),
'date_inscription_salle' => array(
'field' => 'date_inscription_salle',
'label' => 'Date inscription a la salle',
'rules' => 'trim|required|xss_clean'
),
'salle_debut_periode' => array(
'field' => 'salle_debut_periode',
'label' => 'Début période',
'rules' => 'trim|required|xss_clean'
),
'salle_fin_periode' => array(
'field' => 'salle_fin_periode',
'label' => 'Fin période',
'rules' => 'trim|required|xss_clean'
),
'salle_nom' => array(
'field' => 'salle_nom',
'label' => 'Nom de la salle',
'rules' => 'trim|required|xss_clean'
),
'salle_discipline' => array(
'field' => 'salle_discipline',
'label' => 'Discipline de la salle',
'rules' => 'trim|required|xss_clean'
),
'salle_montant_paye' => array(
'field' => 'salle_montant_paye',
'label' => 'Montant à payé',
'rules' => 'trim|required|xss_clean'
),
'salle_versement_espec' => array(
'field' => 'salle_versement_espec',
'label' => 'Versement éspece',
'rules' => 'trim|required|xss_clean'
),
'salle_versement_cheq' => array(
'field' => 'salle_versement_cheq',
'label' => 'Versement chèque',
'rules' => 'trim|required|xss_clean'
),
'salle_numero_cheq' => array(
'field' => 'salle_numero_cheq',
'label' => 'Numéro de chèque',
'rules' => 'trim|required|xss_clean'
),
);
public function get_new()
{
$participant_salle = new stdClass();
$participant_salle->matricule = '';
$participant_salle->nom = '';
$participant_salle->prenom = '';
$participant_salle->beneficiaire = '';
$participant_salle->sexe = '';
$participant_salle->telephone = '';
$participant_salle->date_naissance = '';
$participant_salle->date_inscription_salle = '';
$participant_salle->salle_debut_periode = '';
$participant_salle->salle_fin_periode = '';
$participant_salle->salle_nom = '';
$participant_salle->salle_discipline = '';
$participant_salle->salle_montant_paye = '';
$participant_salle->salle_versement_espec = '';
$participant_salle->salle_versement_cheq = '';
$participant_salle->salle_numero_cheq = '';
return $participant_salle;
}
function __construct ()
{
parent::__construct();
}
}
Everything seems to be good but i realy don't find error, why data don't saved on database.
My database structure is :
id
- nom
- prenom
- beneficiaire
- sexe
- telephone
- date_naissance
- date_inscription_salle
- salle_debut_periode
- salle_fin_periode
- salle_nom
- salle_discipline
- salle_montant_paye
- salle_versement_espec
- salle_versement_cheq
- salle_numero_cheq
Maybe it's not my day for coding, i don't see the probleme, Any help please?
the function save() on MY_Model :
public function save($data, $id = NULL){
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
print_r($id);
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
This line breaks it for me.
count($this->data['participant_salle']) || $this->data['errors'][] = 'Agent non trouvé';
try
if (empty($this->data['participant_salle'])){
$this->data['errors'][] = 'Agent non trouvé';
}
I am using Yii framework and I want to make a registration page. I have created everything that was needed and when I register user I am getting no error at all but I can't find a record in database. so can you help me? here is my code:
SiteController.php :
public function actionRegister()
{
$model=new RegisterForm;
// uncomment the following code to enable ajax-based validation
if(isset($_POST['ajax']) && $_POST['ajax']==='register-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
if(isset($_POST['RegisterForm']))
{
$model->attributes=$_POST['RegisterForm'];
if($model->validate())
{
$user = new User;
$user->username = $_POST['RegisterForm']['username'];
$this->password = $_POST['RegisterForm']['password'];
$this->salt = Security::GenerateSalt(128);
$user->password = hash('sha512', $password.$salt);
$user->question = $_POST['RegisterForm']['question'];
$user->answer = $_POST['RegisterForm']['answer'];
$user->salt = $salt;
$user->email = $_POST['RegisterForm']['email'];
$user->fullname = $_POST['RegisterForm']['fullname'];
$user->birth = $_POST['RegisterForm']['dd'].'/'.$_POST['RegisterForm']['mm'].'/'.$_POST['RegisterForm']['yy'];
$user->avatar = CUploadedFile::getInstance($model,'image');
$user->about = $_POST['RegisterForm']['about'];
$user->sighnup = date('d/m/y');
$user->login = date('d/m/y');
if($user->save())
{
$model->image->saveAs('images/users/localFile.jpg');
// redirect to success page
}
$activation = new Activation;
$record = User::model()->findByAttributes(array('username'=>$_POST['RegisterForm']['username']));
$activation->user = $record->id;
$activation->code = Security::ActivationCode(32);
$activation->save();
}
}
$this->render('register',array('model'=>$model));
}
RegisterForm.php a verification model:
class RegisterForm extends CFormModel
{
public $username;
public $password;
public $password2;
public $question;
public $answer;
public $email;
public $fullname;
public $avatar;
public $about;
public $dd;
public $mm;
public $yy;
public $verifyCode;
public function rules()
{
return array(
array('username, password, password2, question, answer, email, fullname, dd, mm, yy', 'required'),
array('username','length','min'=>4),
array('username','length','max'=>16),
array('username', 'filter', 'filter'=>'strtolower'),
array('username', 'ext.alpha', 'allowSpaces'=>'flase', 'allowNumbers'=>'true', 'allAccentedLetters'=>'false'),
array('username', 'unique', 'attributeName'=> 'username', 'className'=>'User' ,'caseSensitive' => 'false'),
array('password', 'length', 'min' =>6),
array('password', 'length', 'max' =>32),
array('password2', 'compare', 'allowEmpty' => 'false', 'compareAttribute' => 'password'),
array('question', 'length', 'min' =>10),
array('question', 'length', 'max' =>128),
array('answer', 'length', 'min' =>4),
array('answer', 'length', 'max' =>64),
array('email', 'length', 'min' =>8),
array('email', 'length', 'max' =>128),
array('email', 'email'),
array('email', 'unique', 'attributeName'=> 'email', 'className'=>'User' ,'caseSensitive' => 'false'),
array('fullname','length','min'=>6),
array('fullname','length','max'=>64),
array('fullname', 'ext.alpha', 'allowNumbers'=>'false', 'allowSpaces'=>'true', 'allAccentedLetters'=>'false'),
array('avatar', 'file',
'types'=>'jpg, gif, png',
'maxSize'=>1024 * 1024 * 2,
'tooLarge'=>'The file was larger than 2MB. Please upload a smaller file.',
'wrongType'=>'Please upload only images in the format jpg, gif, png',
'tooMany'=>'You can upload only 1 avatar',
'on'=>'upload'),
array('about','length','max'=>384),
array('dd', 'numerical', 'allowEmpty'=>'false', 'integerOnly'=>'true', 'min'=>'1', 'max'=>'31'),
array('dd', 'FilterDay'),
array('mm', 'numerical', 'allowEmpty'=>'false', 'integerOnly'=>'true', 'min'=>'0', 'max'=>'12'),
array('mm', 'FilterMonth'),
array('yy', 'numerical', 'allowEmpty'=>'false', 'integerOnly'=>'true', 'min'=>'1900', 'max'=>'2008'),
array('yy', 'FilterYear'),
array('verifyCode', 'captcha', 'allowEmpty'=>!extension_loaded('gd')),
);
}
public function attributeLabels()
{
return array(
'username' => 'Username',
'password' => 'Passwrod',
'password2' => 'Verify Password',
'email' => 'Email',
'fullname' => 'Full Name',
'dd' => 'Day',
'mm' => 'Month',
'yy' => 'Year',
);
}
}
Register.php a view file:
<div class="form">
<h1><?php echo($data); ?></h1>
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'register-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username'); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo CHtml::activePasswordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password2'); ?>
<?php echo CHtml::activePasswordField($model,'password2'); ?>
<?php echo $form->error($model,'password2'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
<?php echo $form->error($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'fullname'); ?>
<?php echo $form->textField($model,'fullname'); ?>
<?php echo $form->error($model,'fullname'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'question'); ?>
<?php echo $form->textField($model,'question'); ?>
<?php echo $form->error($model,'question'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'answer'); ?>
<?php echo $form->textField($model,'answer'); ?>
<?php echo $form->error($model,'answer'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'avatar'); ?>
<?php echo CHtml::activeFileField($model, 'avatar'); ?>
<?php echo $form->error($model,'avatar'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'about'); ?>
<?php echo CHtml::activeTextArea($model, 'about'); ?>
<?php echo $form->error($model,'about'); ?>
</div>
<?php
function getYear($value1 = 1900, $value2 = 2008)
{
$data = array();
for ($i = $value2; $i >= $value1; $i--){
$data[$i] = (string)$i;
}
return $data;
}
function getMonth()
{
$data = array();
for ($i = 1; $i <= 12; $i++){
$data[$i] = (string)$i;
}
return $data;
}
function getDays()
{
$data = array();
for ($i = 1; $i <= 31; $i++){
$data[$i] = (string)$i;
}
return $data;
}
?>
<div class="row">
<?php echo $form->labelEx($model,'dd'); ?>
<?php echo CHtml::activeDropDownList($model,'dd', getDays()); ?>
<?php echo $form->error($model,'dd'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'mm'); ?>
<?php echo CHtml::activeDropDownList($model,'mm', getMonth()); ?>
<?php echo $form->error($model,'mm'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'yy'); ?>
<?php echo CHtml::activeDropDownList($model,'yy', getYear()); ?>
<?php echo $form->error($model,'yy'); ?>
</div>
<?php if(extension_loaded('gd')): ?>
<div class="simple">
<?php echo CHtml::activeLabel($model,'verifyCode', array('style'=>'width:150px;')); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo CHtml::activeTextField($model,'verifyCode'); ?>
</div>
<p class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</p>
</div>
<?php endif; ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
I am getting no errors at all but the fact is that there is no post in database at all, please help me
--------------------------------------------------------Edited---------------------------------------------------------------------
I found out what was the problem. the problem is that I can't insert an information in database via active record. When I type:
$user = new User;
$user->username = 'irakli';
$user->save();
it runs without errors but it doesn't insert anything in database. But the fact is that Database connection is active because I can read raws from database via Active Record, the problem is that I can't insert a new data in database via Active Record.
So any ideas?
Try this:
$user = new User;
$user->username = 'irakli';
if ($user->save())
{
echo "user record saved to the db";
}
else
{
var_dump($user->getErrors());
}