how to make file upload mandatory yii - file

im a bit new to this,
I have a model with an attribute file_id but it'll be displayed as File. I should make this mandatory..but when user uploads a file, I'm storing the file path and all in file table. and getting id from that table and storing it in my model.
can anyone pls tell me how can i make file upload mandatory for create but not for update
my code for file upload is:
<?php echo $form->labelEx($model,'file'); ?>
<?php echo $form->fileField($model, 'file');?>
<?php echo $form->error($model,'file'); ?>`
its working fine. but i need to make it mandatory for this current model. do i need to make it required in rules function in file model or current model??
Thanks,

The easiest way would be in the model rules:
array('file', 'required','on'=>'insert'),
Then it is only required on insert and not updates.
Another way would be to utilize the before or afterValidate method:
protected function afterValidate(){
if($this->isNewRecord){
if(!isset($this->file)){ //Not sure about handling files if this works.
$this->addError("file","Not file selected. Please choose a file to upload.");
return false;
}
}
return parent::afterValidate();
}

Related

convert mysql_connect to joomla-based connect

I have been struggling with this for a couple days now, but can't get it to work.
I'm currently building a website in Joomla and added a puzzle-game page into it. What I want to do is, save the time-score and create a simple top-10 score list.
I got it to work by what I think is the hard way ;) by using a <form method="post" action="include/dbscore.php"> function. In the 'dbscore.php' file I got the following code:
<?php
$con = mysql_connect("localhost","[my db username]","[my db password]");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("[my db name]", $con);
$sql="INSERT INTO uhkbw_puzzel_score (fname, lname, time, date)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[time]','".date('d-M-Y')."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Your score is succesfully saved";
mysql_close($con)
?>
This does the trick and posts the data I want into the database, but I feel there must be a much simpler and safer way, since Joomla already should know the db name/passw. However the puzzel-game index.php itself is located in a separate folder inside the joomla directory and loaded through an iframe into joomla and is not a standard joomla module or component...
I already tried using the $db = JFactory::getDBO(); methode, but I must do something wrong
Any ideas?

blackhole cakephp 2 associated entities

My Goal:
Reuse of a contact form to be related to several different entities I call "Parents" ie Group has contact information, Member has contact info etc....
The way I tried doing it was:
1. Creating a view file for contact, named "form.ctp" which doesn`t create a new form, nor submits, just echo's the contact's fields.
2. Calling this file using requestAction
My Problem:
The form's _Token get crumbled.
Parent add.ctp example
<?php echo $this->Form->create('Group');?>
<fieldset>
echo $this->Form->input($field_prefix.'contact_id',array('type'=>'hidden'));
<?php echo $this->requestAction(array('controller' => 'contacts', 'action' => 'form'), array('named' => array('index'=>'0','parent'=>'Group',
'fields'=>array(
'email'=>array('value'=>'xx#yy.com','hidden'=>1)
))));
inside the form.ctp I have:
//Associated Model
echo $this->Form->input('Contact.0.city',array('type'=>'hidden'));
echo $this->Form->input('Contact.0.postcode');
echo $this->Form->input('Contact.0.phone');
echo $this->Form->input('Contact.0.cellphone');
echo $this->Form->input('Contact.0.email',array('value'=>""));
echo $this->Form->input('Contact.0.id',array('type'=>'hidden'));
?>
Looking at the HTML source code that is generated, I see that whether I use the request action or just copy the contect of the form.ctp into the "Parent's" add file, I get the same HTML result.
HOWEVER!!! when I use the form.ctp Action Request, I get the blackhole, the tokens are being messed up!!!
Any Ideas?
Thanks in advance
Orly
If your problem is solely reusing a form, you can use the form as a Element, and then you could call it multiple times, substituting in the exact values you need.
As for SecurityComponent, I would recommend (at least as a temporary fix) disabling SecurityComponent for that specific action by using $this->Security->unlockedActions(); in your controller's beforeFilter()

CakePHP generate and save PDF

I am using CakePHP for an application that does auto generation of vouchers to a PDF file. But they work through user clicks. Now I wish to create it automatically and have the file written to the server hard disk. Then later on, these files will get zipped up and sent to an email of my choice.
For the PDFs I use Html2ps/Html2pdf component found in CakePHP. You can view it here http://bakery.cakephp.org/articles/Casmo/2010/06/26/creating-pdf-files-with-html2ps-html2pdf
One issue I have is the formatting doesn't look right. If I have links that look like this:
http://www.mydomain.com/this-is-my-perma-link
They will render this way in the generated PDF:
http://www.mydomain.com/this- is- my- perma- link
And that would be a broken link. I've tried to use other characters to replace the dash but it doesn't work. I am not sure why.
Another issue is, how can I write the generated PDF file to my server hard disk? Is there an option for me to do that and how do I define the destination. Any examples?
Maybe thanks in advance!
Hi you can to use FPDF library . and you can to save file in the server and then redirect to other function.
check the next code.
///Call to library
<?php
App::uses('AppController', 'Controller');
require_once APP . 'Vendor' . DS . 'fpdf17' . DS . 'fpdf.php';
class TestController extends AppController {
public function test(){
--Create fpdf.
$pdf = new FPDF();
$pdf->AddPage();
$pdf->Output('files/Report.pdf');
$pdf->text($x,$y,'Txt');
return $this->redirect(
array('controller' => 'Test', 'action' => 'test_new')
);
}
}

