Codeigniter multifile upload - codeigniter

$this->upload->display_errors()
shows the errors for all the files I am trying to upload.
How can I show the error for each file field ?
for example, if the user can upload 5 files and the third file is to big, I want to be able to tell him that this specific file is to big.

The functionality you are after is not built-in to the CI upload library. Here's CI's $this->upload->display_errors() method:
function display_errors($open = '<p>', $close = '</p>')
{
$str = '';
foreach ($this->error_msg as $val)
{
$str .= $open.$val.$close;
}
return $str;
}
It returns all the errors as a single string. You would need to adjust this accordingly, perhaps to return an array with the key for the respective file field.
You could use the $_FILES superglobal before hand, and check each field for errors, and then if there are no errors, call CI's do_upload()

Related

DOMPDF: How to customize the name of the single pdf, relating to a single client, with the information present in the object

I am trying to create the pdf, using the domPDF library, for each single client present in the table of my application. So far everything ok!
When I go to save the pdf I want the name of the pdf document to be saved as:
name_client_surname_client.pdf,
so if for example I have a client named Alex Haiold, the document must be saved as Alex_Haiold.pdf
To do this, since I am passing the single client in the controller, as shown below, I tried to write
return $pdf->download('client->surname client->name.pdf');
but it is saved as
client-_surname client-_name.pdf (then printing client-_surname client-_name).
Here my code:
public function generatePDF(Client $client)
{
$data = [
'title' => 'Welcome to LaravelTuts.com',
'date' => date('m/d/Y'),
'client' => $client
];
//dd($data);
$pdf = PDF::loadView('client.clientPDF', $data);
return $pdf->download('client->surname client->name.pdf');
}
Can anyone kindly help me?
$pdf = PDF::loadView('client.clientPDF', $data);
return $pdf->download($client->surname . ' ' . client->name . '.pdf');
On the first line, we are just making a view file. The file is resources/views/client.clientPDF.blade.php and we are feeding data to the view file by passing the variable $data to it.
After making the view, our next step is to download the pdf file. For doing this, we need to call the download method of the instance.
On the first parameter, we are passing the filename with extension(pdf).

Generate multiple PDF documents with loop with dompdf in laravel

I am trying to download multiple pdf using dompdf in laravel, but below solution just concatenate into one pdf file
$weeks = ['test','test2'];
$html = '';
foreach($weeks as $hours)
{
$view = view('contract');
$html .= $view->render();
}
$pdf = PDF::loadHTML($html);
$sheet = $pdf->setPaper('a4', 'landscape');
return $sheet->download('download.pdf');
the server can only return a response, if you want several pdf files you should modify your method so that it accepts some parameter and for each parameter generate a pdf
It is not possible to download more than one file in a single HTTP request.
What you could do is pack the files into o zip and download that. You can try https://github.com/zanysoft/laravel-zip or any other available solution.
Another option would be to save the files and return only paths for the saved files back to the client. Then make a new request and download the file for each of the returned filepaths.
Also if you want to save to separate PDF files you need to move PDF creation into your foreach loop (create a PDF for each parameter).
$weeks = ['test','test2'];
$files = [];
foreach($weeks as $hours)
{
$view = view('contract');
$html = $view->render();
$pdf = PDF::loadHTML($html);
$pdf->setPaper('a4', 'landscape');
$pdf->save('documents/'.$hours.'.pdf');
$files[] = 'documents/'.$hours.'.pdf';
}
return response()->json(['files' => $files]);
In this case the foreach doesn't really do anything other than produce two identical PDF files. If you want to actually apply some kind of changes to your view based on values in $weeks you need to pass that to your view.
$view = view('contract', ['data' => $hours]);
That makes $data available in your view and you can change the resulting PDF in that way (show your contract.blade.php if you need more help regarding that).

How i can get the variable data as string like a dd() function in Laravel?

I need to get the request data but i cant get ip, fullUrl and others with all() method (this only print input values), but when i use "dd(request())" this show me all data (i need the data what is printed with dd method, but like a string to save, withour the exception who print this data). Im debbuging my app so i need to save every request data in a log file, something like:
\Log::debug($request)
So,
You can use:
\Log::debug($request->toString());
or alternatively you can use
\Log::debug((string) $request);
The Laravel Request object comes from Illuminate\Http\Request which extends Symfony\Component\HttpFoundation which exposes the following code:
public function __toString()
{
try {
$content = $this->getContent();
} catch (\LogicException $e) {
return trigger_error($e, E_USER_ERROR);
}
$cookieHeader = '';
$cookies = [];
foreach ($this->cookies as $k => $v) {
$cookies[] = $k.'='.$v;
}
if (!empty($cookies)) {
$cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n";
}
return
sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
$this->headers.
$cookieHeader."\r\n".
$content;
}
__toString() is considered a magic method in PHP.
The __toString() method allows a class to decide how it will react
when it is treated like a string. For example, what echo $obj; will
print. This method must return a string, as otherwise a fatal
E_RECOVERABLE_ERROR level error is emitted.
You can read more about it in the official documentation.
I highly recommend to store just what you want from request data if you don't need all of them, however for both cases you can take a look at serialize and json_encode

Ask, how to use redirect without contition?

