everyone. Just like my post, how to create a file only once?
Here's FileController.php
public function actionCreate()
{
$model=new File;
if(isset($_POST['File']))
{
$simpan=$model->nama_file=CUploadedFile::getInstance($model,'nama_file');
if(empty($simpan)){
$model->attributes=$_POST['File'];
$model->save();
}
else{
$model->attributes=$_POST['File'];
$model->pengunggah=Yii::app()->user->id;
$model->nama_file = CUploadedFile::getInstance($model, 'nama_file');
if($model->save()){
$simpan->saveAs(Yii::app()->basePath .
'/../files/' . $model->nama_file.'');
//Yii::app()->user->setFlash('success', "Data berhasil disimpan!");
$this->redirect(array('view','id'=>$model->id_file));
}
}
}
$this->render('create',array(
'model'=>$model,
));
}
After a user create a file, he/she cannot create another, it only allows user to create only once. How to implement it? Thanks a lot
Related
I have a tables named as ideyalar and persons.
In the registration page users can not create their profile if the username taken before.
And every user can create their ideas. But there I to face the problem that; users CAN CREATE the ideas with the same name.
I want to restrict this. But I don't know how..
If you help me, I'll be glad.
Thanks. Best regards.
P.S: I should use CUniqueValidator, but don't know how..
IdeyalarController code:
public function actionCreate()
{
$model = new Ideyalar;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Ideyalar']))
{
$model->attributes=$_POST['Ideyalar'];
$model->istifade = "1";
$model->idcontact = Yii::app()->user->getId();
if($model->save()){
// if($model->validate()) {
$command = Yii::app()->db->createCommand();
$command->insert ('mqrup', array(
'idperson'=> Yii::app()->user->getId(),
'idideya'=>$model->idideya));
$this->redirect(array('viewm','id'=>$model->idideya));
// }
}
}
$this->render('create',array(
'model'=>$model,
));
}
This is in your model file, not the controller under the method rules you should have the following rule:
array('your_attribute', 'unique'),
So you will have something like
public function rules()
{
return array(
//some rules
array('your_attribute', 'unique'),
);
}
See the wiki for more details
I try to upload a file to MySQL table and it does not work.
here what i write:
view:
<div class="row">
<?php echo $form->labelEx($model,'doc_ordered_recieved'); ?>
<?php echo $form->fileField($model,'doc_ordered_recieved'); ?>
<?php echo $form->error($model,'doc_ordered_recieved'); ?>
</div>
model:
i add this attribute:
public $doc_ordered_recieved;
and this rulse:
array('doc_ordered_recieved','file','types'=>'pdf', 'allowEmpty'=>true, 'on'=>'update'),
controllers:
public function actionCreate()
{
$model=new Orders;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Orders']))
{
$model->attributes=$_POST['Orders'];
$model->doc_ordered_recieved=CUploadedFile::getInstance($model,'doc_ordered_recieved');
if($model->save())
{
$doc_ordered_recieved->saveAs('http://localhost/files');
$this->redirect(array('view','id'=>$model->oid));
}
}
$this->render('create',array('model'=>$model,
));
}
please help me i don't know why its not work????
thanks you all
eliya
First you need to change the rule to add create scenario:
array('doc_ordered_recieved','file','types'=>'pdf', 'allowEmpty'=>true, 'on'=>'insert,update'),
and in your create action from your controller you need to do this:
public function actionCreate()
{
$model=new Orders;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Orders']))
{
$model->attributes=$_POST['Orders'];
$uploadedFile = CUploadedFile::getInstance($model,'doc_ordered_recieved');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
if($model->image == null || empty($model->image)){
$rnd = rand(0,9999);// generate random number between 0-9999
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
}
$uploadedFile->saveAs(dirname(__FILE__)..'/files/'. $model->doc_ordered_recieved);
// redirect to success page
}
$this->redirect(array('view','id'=>$model->oid));
}
}
$this->render('create',array('model'=>$model,
));
}
Just by looking at your code I can see that you need to change your file path from
$doc_ordered_recieved->saveAs('http://localhost/files');
to
$doc_ordered_recieved->saveAs(Yii::app()->basePath.'path/to/localFile');
Also, you should provide more information about your model.
How do I get when it finishes inserting the data, perform direct application automatically generates reports based on the data that has just inputted ?
My controller (Save) :
public function actionCreate()
{
$model=new PurchaseOrder;
if(isset($_POST['PurchaseOrder']))
{
$model->attributes=$_POST['PurchaseOrder'];
if($model->save())
$this->redirect('index');
}
$this->render('create',array(
'model'=>$model,
));
}
My controller (Generate Report) :
public function actionCetak()
{
if(isset($_POST['PrintPO'])){
$data = $_POST['no_po'];
if($data==''){
return false;
}else{
$HTML2PDF = Yii::app()->ePdf->HTML2PDF();
$HTML2PDF->WriteHTML($this->renderPartial('data_print', array(
'data' => $this->loadCetak($data)
), true));
$HTML2PDF->Output();
}
}else{
$this->render('form_cetak_po');
}
}
both functions run smoothly, but when I combining into :
public function actionCreate()
{
$model=new PurchaseOrder;
if(isset($_POST['PurchaseOrder']))
{
$model->attributes=$_POST['PurchaseOrder'];
if($model->save())
$HTML2PDF = Yii::app()->ePdf->HTML2PDF();
$HTML2PDF->WriteHTML($this->renderPartial('data_print', array(
'data' => $this->loadCetak($model->id)
), true));
$HTML2PDF->Output();
$this->redirect('index');
}
$this->render('create',array(
'model'=>$model,
));
}
Application only do the insert function. How do I order when finished doing the insert, directly akang application and the data it generates can be downloaded.
Thanks
You misses brackets after if(save())
Look at this :
if(isset($_POST['PurchaseOrder']))
{
$model->attributes=$_POST['PurchaseOrder'];
if($model->save())
{ // <-- add this
$HTML2PDF = Yii::app()->ePdf->HTML2PDF();
$HTML2PDF->WriteHTML($this->renderPartial('data_print', array(
'data' => $this->loadCetak($data)
), true));
$HTML2PDF->Output();
} //<-- add this
else
{
$this->redirect('index');
}
}
Redirecting after download
I don't think this can be done.
The common thing in popular download sites is the reverse: first you go to the "after" page and then the download starts.
You can do this :
after save,redirect to something like this
index.php?r=controller/index&file_info=information
and in index method, check if ($_GET['file_info']), then create your pdf file and make the download.
Look at the top answer here
I am trying to submit a form , after form submition the current page should stay on with user entered datas . how to achieve this ?
public function actionUpload()
{
$model=new UploadModel();
$basemodel=new BaseContactList();
$importmodel=new ImportedFilesModel();
$importmodel->name =$basemodel->name;
$importmodel->import_date = $now->format('Y-m-d H:i:s');
$importmodel->server_path = $temp;
$importmodel->file_name = $name;
$importmodel->crm_base_contact_id = $crm_base_contact_id;
if ($importmodel->save())
echo "Import saved";
else
echo "Import Not Saved";
unset($_POST['BaseContactList']);
$this->redirect(Yii::app()->request->urlReferrer);
}
This line "$this->redirect(Yii::app()->request->urlReferrer);" goes to previous page but the user entered values are cleared . How to redirect to previous page without clearing the values in the form ??
Same with when you view the error message after failed model saving. Instead of doing redirection, you can just pass the saved model to the form.
public function actionIndex(){
$model = new Model();
if (isset($_POST[get_class($model)]){
$model->setAttributes($_POST[get_class($model)]);
if ($model->save()){
//do nothing
//usually people do a redirection here `$this->redirect('index');`
//or you can save a flash message
Yii::app()->user->setFlash('message', 'Successfully save form');
} else {
Yii::app()->user->setFlash('message', 'Failed to save form');
}
}
//this will pass the model posted by the form to the view,
//regardless whether the save is successful or not.
$this->render('index', array('model' => $model));
}
In the index view you can do something like.
<?php if (Yii::app()->user->hasFlash('message')):?>
<div class="message"><?php echo Yii::app()->user->getFlash('message');?></div>
<?php endif;?>
<?php echo CHtml::beginForm();?>
<!-- show the form with $model here --->
<?php echo CHtml::endForm();?>
The downside is, when you accidentally hit Refresh button (F5), it will try to post the form again.
Or you can save it using user session using setFlash.
public function actionUpload()
{
$model=new UploadModel();
$basemodel=new BaseContactList();
$importmodel=new ImportedFilesModel();
$importmodel->name =$basemodel->name;
$importmodel->import_date = $now->format('Y-m-d H:i:s');
$importmodel->server_path = $temp;
$importmodel->file_name = $name;
$importmodel->crm_base_contact_id = $crm_base_contact_id;
if ($importmodel->save())
echo "Import saved";
else
echo "Import Not Saved";
unset($_POST['BaseContactList']);
//here we go
Yii::app()->user->setFlash('form', serialize($basemodel));
//
$this->redirect(Yii::app()->request->urlReferrer);
}
In the previous form, you load the value from the session.
public function actionForm(){
if (Yii::app()->user->hasFlash('form')){
$basemodel = unserialize(Yii::app()->user->getFlash('form');
} else {
$basemodel = new BaseContactList();
}
$this->render('form', array('basemodel' => $basemodel));
}
I do not know whether really such a long code is needed to do such a thing but I can simply do it by this.
Suppose i have an actionUpdate
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Products']))
{
$model->attributes=$_POST['Products'];
$model->save();
// remove this redirect() line
// $this->redirect(array('view', 'id' => $model->productId));
}
$this->render('update',array(
'model'=>$model,
));
}
If in your action, you are redirecting after saving your data then just remove that line and you are done, provided that you are rendering the form again in the following lines
If you are not rendering the form in the next lines then you can do it yourself like
if($model->save())
{
$this->render('update',array(
'model'=>$model,
));
Yii::app()->end();
}
Will this do?
if ($importmodel->save())
$_SERVER['PHP_SELF'];
Simple Redirect to the same action and send the model loaded as an arguement
Below is the relation between three tables I have.
Now, while creating a new user through user/create action, the form takes input for both user table fields and the unit name. The unit name here isn't a dropdown (using that is not an option), but a textfield. If the unit name entered in the form doesn't exist in the unit table, I need to insert it in the unit table and then save the relation/reference in the user_unit table. If it exists I just update the user_unit table. I am able to get it kind of working by declaring the unitname property in the User model and then associating it with the form, then in the controller I check if the unit name entered exists in unit table. If it exists then I update the UserUnit model if it doesn't then I create the unit and then update UserUnit. It works, except that I am not able to associate the unit name to the form when updating the record. The userunit relationship is a HAS_MANY one and I guess that is creating some issue here. Could anyone suggest me how to approach solving it?
Here's the user/create action
$model = new User;
$modeluserunit = new UserUnit;
$user_group=Yii::app()->user->group;
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
//$modeluserunit->attributes=$_POST['UserUnit'];
$valid=$model->validate();
if($valid)
{
if($model->save(false))
{
$Userunitmodel = Unit::model()->findByAttributes(array('name'=>$model->unitplaceholder,'groupId'=>$user_group));
if (count($Userunitmodel)!=0)
{
$modeluserunit->UserId = $model->id;
$modeluserunit->unitId = $Userunitmodel->id;
if ($modeluserunit->save())
{
Yii::app()->user->setFlash('success', "User created!");
$this->redirect(array('view','id'=>$model->id));
}
}
else if (count($Userunitmodel)==0)
{
$unitmodel = new Unit;
$unitmodel->name=$model->unitplaceholder;
$unitmodel->communityId=$user_group;
if ($unitmodel->save())
{
$modeluserunit->UserId = $model->id;
$modeluserunit->unitId = $unitmodel->id;
if ($modeluserunit->save())
{ Yii::app()->user->setFlash('success', "User created!");
$this->redirect(array('view','id'=>$model->id));
}
}
}
}
}
}
$this->render('create', array(
'model'=>$model,
'modeluserunit'=>$modeluserunit,
));
The user/update action
$model=$this->loadModelupdate($id);
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
if($model->save())
Yii::app()->user->setFlash('success', "User updated!");
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
And the loadModel function
$criteria=new CDbCriteria();
$criteria->compare('t.id',$id);
$criteria->compare('unit.groupId',Yii::app()->user->group);
$model = User::model()->with(array('UserUnits' => array('with' => 'unit')))->find($criteria);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
The relationship in the User Model
return array(
'userUnits' => array(self::HAS_MANY, 'UserUnit', 'userId'),
);
You should use form model for this purpose. At the end of validation, you just create user, then create new unit with given name, and then create new user_unit feeding freshly created user id and unit id.
Read more Yii Definitive Guide - Model and CFormModel.
Try this at home:
<? /*** stuff for your model User ***/
// store all ids from rela Model
public $selectedIds;
public function relations()
{
return array(
'userUnits' => array(self::MANY_MANY, 'Unit', 'UserUnit(userId, unitId)','index'=>'id'),
);
}
public function afterFind()
{
// "userUnits" is defined in relations()
$this->selectedIds = array_keys($this->userUnits);
parent::afterFind();
}
?>
After your User Model is loaded for update-action, all assigned Groups (ids) are in $selectedIds.
So you can iterate over it and build your ActiveForm Inputs.