Cannot edit perticular user's data using yii framework - php

I am new in yii framework. I am doing update operation using yii framework. I have controller with name sitecontroller.php, model jobseekerprofile.php, view personal.php. I can't update data by form posting.
My controller is sitecontroller.php
<?php
class SiteController extends Controller
{
public function actionpersonal()
{
$user_id = trim($_GET['id']);
$model = new jobseekerprofile();
if(isset($_POST['jobseekerprofile']))
{
$model->attributes=$_POST['jobseekerprofile'];
if($model->save())
{
$this->redirect(array('profile','user_id'=>$model->user_id));
}
}
$model=jobseekerprofile::model()->find(array(
'select'=>'contact_no,address',"condition"=>"user_id=$user_id",
'limit'=>1,));
$this->render('personal',array('model' =>$model));
}
}
?>
My view page personal.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableClientValidation'=>true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
'clientOptions'=>array(
'validateOnSubmit'=>true
),
)); ?>
<?php
foreach(Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
}
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php //echo $form->textField($model,'pp_status', array('value'=>'Open', 'readonly' => 'true')); ?>
<?php echo $form->labelEx($model,'Contact No'); ?>
<?php echo $form->textField($model,'contact_no'); ?>
<?php echo $form->error($model,'contact_no'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Address'); ?>
<?php echo $form->textField($model,'address'); ?>
<?php echo $form->error($model,'address'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Save'); ?>
</div>
<?php $this->endWidget(); ?>
My model jobseekerprofile.php
<?php
class Jobseekerprofile extends CActiveRecord
{
public $contact_no;
public $dob;
public $gender;
public $mstatus;
public $address;
public $user_id;
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'job_seeker_profile';
}
public function rules()
{
return array(
array('contact_no,gender,dob,address,mstatus','required'),
);
}
}
?>
Anybody help me?

Because on each request you create new jobseekerprofile model, then this code will create new jobseekerprofile record each time you submit. Change your action into this:
public function actionpersonal()
{
$user_id = trim($_GET['id']);
$model=jobseekerprofile::model()->find(array(
'select'=>'contact_no,address',"condition"=>"user_id=$user_id",
'limit'=>1,));
if(isset($_POST['jobseekerprofile']))
{
$model->attributes=$_POST['jobseekerprofile'];
if($model->save())
{
$this->redirect(array('profile','user_id'=>$model->user_id));
}
}
$this->render('personal',array('model' =>$model));
}
This should works.

You haven't given the primary key of the user which you want to edit.
Try following
$model=jobseekerprofile::model()->findByPk($id);
$id is the primary key of the table.
Then you can write following
if($model->save())
{
$this->redirect(array('profile','user_id'=>$model->user_id));
}
if you only use $model->save() it will insert data, but not update.

Related

how to insert a form post data into database in yii 1 framework

this is my form in view
<div class="form">
<?php echo CHtml::errorSummary($model); ?>
<div class="row">
<?php echo CHtml::activeLabel($model,'Your Name'); ?>
<?php echo CHtml::activeTextField($model,'regname') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Your Password'); ?>
<?php echo CHtml::activePasswordField($model,'regpass') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Email Address'); ?>
<?php echo CHtml::activePasswordField($model,'regemail') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'Contact'); ?>
<?php echo CHtml::activePasswordField($model,'regcontact') ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('Login'); ?>
</div>
please help me to save this data from my controller to model
this is my model
//-- set Table
public function tableName(){
return 'user';
}
public function attributeLabels()
{
return array(
'username'=>'Your username for the game',
'password'=>'Your password for the game',
'email'=>'Needed in the event of password resets',
);
}
and this is my controller
public function actionRegister2()
{
$model=new RegisterForm;
if(isset($_POST['RegisterForm']))
{
echo 'done';
}
$this->render('register2',array(
'model'=>$model,
));
i an new in yii framework so didn't get a good tutorial for it, please suggest me how i insert the data into database by submitting a form
you can add this code in your controller:
public function actionRegister2()
{
$model=new RegisterForm;
if(isset($_POST['RegisterForm']))
{
$model->attributes = $_POST['RegisterForm'];
if ($model->save()) {
Yii::app()->user->setFlash('success', 'You have successfully added.');
$this->redirect(array('index'));
}
// or if(!$model->save()){ print_r($model->getErrors())}
}
$this->render('register2',array(
'model'=>$model,
));
}

update form with database value in field

I'm newbie.I want to create update form in yii.I created a controller Adminprofile and call the model ProfileForm.In my view 'adminprofile.php' I want to load the value for the admin from the table 'superadmin' in name and password fields.Now It displays only field without values.
I want to use update as $update=update superadmin set username='$username',password='$password' where id='1'
SiteController.php
public function actionAdminprofile()
{
$model=new ProfileForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$name='=?UTF-8?B?'.base64_encode($model->name).'?=';
$password='=?UTF-8?B?'.base64_encode($model->password).'?=';
$this->refresh();
}
}
$this->render('adminprofile',array('model'=>$model));
}
ProfileForm.php (MODEL)
class ProfileForm extends CFormModel
{
public $name;
public $password;
public function rules()
{
return array(
// name, email, subject and body are required
array('name, password', 'required'),
);
}
}
Adminprofile.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
),
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
<?php echo $form->error($model,'name'); ?>
</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 buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div>
<?php endif; ?>

