It's evidently a little more complicated to create a file dynamically in SS4
$folder = Folder::find_or_make('Cards');
$filename = 'myimage.jpg';
$contents = file_get_contents('http://example.com/image.jpg');
$pathToFile = Controller::join_links(Director::baseFolder(), ASSETS_DIR, $folder->Title, $filename);
file_put_contents($pathToFile, $contents);
$image = Image::create();
$image->ParentID = $folder->ID;
$image->Title = "My title";
$image->Name = $filename;
$image->FileFilename = 'Cards/' . $filename;
$image->write();
Member::actAs(Member::get()->first(), function() use ($image, $folder) {
if (!$image->isPublished()) {
$image->publishFile();
$image->publishSingle();
}
if (!$folder->isPublished()) {
$folder->publishSingle();
}
});
The above, creates the file as expected in /assets/Cards/myimage.jpg and publishes it fine
However all previews are blank, so it's obviously not finding the file:
Any idea what I missed in creating the Image object?
This should work:
$folder = Folder::find_or_make('Cards');
$contents = file_get_contents('http://example.com/image.jpg');
$img = Image::create();
$img->setFromString($contents, 'image.jpg');
$img->ParentID = $parent->ID;
$img->write();
// This is needed to build the thumbnails
\SilverStripe\AssetAdmin\Controller\AssetAdmin::create()->generateThumbnails($img);
$img->publishSingle();
FYI: $img->Filename no longer exists. An Image or File object have a File property, which is a composite field of type DBFile. This composite fields contains the filename, hash and a variant…
So you should use the composite field to address these fields.
Related
I am working on my personal wordpress site that distribute images.
In single post page, I registered several images via ACF(Advanced Custom Fields) and I know how to get image path/filename through get_field ACF function.
I just googled then found this page, but how can I apply this technique to wordpress site?
Download multiple images into zip
Now I am stuck...
On single post page, place the url of download_zip.php file, where you will place all your code for creating zip.
On single post page:
Download ZIP
In variable 'model_id', place the post id of the single post.
Now create a download_zip.php file on the root of your wordpress setup, where wp-config.php file exists.
Here is the code of download_zip.php file.
<?php
/*File for downloading the gallery zip files*/
$post_id = $_GET['model_id'];
require_once('wp-blog-header.php');
require_once('/wp-admin/includes/file.php');
WP_Filesystem();
$files_to_zip = array();
$zip = new ZipArchive();
$title = get_the_title($post_id);
$destination = wp_upload_dir();
//var_dump($destination);
$destination_path = $destination['basedir'];
$DelFilePath = str_replace(" ","_",$title).'_'.$post_id.'_'.time().'.zip' ;
$zip_destination_path = $destination_path."/".$DelFilePath;
if(file_exists($destination_path."/".$DelFilePath)) {
unlink ($destination_path."/".$DelFilePath);
}
if ($zip->open($destination_path."/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) {
die ("Could not open archive");
}
//this is only for retrieving Repeater Image custom field
$row1 = get_field('acf_field_name1',$post_id);
$row1 = get_field('acf_field_name2',$post_id);
$rows = array($row1,$row2);
if($rows) {
foreach($rows as $row): ?>
<?php
$explode = end(explode("uploads",$row));
$index_file = array($destination_path,$explode);
$index_file = implode("",$index_file);
$new_index_file = basename($index_file);
$zip->addFile($index_file,$new_index_file);
endforeach;
}
$zip->close();
if(file_exists($zip_destination_path)) {
send_download($zip_destination_path);
}
//The function with example headers
function send_download($file) {
$basename = basename($file);
$length = sprintf("%u",filesize($file));
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$basename.'"');
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
header('Content-Length: ' . $length);
set_time_limit(0);
ob_clean();
flush();
readfile($file); // "Outputs" the file.
unlink($file);
}
?>
Please modify this code according to your requirement such as get_field(), place your image field name inside it, & define your upload directory, so that you can break the url in $explode variable for defining path of image in $index_file variable.
And please also check your destination path stored in $destination_path variable is correct or not.
Hope, this may be helpful to you.
I'm using the Contact Form 7 plugin for the user to generate a pdf based on submitted (by the form) and server provided data.
I'd like to also show a "preview" after submission so I need to pass the custom fields to the client in order to get them in some js file.
This is what I have:
plugin rendering the pdf:
<?php
add_action('wpcf7_before_send_mail', 'generate_pdf');
function generate_pdf($wpcf7) {
$file_uri = 'fpdf/fpdf.php';
require_once($file_uri);
/* PDF file initialization */
$pdf = new FPDF();
$pdf->AddPage();
$pdf->AliasNbPages();
$pdf->SetFont('Arial','B',12);
$today_date = "California, " . date("d F Y");
$pdf->Cell(0, 10, $today_date, 0, 1, 'R');
$name = $data['your-name'];
$submission = WPCF7_Submission::get_instance();
$data = $submission->get_posted_data();
$pdf->Output(wp_upload_dir()['basedir'] . '/' . $name . '.pdf', 'F');
$wpcf7['custom_field'] = 'CUSTOM VALUE';
return $wpcf7;
}
?>
javascript file called on form submit:
$('.wpcf7-submit').on('click', function (e) {
var data = $('form').serializeArray();
var cleaned_data = {};
for (item in data) {
var name = data[item]['name'];
if (name[0] != '_'){
cleaned_data[name] = data[item]['value'];
}
}
var testInput = cleaned_data["your-name"];
})(jQuery);
In this last code I'd like to get the values passed by the php script, but I don't know how to do it.
Assuming that the PDF generation function is in functions.php and that you've enqueued the js, what you're looking to do is localization. You can read more about it here: Localize scripts
I have this code that creates a new Image based on a new file added to the filesystem but not yet in the DB:
$image = Image::create();
$image->Filename = 'assets/Art/e3434cc7-d348-491a-9dc8-325af3d9086d.jpg';
$image->write();
$images = Image::get();
$image = $images->last();
$vd = new ViewableData();
$ad = new ArrayData(array(
'Image' => $image
));
$strHTML = $vd->customise($ad)->renderWith('Art');
Art.ss contains only $Image.SetWidth(100)
Ignoring the fact the query doesn't look up by ID or whatever... why is the image only rendered into $strHTML if I retrieve the image from the DB after creating? If I delete the code below, $strHTML is empty:
$images = Image::get();
$image = $images->last();
There is a setter available so using that alone may help, but you also may need to assign the ID of the parent folder to the object:
$pFolder = Folder::find_or_make('Art');
if ($pFolder) {
$image->setParentID($pFolder->ID);
$image->setFilename('assets/Art/e3434cc7-d348-491a-9dc8-325af3d9086d.jpg');
}
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
If I have a page whose url alias is "/api/user/create", how can I name a template file based on the url such as "page-api-user-create.tpl.php".
You need to name it:
page--api--user--create.tpl.php
(note double dashes in the file name).
See http://drupal.org/node/1089656 for more info.
You can set up a page level template file to reflect the url, as was explained by Maciej Zgazdaj.
To do the same with a node level template file you have to add this to your template.php file:
function YOURTHEME_preprocess_node(&$variables) {
$url = str_replace("-", "", $variables['node_url']);
$urlParts = explode("/", $url);
unset($urlParts[0]);
if($urlParts[1] !== false) {
$out = array();
$sug = "node";
foreach($urlParts as $val) {
$sug .= "__".$val;
$out[] = $sug;
}
$variables['theme_hook_suggestions'] =
array_merge($variables['theme_hook_suggestions'], $out);
}
}
Replace YOURTHEME with .. well your theme. Check the offered suggestions with devel_themer.