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. My table is job_seeker_profile with fields id,user_id,contact_no,gender,dob,mstatus,address.I can't update data by form posting.
My controller is sitecontroller.php
class SiteController extends Controller
{
public function actionpersonal()
{
$user_id = trim($_GET['id']);
$model = new jobseekerprofile();
$model = jobseekerprofile::model()->find(array(
'select' => 'contact_no,address', "condition" => "user_id=$user_id",
'limit' => 1,));
$model = $this->loadModel($user_id);
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));
}
public function loadModel($user_id)
{
echo $model = jobseekerprofile::model()->findByPk($user_id);
if ($model === null)
throw new CHttpException(404, 'The requested page does not exist.');
return $model;
}
}
view-personal.php
<div class="form">
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'login-form',
'enableClientValidation' => false,
'htmlOptions' => array(),
'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->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(); ?>
model-jobseekerprofile.php
rules in model
public function rules()
{
return array(
array('contact_no,gender,dob,address,mstatus','required'),
);
}
Anybody help me?
You need to use uppercases.
Jobseekerprofile.php and $model = new Jobseekerprofile(); at least, I'd even call it: JobseekerProfile.php and $model = new JobseekerProfile(); or something.
Example controller (not tested):
public function actionPersonal($id) {
$model = Jobseekerprofile::model()->findByPk($id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['Jobseekerprofile'];
if ($model->save())
$this->redirect(array('view', 'id' => $model->id));
}
$this->render('personal', array(
'model' => $model,
));
}
Also you could use the Gii posibilities of Yii for these standard forms. It will generate forms based on your database and the relations in it.
Related
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
));
}
I'm not sure how to describe my question. First I added a button at my CCGridview:
array(
'class'=>'CButtonColumn',
'template' => '{view}{update}{delete}{upload_image}',
'buttons' => array(
'upload_image' => array(
'label' => 'upload foto',
'url' => 'Yii::app()->createUrl("/image/create",
array("product_id" => $data->product_id))',
),
),
),
when I clicked it will bring me to the /image/create view which has a product_id value. For example on that gridview I clicked record number 7, so the url would be:
(webApp)/index.php/image/create?product_id=7
Since it rendering a partial _form so the form has the attribute according to the image table which has this attributes: id, title, filename, product_id.
So the view will be something like:
<div class="row">
<?php echo $form->labelEx($model,'title'); ?>
<?php echo $form->textField($model,'title',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'title'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'filename'); ?>
<?php echo $form->fileField($model,'filename',array('size'=>45,'maxlength'=>45)); ?>
<?php echo $form->error($model,'filename'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'product_id'); ?>
<?php echo $form->textField($model,'product_id'); ?>
<?php echo $form->error($model,'product_id'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
My question is, how do we use the value from the url which I mentioned before is 7 (../create?product_id=7) into the product_id attribute without have to type it at provided textField?
In other word I will remove this from the view:
<div class="row">
<?php echo $form->labelEx($model,'product_id'); ?>
<?php echo $form->textField($model,'product_id'); ?>
<?php echo $form->error($model,'product_id'); ?>
</div>
But when i submitted, the form the value (7) should have been passed/saved at product_id field.
Added:
My controller actionCreate is
//...
public function actionCreate()
{
$dir = Yii::app()->basePath . '/../productimages/';
$uploaded = false;
$model=new Image();
if(isset($_POST['Image']))
{
$model->attributes=$_POST['Image'];
$tempSave=CUploadedFile::getInstance($model,'filename');
if($model->validate())
{
$uploaded = $tempSave->saveAs($dir.'/'.$tempSave->getName());
$this->redirect(array('/products/index'));
}
}
$this->render('index', array(
'model' => $model,
'uploaded' => $uploaded,
'dir' => $dir,
));
}
That's it. Many thanks..
modify your controller this way:
if(isset($_POST['Image']))
{
$model->attributes=$_POST['Image'];
$tempSave=CUploadedFile::getInstance($model,'filename');
if($model->validate())
{
$uploaded = $tempSave->saveAs($dir.'/'.$tempSave->getName());
$this->redirect(array('/products/index'));
}
} else {
//initialize defaults
$model->product_id=intval($_GET['product_id']);
}
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.
I have 2 templates,
- /view/opinions/add.ctp - add form
- /view/opinions/list.ctp - displays opinions
and I want them diplay in /views/opinions/index.ctp is it possible?
Is the only way to do it by $this -> element() ? if so, can I include templates from /view/opinions instead of /view/elements ?
#edit
OpinionsController.php
class OpinionsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
var $name = 'Opinions';
function index() {
$opinions = $this->Opinion->find('all');
if(isset($this->params['requested'])) {
return $opinions;
}
$this->set('opinions', $opinions);
}
public function add() {
if ($this->request->is('post')) {
$this->Opinion->create();
if ($this->Opinion->save($this->request->data)) {
$this->Session->setFlash(__('saved.'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('Unable to add.'));
}
}
}
}
index.ctp
$this->extend('/Opinions/view');
$this->extend('/Opinions/add');
add.ctp
echo $this->Form->create('Opinion', array('type' => 'file'));
echo $this->Form->input('author_name', array('label' => 'Imię'));
echo $this->Form->input('author_signature', array('label' => 'Podpis'));
echo $this->Form->input('text', array('rows' => '5', 'cols' => '30', 'label' => 'Opinia'));
echo $this->Form->input('author_pic', array('type' => 'file', 'label' => 'Zdjęcie'));
echo $this->Form->input('author_pic_dir', array('type' => 'hidden'));
echo $this->Form->end('Dodaj opinię');
view.ctp
`
<?php foreach ($opinions as $opinion): ?>
<div class="opinion">
<div class="author">
<div class="pic"><?php echo $this->Html->image("defaultAvatar.jpg", array('alt' => $opinion['Opinion']['author_name'])); ?></div>
<div class="signature"><b><?= $opinion['Opinion']['author_name']?></b><br><i><?= $opinion['Opinion']['author_signature']?></i></div>
</div>
<div class="text">
<blockquote><p><?= $opinion['Opinion']['text']?></p></blockquote>
</div>
<div class="clear"><!-- . --></div>
</div>
<div class="clear"><!-- . --></div>
<?php endforeach; ?>
<?php unset($post); ?>
`
In web frameworks like CakePHP, we want to keep our code DRY. In order to do what you want, I think the better approach is to create elements to list your opinions and another with the form to add a new one.
Then in index.ctp you would put these two elements. And in add.ctp you put only the element with the form and in view.ctp you should put the element that list the opinions.
I have a CActiveForm which when submitted should make a second CActiveForm become visible. I know how to change the htmlOptions of the form when its created but not how to access it via the controller.
My View with two forms. The second form has visibility:hidden
<div class="form">
<?php
$numberForm = $this->beginWidget('CActiveForm', array(
'id' => 'addnumber-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
));
?>
<p class="note"><?php echo UserModule::t('Fields with <span class="required">*</span> are required.'); ?></p>
<?php echo $numberForm->errorSummary($numberModel); ?>
<div class="row">
<?php echo $numberForm->labelEx($numberModel, 'number'); ?>
<?php echo $numberForm->textField($numberModel, 'number'); ?>
<?php echo $numberForm->error($numberModel, 'number'); ?>
<?php
echo CHtml::submitButton(UserModule::t("Verify"), array(
"class" => "btn btn-success"
));
?>
</div>
<?php $this->endWidget(); ?>
<?php
$verifyForm = $this->beginWidget('CActiveForm', array(
'id' => 'verify-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array("style"=>"visibility: hidden"),
));
?>
<?php echo $verifyForm->errorSummary($verifyModel); ?>
<p>A authorisation code has been sent to your phone. Please enter it below. If you don't receive a text message make sure you entered your number correctly and try again</p>
<div class="row">
<?php echo $verifyForm->labelEx($verifyModel, 'authcodeUser'); ?>
<?php echo $verifyForm->textField($verifyModel, 'authcodeUser'); ?>
<?php echo $verifyForm->error($verifyModel, 'authcodeUser'); ?>
<?php
echo CHtml::submitButton(UserModule::t("Confirm"), array(
"class" => "btn btn-success"
));
?>
<?php
foreach(Yii::app()->user->getFlashes() as $key => $message) {
echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
}
?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
My controller for these forms
public function actionAddnumber(){
$numberModel = new UserAddNumber;
$verifyModel = new UserVerifyNumber;
if (Yii::app()->user->id) {
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='addnumber-form')
{
echo UActiveForm::validate($numberModel);
Yii::app()->end();
}
if(isset($_POST['UserAddNumber'])) {
$numberModel->attributes=$_POST['UserAddNumber'];
if($numberModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNo = $numberModel->number;
$profile->save();
//MAKE $verifyForm visibility to visible uring htmlOptions
Yii::app()->session['authcode'] = '4444';
}
}
if(isset($_POST['UserVerifyNumber'])) {
$verifyModel->attributes=$_POST['UserVerifyNumber'];
if($verifyModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNoVerified = True;
$profile->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("Your mobile number has been verified"));
$this->redirect(array("profile"));
}
}
}
$this->render('addnumber', array('numberModel'=>$numberModel, 'verifyModel' => $verifyModel));
}
It looks like you could just create a new variable for whether or not to show the second form and then pass it to the view. Here is your controller:
public function actionAddnumber(){
$numberModel = new UserAddNumber;
$verifyModel = new UserVerifyNumber;
$formVisibility = "hidden";
if (Yii::app()->user->id) {
// ajax validator
if(isset($_POST['ajax']) && $_POST['ajax']==='addnumber-form')
{
echo UActiveForm::validate($numberModel);
Yii::app()->end();
}
if(isset($_POST['UserAddNumber'])) {
$numberModel->attributes=$_POST['UserAddNumber'];
if($numberModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNo = $numberModel->number;
$profile->save();
//MAKE $verifyForm visibility to visible uring htmlOptions
$formVisibility = "visible";
Yii::app()->session['authcode'] = '4444';
}
}
if(isset($_POST['UserVerifyNumber'])) {
$verifyModel->attributes=$_POST['UserVerifyNumber'];
if($verifyModel->validate()) {
$profile = Profile::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
$profile->mobileNoVerified = True;
$profile->save();
Yii::app()->user->setFlash('profileMessage',UserModule::t("Your mobile number has been verified"));
$this->redirect(array("profile"));
}
}
}
$this->render('addnumber', array('numberModel'=>$numberModel, 'verifyModel' => $verifyModel, 'formVisibility' => $formVisibility));
}
And here is the first part of your second form:
<?php
$verifyForm = $this->beginWidget('CActiveForm', array(
'id' => 'verify-form',
'enableAjaxValidation' => true,
'clientOptions' => array(
'validateOnSubmit' => true,
),
'htmlOptions' => array("style"=>"visibility: ".$formVisibility),
));
?>
[edit] To make sure I am answering your question, I should add that I've never seen any way of changing the htmlOptions from the controller directly. That's why I proposed this solution instead.