phpexcel File does not exist - symfony

I am trying to read a xlsx document with PHPExcel. My document is in my local and my code shows me this error.
*
Could not open MunicipioPreinscripcion.xlsx for reading! File does not
exist.
*
This is my code (My excel document is my current directory with my controller)
#namespace Backend\AlumnosBundle\Controller
define('PHPEXCEL_ROOT', dirname(__FILE__) . '/');
$inputFileName = 'MunicipioPreinscripcion.xlsx';
$inputFileNameWithPath = PHPEXCEL_ROOT.$inputFileName;
if(file_exists($inputFileNameWithPath)) {
echo 'exist'; //Allways show exist
echo $inputFileNameWithPath."<br>";
} else {
echo 'dont exist';
}
/** Identify the type of $inputFileName **/
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
/** Create a new Reader of the type that has been identified **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Advise the Reader that we only want to load cell data **/
$objReader->setReadDataOnly(true);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName); //This is where throw the error
What i am doing wrong?
How can i show the directory where load() method is looking for files? I'm lost
Thanks in advance

SOLVED: I think it didn´t load for permission in this directory (mybundle/controller). I have moved the xlsx file to web/upload directory and this work correctly.
$objPHPExcel = $this->get('xls.load_xls2007')->load($this->get('kernel')->getRootDir() .'/../web/upload/MunicipioPreinscripcion.xlsx');

Related

Is there a way to transfer data from a repeater field in WP Formidable Forms to ActiveCampaign?

Currently I am trying to transfer data from a repeater field in Wordpress Formidable Forms to a list in a CRM system known as ActiveCampaign.
Unfortunately the ActiveCampaign Add-On does not recognise fields inside the repeater field.
When exporting the Child Form, I get exactly what I want. Is there any way to export this file as soon as an entry is created?
Any support would be greatly appreciated.
Maybe this link can help you: https://www.fdmdigital.co.uk/export-a-form-entry-to-csv-on-submit/
add_action('frm_after_create_entry', 'create_csv', 30, 2);
function create_csv($entry_id, $form_id) {
if ($form_id == 1234) { //replace 1234 with the id of the form
// Collect the form data - Add a new row for each field you want to export and give it a unique name
$firstName = isset($_POST['item_meta'][1537]) ? $_POST['item_meta'][1537] : '';
$lastName = isset($_POST['item_meta'][1538]) ? $_POST['item_meta'][1538] : '';
$email = isset($_POST['item_meta'][1540]) ? $_POST['item_meta'][1540] : '';
$organizationId = isset($_POST['item_meta'][1547]) ? $_POST['item_meta'][1547] : '';
$organizationName = isset($_POST['item_meta'][1548]) ? $_POST['item_meta'][1548] : '';
$createdAt = isset($_POST['item_meta'][1555]) ? $_POST['item_meta'][1555] : '';
// The header row of the CSV - Add a name for each field in the form
$header = "firstName,lastName,email,organizationId,organizationName,createdAt\n";
// The data of the CSV - Add each of the form fields listed above
$data = "$firstName,$lastName,$email,$organizationId,$organizationName,$createdAt\n";
/*
* The file name of the CSV.
*
* NB: To save a single file per entry you will need to make the file name unique
* This can be done using the entry ID or the date & time stamp by including the hour, minutes & seconds.
* E.g at 12:38:43 the file will be named "TestUser-21-02-05-12-38-43-request.csv".
* One second later the time (and file name) will be "12:38:44".
* Then a new file "TestUser-21-02-05-12-38-44-request.csv" will be created.
* How you name the file will determine if you have a new file for each entry, a new file per user or a single file with all entry data.
*/
$fileName = dirname(__DIR__, 3) . "/your-project-folder/" . $refUserId . "-" .$createdAt . "-request" . ".csv";
/*
* Create the CSV file.
* If file exists, append the data to it. Otherwise create a new file.
*/
if (file_exists($fileName)) {
// Add only data. The header is already added in the existing file.
file_put_contents($fileName, $data, FILE_APPEND);
} else {
// Add CSV header and data.
file_put_contents($fileName, $header.$data);
}
}
}

How to handle file upload in symfony?