how to edit a cakephp record without deleting the path to an uploaded file

I want to edit a record in CakePhp without deleting the saved path of an uploaded jpg file. Right now when I edit the record it deletes the saved file path.
The approach I think would work is to do a logic check in the form to check if the field is empty or not. Display the saved file path if it's not empty or show an empty path if it is. Would this be the best way to update the record?
I'm using Miles Johnson's uploader plugin for uploading files.
Here's the code within the form:
<?php
if (!empty ($slider ['Slider']['bgImg']));
echo $slider ['bgImg'];
else
echo $form->input('file', array('type' => 'file'));
?>
This logic should be in the controller, strictly speaking.
In my apps with files and edit capabilities, I will show a file field and a link/thumbnail of the image in question on the edit form.
my approach uses my own uploader, so your results may vary, but essentially:
if (!empty($this->data)) {
$file_object = $this->data['Listing']['featured_image'];
$image_data=$this->Upload->do_upload($file_object, 'img/uploads/');
if($image_data){
$this->data['Listing']['featured_image'] = $image_data['name'];
} else {
unset($this->data['Listing']['featured_image']);
}
$this->Listing->save($this->data)
and in my upload component, I have this:
public function do_upload($file_object, $location='img/uploads/') {
/**
* No file was uploaded
*/
if($file_object['error']==4) {
return false;
}
// carry on uploading
So essentially; I pass my upload component the $file_object, which is from the form. I then do a simple test, using the default set of error codes to see if the file is empty (4). If it's empty, I return false. (you could return errors etc, but this was my approach).
after the upload call, I check the return value, and if the file was uploaded successfully, I can then set the field in my model. (the file name, in my case) - you may want to store the path as well, for instance.
If it's false - it means there was no file; so I unset the value from the array.
Because the field does not exist in the array, cake will not attempt to overwrite existing data - it simply ignores it; allowing the old value to stay untouched.

How to reduce form code duplication in CakePHP

I have a form in CakePHP with a few dozen fields in it. From all the examples I have seen, there is duplicate form code for an add view and an edit view.
Is there any tricks to keep the duplication out? What is best method in CakePHP for this?
What I do, is to put all form fields in an element, and then insert the element in the add.ctp and edit.ctp
Don't forget to add the hidden field with the id in the edit.ctp
This way all visible elements are in one file, easier to maintain.
View/MyModel/add.ctp
echo $this->Form->create('MyModel');
echo $this->element('my_form');
echo $this->Form->end();
View/MyModel/edit.ctp
echo $this->Form->create('MyModel');
echo $this->Form->input('id');
echo $this->element('my_form');
echo $this->Form->end();
View/Elements/my_form.ctp
// your form inputs
// whatever they are
You should NOT merge those views, because add/edit are different actions and deserve separate view files. As your application grows you will realize that its good to have separate views to reduce complexity of if else conditions.
If you still want to avoid the separate files, Use
function add() {
.....
$this->render('edit')
}
I've done this before, but reverted back to having separate views, mainly for my own sanity.
It's easy enough to do. The edit requires an input for the record id. This is usually hidden. Any default form values for the add form will have to be contained in conditionals so that the stored values are not overwritten with defaults when you are editing a record
On the controller side of things, you'll need a conditional statement to decide whether to act as an add or edit depending on whether the $this->data['MyModel']['id'] is set.
I think that covers it - if I think of anything else I'll add it in.
My work pattern tends to be to build the edit view, then copy and paste to create the basis for the add view.
this code will check if you have admin_form.ctp or form.ctp which will make it use the same code for add / edit
https://github.com/infinitas/infinitas/blob/dev/app_controller.php#L389
1.3 submits the forms automatically to where the are from so when you go to /edit/1 it will post to there, and /add will post to add.
that is all you need to do. if you have a edit that is vastly different to the add, then you just create the 2 files. when you want them the same, just make the one.
in your app controller
public function render($view = null, $layout = null) {
$viewPaths = App::path('View', $this->plugin);
$rootPath = $viewPaths[0] . DS . $this->viewPath . DS;
$requested = $rootPath . $view . '.ctp';
if (in_array($this->request->action, array('admin_edit', 'admin_add', 'edit', 'add'))) {
$viewPath = $rootPath . $this->request->action . '.ctp';
if (!file_exists($requested) && !file_exists($viewPath)) {
if (strpos($this->request->action, 'admin_') === false) {
$view = 'form';
} else {
$view = 'admin_form';
}
}
}
return parent::render($view, $layout);
}
and in your view you can always check whether its edit or add
if ($this->request->params['action'] == 'admin_edit') {
//do something
}
if ($this->request->params['action'] == 'admin_add') {
//do something
}
in edit.ctp
if($this->data[ModelName]['id']) {
$this->Form->input('id');
}
// create rest of the fields
in Controller::add()
$this->autoRender=false; // at the start of function
$this->render('edit.ctp'); // at the point where you actually want to render
no need to create add.ctp

Resources