i have codes like this
function download(){
$id = $this->uri->segment(3);
$dat = $this->mikland->gidiklanfoto($id);
foreach ($dat as $item){
$name = $item->foto;
$data = file_get_contents(base_url()."/uploads/".$name); // filenya
force_download($name,$data);
}
redirect('cikland/viewiklan/'.$id);
}
when the function are running, redirect cannot run.,
somebody can help??
i think is a simple thing but i dont know the trick., thank's before
At the end of force_download() there is an exit() statement, so no code after a forced download will run.
And you are trying to have several files downloaded at the same time - using some sort of multipart mime type, that might or might not work, but not in the given case, because CI's force_download() does not seem to support that.
An alternative to that would be creating a temporary archive file which contains all the files for download; please have a look at the official documentation on compression and archives for that.
If you'd want to send a redirection header along with the file, you'd have to do it like this:
function download(){
// add this somewhere befor the download
header('Location: '.site_url('cikland/viewiklan/'.$id));
$id = $this->uri->segment(3);
$dat = $this->mikland->gidiklanfoto($id);
// only first item is downloaded
foreach ($dat as $item)
{
$name = $item->foto;
$data = file_get_contents(base_url()."/uploads/".$name); // filenya
force_download($name,$data);
}
}
But the question would remain how the browsers would deal with a redirect and content: most likely you would only get the redirect.
You need load url helper.
$this->load->helper('url');
after
redirect("cikland/viewiklan/$id", 'refresh');
or
redirect("cikland/viewiklan/$id", 'location', 301);
Font: http://ellislab.com/codeigniter%20/user-guide/helpers/url_helper.html
redirect() method redirects to a URL. You need to pass it a full URL (as it uses the header() function which according to the RFC for HTTP1.1 requires a full URL.
so you need to hard code the full url like the given example - redirect('http://www.yoursite.com/cikland/viewiklan/'.$id);

Codeigniter form validation failing when it should succeed

I'm building an admin utility for adding a bulk of images to an app I'm working on. I also need to to log certain properties that are associated with the images and then store it all into the database.
So basically the script looks into a folder, compares the contents of the folder to records in the database. All of the info must be entered in order for the database record to be complete, hence the form validation.
The validation is working, when there are no values entered it prompts the entry of the missing fields. However it happens even when the fields ARE filled.
I'm doing something a bit funny which may be the reason.
Because I'm adding a bulk of images I'm creating the data within a for loop and adding the validation rules within the same for loop.
Here is the results:
http://s75151.gridserver.com/CI_staging/index.php/admin_panel/bulk_emo_update
Right now I have default test values in the form while testing validation. The submit button is way at the bottom. I'm printing POST variable for testing purposes.
Here is the code:
function bulk_emo_update() {
$img_folder_location = 'img/moodtracker/emos/';//set an image path
$emo_files = $this->mood_model->get_emo_images('*.{png,jpg,jpeg,gif}', $img_folder_location); //grab files from folder
$emo_records = $this->mood_model->get_all_emos(); //grab records from db
$i=1; //sets a counter to be referenced in the form
$temp_emo_info = array(); //temp vairable for holding emo data that will be sent to the form
//loop through all the files in the designated folder
foreach($emo_files as $file) {
$file_path = $img_folder_location.$file;//builds the path out of the flder location and the file name
//loops through all the database reocrds for the pupose of checking to see if the image file is preasent in the record
foreach($emo_records as $record) {
//compairs file paths, if they are the
if($record->picture_url != $file_path) {
//FORM VALIDATION STUFF:
$rules['segment_radio['.$i.']'] = "required";
$rules['emo_name_text_feild['.$i.']'] = "required";
//populating the temp array which will be used to construct the form
$temp_emo_info[$i]['path'] = $file_path;
$temp_emo_info[$i]['name'] = $file;
}
}
$i++;
}
//sets the reference to validation rules
$this->validation->set_rules($rules);
//checks to see if the form has all it's required fields
if ($this->validation->run() == FALSE) { //if validation fails:
print_r($_POST);
//prepairs the data array to pass into the view to build the form
$data['title'] = 'Bulk Emo Update';
$data['intro_text'] = 'fill out all fields below. hit submit when finished';
$data['emos_info'] = $temp_emo_info;
$this->load->view('admin_bulk_emo_update_view',$data);
} else { // if it succeeds:
//printing for test purposes
print_r($_POST);
$this->load->view('form_result');
}
}
I'm new to codeigniter and php in general so if anything looks outrageously weird please tell me, don't worry about my feelings I've got thick skin.
if ($this->validation->run() == FALSE)
if you are calling the run() method of the validation class every time the script is run, will it ever return TRUE and run the else? Maybe a different return?
I'm a little cornfused by what's going on. Generally, if I'm having a problem like this, I will figure out a way to force the result I'm looking for. e.g. in your code, I'd force that else to run... once I get it to run, break down what happened to make it run. Rudimentary, but it has served me well.
You use array of rules in
$this->form_validation->set_rules()
wrong.
If you want to pass the rules in array you must stick to the key names like described here http://codeigniter.com/user_guide/libraries/form_validation.html#validationrulesasarray
So instead of
$rules['input_name'] = "required"
try this:
array(
'field' => 'input_name',
'label' => 'Name that you output in error message',
'rules' => 'required'
)

Resources