Yii login from index and ajax login captcha error

I would like a user to be able to login to my app at site/index.php with an ajax request when the user provides a correct username and password the first time. If username or password is wrong the first time, it shows a captcha then if all inputs are correct don't show captcha error.
This my code:
loginForm
<?php
/**
* LoginForm class.
* LoginForm is the data structure for keeping
* user login form data. It is used by the 'login' action of 'SiteController'.
*/
class LoginForm extends CFormModel
{
public $username;
public $password;
public $rememberMe;
public $verifyCode;
private $_identity;
/**
* Declares the validation rules.
* The rules state that username and password are required,
* and password needs to be authenticated.
*/
public function rules()
{
return array(
array('username, password', 'required'),
array('rememberMe', 'boolean'),
array('password', 'authenticate'),
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(), 'on' => 'captchaNeed'),
);
}
/**
* Authenticates the password.
* This is the 'authenticate' validator as declared in rules().
*/
public function authenticate($attribute,$params)
{
if (!$this->hasErrors()) {
$this->_identity = new UserIdentity($this->username,$this->password);
if (!$this->_identity->authenticate()) {
$this->addError('password','Incorrect username or password.');
}
}
}
/**
* Logs in the user using the given username and password in the model.
* #return boolean whether login is successful
*/
public function login()
{
if ($this->_identity === null) {
$this->_identity=new UserIdentity($this->username,$this->password);
$this->_identity->authenticate();
}
if ($this->_identity->errorCode===UserIdentity::ERROR_NONE) {
$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
Yii::app()->user->login($this->_identity,$duration);
return true;
} else {
return false;
}
}
site/index
/**
* This is the default 'index' action that is invoked
* when ad action is not explicitly requested by users.
*/
public function actionIndex()
{
// set default layout
$this->layout = 'main';
$loginModel = new LoginForm;
if (Yii::app()->request->isAjaxRequest) {
if (isset(Yii::app()->session['captchaNeed'])) {
LoginModel->scenario = 'captchaNeed';
}
if (isset($_POST['LoginForm'])) {
$loginModel->attributes = $_POST['LoginForm'];
if ($loginModel->validate() && $loginModel->login()) {
echo '<script>window.location= "' . Yii::app()->createUrl('site/dashboard') . '"</script>';
unset(Yii::app()->session['captchaNeed']);
Yii::app()->end();
} else {
Yii::app()->session['captchaNeed'] = true;
$loginModel->scenario = 'captchaNeed';
}
$this->renderPartial('_login', array('model' => $loginModel));
}
}
if (!Yii::app()->request->isAjaxRequest) {
$this->render('index', array('loginModel' => $loginModel));
}
}
siteController actions
public function actions()
{
return array(
'captcha' => array(
'class' => 'CCaptchaAction',
'minLenght' => 4,
'maxLenght' => 4,
'testLimit' => 1,
'backColor' => 0x7D287E,
'foreColor' => 0xFFFFFF,
'height' => 24,
'width' => 100,
'offset' => 1,
),
);
}
view\site\index
<section class="col-xs-8" id="index-login">
<?php if (Yii::app()->user->isGuest) : ?>
<div id="login">
<?php $this->renderPartial('_login', array('model' => $loginModel)) ;?>
</div>
<?php echo CHtml::ajaxSubmitButton(
'Login',
Yii::app()->createUrl('site/index'),
array(
'type' => 'post',
'update' => '#login',
'data' => 'js:$("#login-form").serialize();
),
array(
'id'=>uniqid(),
'class'=>'btn btn-danger',
)
); ?>
<?php endif; ?>
</section>
view\site_login
<?php
/* #var $this SiteController */
/* #var $model LoginForm */
/* #var $form CActiveForm */
$this->pageTitle =Yii::app()->name . ' - Login';
$this->breadcrumbs = array('Login',);
?>
<h1>Login</h1>
<p>Please fill out the following form with your login credentials:</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
)
);?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<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 $form->passwordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
<p class="hint">Hint: You may login with <kbd>demo</kbd>/<kbd>demo</kbd> or <kbd>admin</kbd>/<kbd>admin</kbd>.
</p>
</div>
<?php if (CCaptcha::checkRequirements() && $model->scenario == 'captchaNeed'): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.
</div>
<?php echo $form->error($model,'verifyCode'); ?>
</div>
<?php endif; ?>
<div class="row rememberMe">
<?php echo $form->checkBox($model,'rememberMe'); ?>
<?php echo $form->label($model,'rememberMe'); ?>
<?php echo $form->error($model,'rememberMe'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton('Login'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->

form and validation not working in yii

This is my second question related to YII framework.
I have created a form in YII framework. It is not posting any data. Also validation is not working.
Here is the code of my Controller class:
class RegisterController extends Controller
{
public function actionIndex()
{
$model = new C_regsiter();
if (isset($_POST['C_register'])) {
// do something
$model->data = $_POST['C_register'];
$model->username = $_POST['C_register']['username'];
$model->Password = $_POST['C_register']['Password'];
$model->email = $_POST['C_register']['email'];
if ($model->validate()) {
//do something
}
} else {}
$this->render('index', array(
'model' => $model
));
}
}
Here is the Code of my Model Class:
class C_regsiter extends CFormModel{
public $username;
public $Password;
public $email;
public $data;
protected $id;
public function rules(){
return array(
array('username,password,email','required','on'=>'Register'),
array('email','email'),
);
}
public function attributelabel(){
return array(
'username'=>'User Name',
'password'=>'Password',
'email'=>'Email Address '
);
}
}
Here is the code of my View Class
<div class="form">
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::errorSummary($model); ?>
<div class="row">
<?php echo CHtml::activeLabel($model, 'username'); ?>
<?php echo CHtml::activeTextField($model, 'username'); ?>
<?php echo CHtml::error($model, 'username') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model,'email'); ?>
<?php echo TbHtml::activeEmailField($model , 'email') ?>
<?php echo CHtml::error($model, 'email') ?>
</div>
<div class="row">
<?php echo CHtml::activeLabel($model, 'password'); ?>
<?php echo CHtml::activePasswordField($model, 'Password'); ?>
<?php echo CHtml::error($model, 'password') ?>
</div>
<div class="row">
<?php echo CHtml::submitButton('Register') ;?>
</div>
<?php echo CHtml::endForm(); ?>
</p>
Any help is highly appreciated.
you have to set model attribute try this inside your action
class RegisterController extends Controller
{
public function actionIndex()
{
$model = new C_regsiter();
if (isset($_POST['C_register'])) {
$model->attributes = $_POST['C_register'];
if ($model->validate()) {
//do something
}
}
$this->render('index', array('model' => $model));
}
}
Isn't this because you have got typo in model's name? C_regsiter instead of C_register and you check C_register POST data. Anyway use this.
public function actionIndex()
{
$model = new C_regsiter();
$data = Yii::app()->request->getPost('C_regsiter');
if ($data) {
$model->setAttributes($data);
if ($model->validate()) {
// ....
}
}
$this->render('index', array(
'model' => $model
));
}

DROPDOWN list input values not fetched

I get repeatedly the same error. dropdown data is not fetched from the form. I have my code here
this is my controller:ProductController
{<?php
class ProductController extends Controller
{
public function actionCreate()
{
$model=new CreateForm;
// collect user input data
if(isset($_POST['CreateForm']))
{
$model->attributes=$_POST['CreateForm'];
$model->setAttributes($_POST['CreateForm']);
// validate user input and redirect to the previous page if valid
if($model->validate())
{
$product=new Product;
$product->save();
}
else {
echo "Hi";
}
}
// display the login form
$this->render('create',array('model'=>$model));
}
}
?>}
My model:CreateForm
{<?php
class CreateForm extends CFormModel
{
public $product_name;
public $category_name;
public $description;
public function rules()
{
return array(
array('product_name, category_name, description', 'required'),
array('product_name', 'unique', 'className' => 'Product', 'attributeName' => 'product_name', 'message'=>'This product name is already in use'),
);
}
public function attributeLabels()
{
return array(
'product_name'=>'PRODUCT NAME',
'category_name'=>'CATEGORY',
'description'=>'DESCRIPTION'
);
}
}
?>
}
Category
{
<?php
class Category extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'category';
}
public function attributeLabels()
{
return array(
'category_id'=>'CATEGORY ID',
'category_name'=>'CATEGORY NAME',
);
}
}
?>}
MY view:create.php
{<?php
$this->pageTitle=Yii::app()->name . ' - Create';
$this->breadcrumbs=array(
'Create',
);
?>
<h1>CREATE</h1>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'create-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
));
?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo $form->labelEx($model,'product_name'); ?>
<?php echo $form->textField($model,'product_name'); ?>
<?php echo $form->error($model,'product_name'); ?>
</div>
<div class="row">
<?php
echo $form->labelEx($model,'category_name');
$records = Category::model()->findAll();
$list = CHtml::listData($records, 'category_id', 'category_name');
echo CHtml::DropDownList('category_name', null, $list, array('prompt'=>'select '));
echo $form->error($model,'category_name');
?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'description'); ?></br>
<?php echo $form->textArea($model,'description',array('style' => 'height:100px;width:500px;','maxlength'=>500)); ?>
<?php echo $form->error($model,'description'); ?>
</div>
<div class="row submit">
<?php echo CHtml::submitButton('CREATE'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
}
if I enter all the fields, again it gives an error stating "PLS enter the category"
What you have done is called massive assignment
$model->attributes=$_POST['CreateForm'];
this would not assign all the values and is not safe in handling datas also
the datas would be saved only if they are in safe in the model
you will redeclare the posted data as
$model->attributes=$_POST['CreateForm'];
$model->dropdownname=$_POST['CreateForm']['dropdownname'];
Hope this will help you
http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/#hh2
I think you change your code of dropdown.
<?php
echo $form->labelEx($model,'category_name');
$records = Category::model()->findAll();
$list = CHtml::listData($records, 'category_id', 'category_name');
echo CHtml::DropDownList('category_name', null, $list, array('prompt'=>'select '));
echo $form->error($model,'category_name');
?>
To
<?php
echo $form->labelEx($model,'category_name');
$records = Category::model()->findAll();
$result = array();
foreach($records as $p) {
$result[p->category_id] = p->category_name ;
}
echo CHtml::activeDropDownList($model, 'category_name', $result);
echo $form->error($model,'category_name');
?>
Now you need to check, either your category id or name is coming or not.
Then you debug your controller file, as in given below.
public function actionCreate()
{
$model=new CreateForm;
// collect user input data
if(isset($_POST['CreateForm']))
{
$model->attributes=$_POST['CreateForm'];
echo $model->category_id ;
exit ; // Finish program here, and drop down will be printed.
$model->setAttributes($_POST['CreateForm']);
// validate user input and redirect to the previous page if valid
if($model->validate())
{
$product=new Product;
$product->save();
}
else {
echo "Hi";
}
} // display the login form
$this->render('create',array('model'=>$model));
}
Hope it help you.
Thanks

Categories