im trying to upload diffrent types of files in symfony
$uploadedFile = $request->files->get('image');
Works good for handling with images, However i cannot use it with diffrent files than
$uploadedFile = $request->files->get('file');
dd($uploadedFile);
Whatever i send using this, dd method shows me null.
How can I upload files for example pdfs, docx etc. (diffrent than images)
I use vue on the frontend.
You should use createForm.
https://symfony.com/doc/current/controller/upload_file.html
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** #var UploadedFile $brochureFile */
$brochureFile = $form->get('brochure')->getData();
// this condition is needed because the 'brochure' field is not required
// so the PDF file must be processed only when a file is uploaded
if ($brochureFile) {
$originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();
// Move the file to the directory where brochures are stored
try {
$brochureFile->move(
$this->getParameter('brochures_directory'),
$newFilename
);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
// updates the 'brochureFilename' property to store the PDF file name
// instead of its contents
$product->setBrochureFilename($newFilename);
}

Adding images from an external gallery to a SilverStripe site via a BuildTask

I'm making a Silverstripe build task to get many images from an external gallery, and create/upload them into the /assets/images/gallery folder with the necessary database links to the GalleryPage.
So I load the list of Urls, display the images to the browser, now how do I save an image into the assets folder with the necessary GalleryPage database links?
class ImportGalleryTask extends BuildTask {
public function writeImage($data) {
//$data->Title
//$data->Filename
//$data->Url
//this is the external url that I can output as an image to the browser
//
// folder to save image is 'assets/images/gallery'
//
// ? save into folder and database and associate to PageImageBelongsToID ?
}
}
You can use copy to copy a remote file to your local filesystem. PHP must be configured to support allow_url_fopen though.
So, your resulting function might look like this:
/**
* #param $data
* #return null|Image return written Image object or `null` if failed
*/
public function writeImage($data)
{
// The target folder for the image
$folder = Folder::find_or_make('images/gallery');
// assuming that $data->Filename contains just the file-name without path
$targetPath = $folder->getFullPath() . $data->Filename;
// Check if an image with this name already exists
// ATTENTION: This will overwrite existing images!
// If you don't want this, you need to implement this differently
if(
file_exists($targetPath) &&
$image = Image::get()->where(array(
'"Name" = ?' => $data->Filename,
'"ParentID" = ?' => $folder->ID
))->first()
){
// just copy the new file over…
copy($data->Url, $targetPath);
// … and delete all cached images
$image->deleteFormattedImages();
// and we're done
return $image;
}
// Try to copy the file
if (!copy($data->Url, $targetPath)) {
return null;
}
// Write the file to the DB
$image = Image::create(array(
'Name' => $data->Filename,
'ParentID' => $folder->ID,
'Filename' => $folder->getRelativePath() . $data->Filename
));
$image->write();
return $image;
}

PHPExcel file does not exsit

Please kindliy help out.Am using php excel with laravel but whenever i try to import excel file into database i get error "Error loading file "update.xlsx": Could not open localhost:9090/xls/update.xlsx for reading! File does not exist.".
My xls folder is placed in my public directory and am loading phpexcel with composer.Kindly help out i ddont know what am doing wrong.thanks in advance
Here is my code:
<?php
/************************ YOUR DATABASE CONNECTION START HERE ****************************/
define ("DB_HOST", "lhost"); // set database host
define ("DB_USER", "root"); // set database user
define ("DB_PASS",""); // set database password
define ("DB_NAME","name"); // set database name
// $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
// $db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
$databasetable = "applicant";
$con = new mysqli(DB_HOST, DB_USER,DB_PASS,DB_NAME);
/************************ YOUR DATABASE CONNECTION END HERE ****************************/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
// This is the file path to be uploaded.
$inputFileName = asset("xls/".$filename);;
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++)
{
$surname = trim(strtoupper($allDataInSheet[$i]["A"]));
$othernames = trim(strtoupper($allDataInSheet[$i]["B"]));
$address = strtoupper($allDataInSheet[$i]["C"]);
$lga = trim(strtoupper($allDataInSheet[$i]["D"]));
$sex = trim(strtoupper($allDataInSheet[$i]["E"]));
$dob = trim(strtoupper($allDataInSheet[$i]["F"]));
$genotype = trim(strtoupper($allDataInSheet[$i]["G"]));
$blood_grp = trim(strtoupper($allDataInSheet[$i]["H"]));
$phone = trim(strtoupper($allDataInSheet[$i]["I"]));
$email = trim(strtoupper($allDataInSheet[$i]["J"]));
$occupation = trim(strtoupper($allDataInSheet[$i]["K"]));
$place_emp = trim(strtoupper($allDataInSheet[$i]["L"]));
$facility = trim(strtoupper($allDataInSheet[$i]["M"]));
$medical_his = trim(strtoupper($allDataInSheet[$i]["N"]));
$allergy = trim(strtoupper($allDataInSheet[$i]["O"]));
$reg_frm = trim(strtoupper($allDataInSheet[$i]["P"]));
$reg_to = trim(strtoupper($allDataInSheet[$i]["Q"]));
$collector = trim(strtoupper($allDataInSheet[$i]["R"]));
$form_no = trim(strtoupper($allDataInSheet[$i]["S"]));
$tell_no = trim(strtoupper($allDataInSheet[$i]["T"]));
$amt_paid = trim(strtoupper($allDataInSheet[$i]["U"]));
$query = "SELECT surname FROM `applicant` WHERE `surname` = '$surname' and `othernames` = '$othernames'";
$sql = $con->query($query);
$recResult = mysqli_fetch_array($sql);
$existName = $recResult["surname"];
if($existName=="") {
$insertTable= $con->query("insert into `applicant` (surname, othernames,address,lga,sex,dob,genotype,blood_grp,phone,email,occupation,place_emp,facility,medical_his,allergy,reg_frm,reg_to,collector,form_no,tell_no,amt_paid)
values('".$surname."', '".$othernames."','".$address."','".$lga."','".$sex."','".$dob."',
'".$genotype."','".$blood_grp."','".$phone."','".$email."','".$occupation."',
'".$place_emp."','".$facility."','".$medical_his."','".$allergy."','".$reg_frm."',
'".$reg_to."','".$collector."','".$form_no."','".$tell_no."','".$amt_paid."');");
$msg = 'Record has been added';
}
else
{
$msg = 'Record already exist';
}
}
echo "<div class='alert alert-info'>".$msg."</div>";
?>
I'm not sure what is "composer" and what the asset() function is supposed to be doing, but normally for file uploads to a PHP script you'd use a "mime/multipart" web form with a file input, and then the PHP runtime will consume the file and make it available in the $_FILES array. Read the PHP manual on handling file uploads for more information.
PHPExcel cannot open a file from a URL, only from the local filesystem. As the url that you're using (localhost)suggests that file is on the server's filesystem, us a full filesystem path instead

Delete image on database delete symfony2

Symfony Forms
I have this all working correctly. One thing that I am not sure is how to delete the image that is uploaded in the uploads folder when the associated entry in the database is deleted.
I really just need an idea on how to do it to get headed in the right direction.
Thanks in advance.
You are both correct I did a var dump on the code that was in the entity...
/**
* #ORM\PostRemove
*/
public function removeUpload()
{
if(file_exists($file)) {
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
}
if file exists $file was showing an empty variable. In the upload it saves the variable as $logo
I changed the code to the following
/**
* #ORM\PostRemove
*/
public function removeUpload() {
// ** Original Code used file but logo has the name in it.
if(file_exists($this->getAbsolutePath())) {
if ($this->getUploadRootDir() . $this->logo = $this->getAbsolutePath()) {
unlink($this->logo);
}
}
}
It now deletes the file correctly. Thank you both.
In your delete action, you would have to delete the file manually. I assume you will be storing the file path in the database, so this should be relatively easy.
$path = ....//query db to get the path to the file
if($path){
unlink($path);
}
//now you can delete the record in the database
See php docs for deleting a file
What you are probably searching for are Doctrine2 Lifecycles. Just add a method to your entity:
/**
* #ORM\PreRemove
*/
public function deleteImage()
{
// unlink your image and what not.
}
Also don't forget the #ORM\HasLifecycleCallbacks() annotation for your entity class.

Resources