File isn't deleted when code is in a specific order - ajax

I ran into the problem that when I try to delete a record from database using ->delete() and my code stopped after successfully deleted the record.
This code doesn't execute the Storage::delete($image)
public function productImageDelete(Request $request){
if($request->ajax()):
$image_id = Input::get('image-id');
$image = Input::get('image');
try {
$image = Image::findOrFail($image_id);
$image->delete();
Storage::delete($image); //This doesn't execute at all
return "success";
} catch ( \Illuminate\Database\QueryException $e) {
return $e;
}
endif;
}
However when I placed Storage::delete($image) before $image->delete(); the code works.
public function productImageDelete(Request $request){
if($request->ajax()):
$image_id = Input::get('image-id');
$image = Input::get('image');
try {
Storage::delete($image); //This executes first
$image = Image::findOrFail($image_id);
$image->delete();
return "success";
} catch ( \Illuminate\Database\QueryException $e) {
return $e;
}
endif;
}

You need to take a look at the details. You're creating two variables named $image and that's your issue.
On the first case, you're calling Storage::delete($image); where $image is an object and on the second case, you're calling the same method but in that case $image is a Input::get('image').
If you simply rename the variable of Input::get('image') to, say $imageParam = Input::get('image') and execute Storage::delete($imageParam);, it should work on both cases.
The bottomline is: never use the same variable name, as it will led to such unnecessary confusions.

Related

want to generate pdf from laravel request data

i tried to generate pdf from my request data function. but it can't pass variable into my pdf generate function. i get requested data from this function.
public function fetch_data()
{
if(request()->ajax())
{
if(request()->from_date != '' && request()->to_date != '')
{
$data = DB::table('sales')
->whereBetween('dlvd_date', array(request()->from_date, request()->to_date))
->get();
} else {
$data = DB::table('sales')->orderBy('dlvd_date', 'desc')->get();
}
echo json_encode($data);
}
}
i want to get this $data value into my pdf generated function like below.
function convert_sales_data_to_html($data)
{
$sales_data = $data;
dd($sales_data);
$output = '';
return $output;
}
and pass to this function
public function pdf($data)
{
$pdf = \App::make('dompdf.wrapper');
$pdf->loadHTML($this->convert_sales_data_to_html($data))->setPaper('a4', 'landscape');
return $pdf->stream();
}
i tried this so many times but show me errors with missing argument. how can i fix this or have another method to generate pdf from requested data in laravel.
this is my routes
Route::post('salesreport/fetch', 'Report\SalesReportController#fetch_data')->name('salesreport.fetch_data');
Route::get('salesreport/pdf', 'Report\SalesReportController#pdf');

Blade :: compileString() and embedded variables

I am able to parse HTMl that uses blade template variables through the following code:
$generated = Blade::compileString($string);
ob_start();
try
{
eval($generated);
}
catch (\Exception $e)
{
ob_get_clean(); throw $e;
}
$content = ob_get_clean();
return $content;
And it works fine as long as i don't use blade variables within. Which on being parsed give me undefined variable error. How can i make sure that blade variables are available in my custom parsing method?
This works for me with the latest version of Laravel 5.7. Notice how I include the __env var so that functions like #include, #foreach, etc can work.
public static function renderBlade($string, $data = null)
{
if (!$data) {
$data = [];
}
$data['__env'] = app(\Illuminate\View\Factory::class);
$php = Blade::compileString($string);
$obLevel = ob_get_level();
ob_start();
extract($data, EXTR_SKIP);
try {
eval('?' . '>' . $php);
} catch (Exception $e) {
while (ob_get_level() > $obLevel) {
ob_end_clean();
}
throw $e;
} catch (Throwable $e) {
while (ob_get_level() > $obLevel) {
ob_end_clean();
}
throw new FatalThrowableError($e);
}
return ob_get_clean();
}
Turns out I was not passing the arguments array to the method that parses the Blade structure. My assumption was that the Mail::send method takes care of making variables available which it takes in as a second parameter. I also had to extract($args, EXTR_SKIP).
$generated = Blade::compileString($string);
ob_start(); extract($args, EXTR_SKIP)
try
{
eval($generated);
}
catch (\Exception $e)
{
ob_get_clean(); throw $e;
}
$content = ob_get_clean();
return $content;

Get auto incremented value from INSERT statement and assigning it to PHP

I am using Zend framework and Oracle, below is my save() function
public function save()
{
$time = strtotime($_POST['DeliveryDate']);
$deliveryDate = date('d-M-Y',$time);
try{
$result = '';
$dml = "INSERT INTO NOBL_TEC_EFT(SNO_PK, ITEM, ITEM_TYPE, QUANTITY, UNIT_PRICE, NEED_BY_DATE, SITE, DELIVER_TO_LOCATION, AFE, TASK, REQUESTOR, ATTRIBUTE1, ATTRIBUTE2) VALUES (Sno_seq.nextval, '".$_POST['Item']."', '".$_POST['ItemType']."', ".(int)$_POST['Quantity'].", ".(int)$_POST['TotalPrice'].", '".$deliveryDate ."', '".$_POST['Site']."', '".$_POST['DeliverToLoc']."', '".$_POST['Afe']."', 'Task', '".$_POST['Requestor']."', '".$_POST['CodeOne']."', '".$_POST['CodeTwo']."')";
$query = Application_Model_DbTable_Eftrqsthead::getDefaultAdapter();
// echo $dml;
$query = $query->query($dml);
if($query){
return true;
}else{
return false;
}
}catch(Exception $e){
echo $e->getMessage();
}
}
Above in my INSERT statement am inserting SNO_PK as auto incremented value, what I want to do here is I want to get the SNO_PK value from that INSERT statement and assign it to a PHP variable, then return it. I am new to Oracle, any help will be appreciated, Thanks.
I have seen RETURNING clause but didn't understood how to use it in my case.
Check get_class_methods($query) and you will find something like $query->lastInsertId();.
PS. Watch out how you put variables into your SQL. Short way to SQLInjection ;)
It's Simple, while you are executing query, suddenly you will get its last (incremented value). I have implemented your code.
$query = Application_Model_DbTable_Eftrqsthead::getDefaultAdapter();
// echo $dml;
$query = $query->query($dml);
if($query){
echo $query;
return true;
}else{
return false;
}
}catch(Exception $e){
echo $e->getMessage();
}
}

Redirect , POST and Flashdata issue in Codeigniter

i am developing an application where i need some suggestions. Here is the detail of the problem.
public function form()
{
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
if($data = $this->input->post()){
$result = $this->form_validation->run();
if($result){
if($id > 0){
// here update code
}else{
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}
}else{
//$this->call_post($data);
$this->session->set_flashdata('message','The Red fields are required');
$this->view = FALSE;
$this->redirect = "mycontroller/form/$id";
}
}else{
$row = $this->mymodel->fetch_row($id);
$this->data[]= $row;
}
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$return = call_user_func_array(array($this, $method),$parameters);
}else{
show_404();
}
if(strlen($this->view) > 0)
{
$this->template->build('default',array());
}else{
redirect($this->redirect);
}
}
Here you can see how i am trying to reload the page on failed validation.
Now the problem is that i have to display the flash data on the view form which is only available after redirect and i need to display the validation errors to which are not being displayed on redirect due to the loss of post variable. If i dont use redirect then cant display flashdata but only validation errors. I want both of the functionalities togather. I have tried even creating POSt again like this
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
Which i commented out in the formmethod.How can i achieve this.
Here's a thought.
I think you can add the validation error messages into the flash data. Something like this should work:
$this->session->set_flashdata('validation_error_messages',validation_errors());
Notice the call to the validation_errors function. This is a bit unconventional, but I think it should work. Just make sure that the code are executed after the statement $this->form_validation->run(); to make sure the validation error messages are produced by the Form Validation library.
well i have little different approach hope will help you here it is
mycontroller extend CI_Controller{
function _remap($method,$params){
switch($method){
case 'form':
$this->form($params);
break;
default:
$this->index();
break;
}
}
function form(){
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
$this->form_validation->set_rules('name','Named','required|trim');
$this->form_validation->set_rules('email','email','required|valid_email|trim');
// if validation fails and also for first time form called
if(!$this->form_validation->run()){
$this->template->build('default',array());
}
else{ // validation passed
$this->save($id)
}
}
function save($id = 0){
$data = $this->input->post();
if($id == 0){
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}else{
// update the field
$this->session->set_flashdata('message','The Red fields are required');
}
redirect("mycontroller/index");
}
}
your form/default view should be like this
<?
if(validation_errors())
echo validation_errors();
elseif($this->session->flashdata('message'))
echo $this->session->flashdata('message');
echo form_open(uri_string());// post data to same url
echo form_input('name',set_value('name'));
echo form_input('email',set_value('email'));
echo form_submit('submit');
echo form_close();
try it if you face any problem post here.

"File was not uploaded" magento error even file is uploaded to particular folder

I am making an application in which i am uploading file from my custom tab as follows
i created a observer for event called catalog_product_save_after. In the particular function, i am uploading those files to catalog/product folder and its get uploaded to those folder without any error.
But when i am trying to assign those images to that particular product, i got the following error.
File was not uploaded at file E:\xampp\htdocs\magento\lib\Varien\File\Uploader.php on line 152
If i check system.log then i see the 2012-08-24T11:33:15+00:00 ERR (3): User Error: Some transactions have not been committed or rolled back in E:\xampp\htdocs\magento\lib\Varien\Db\Adapter\Pdo\Mysql.php on line 3645 this error.
My observer function is as follows
public function Savedata($observer)
{
$params = Mage::app()->getRequest()->getParams();
$product = $observer->getEvent()->getProduct();
$product_id = $product->getId();
$filesData = array();
$keysData = array_keys($_FILES);
foreach($keysData as $keys)
{
$uploader = new Varien_File_Uploader("$keys");
$uploader->setAllowedExtensions(array('jpeg', 'jpg', 'png', 'tiff'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . "catalog" . DS . "product";
if(!is_dir($path))
{
mkdir($path);
}
$extension = pathinfo($_FILES["$keys"]['name'], PATHINFO_EXTENSION);
$date = new DateTime();
$file_name = $keys . "_" . $product_id . "." . $extension;
$_FILES["$keys"]['name'] = $file_name;
$uploader->save($path, $_FILES["$keys"]['name']);
$filesData[] = $path .DS. $_FILES["$keys"]['name'];
}
print_r($filesData);
///till this works file.. when i add following code, program dies.
try
{
$productData = Mage::getModel('catalog/product')->load($product_id);
print_r($productData->getData());
foreach($filesData as $file)
{
$productData->addImageToMediaGallery($file, "image" ,false, false);
}
$productData->save();
$productData = Mage::getModel('catalog/product')->load($product_id);
print_r($productData->getData());
}
catch (Exception $e)
{
echo $e->getMessage() . "||" . $e->getCode() . "||" . $e->getFile() . "||" . $e->getLine();
}
exit();
}
any suggestion where i am going wrong? why this error occur?
i am using magento 1.7
I see that you're going to update your catalog/product object when you're saving it.
You are using event catalog_product_save_after.
Inside the observer, you call:
$productData = Mage::getModel('catalog/product')->load($product_id);
...
$productData->save();
$productData is catalog/product object -> you saved it.
You can guess what will happen, it will trigger event catalog_product_save_after and so on, looping forever.
I see that you call $productData->save(); because in this event, the value has been saved and can not be changed.
So instead of using catalog_product_save_after, you can use catalog_product_save_before.
The same like your code, but remove $productData->save(); because it will automatically call save.
Mage_Core_Model_Abstract
public function save()
{
/**
* Direct deleted items to delete method
*/
if ($this->isDeleted()) {
return $this->delete();
}
if (!$this->_hasModelChanged()) {
return $this;
}
$this->_getResource()->beginTransaction();
$dataCommited = false;
try {
$this->_beforeSave();
if ($this->_dataSaveAllowed) {
//see this line below, it will call save, so you don't need to call save in your `catalog_product_save_before` (no looping forever)
$this->_getResource()->save($this);
$this->_afterSave();
}
$this->_getResource()->addCommitCallback(array($this, 'afterCommitCallback'))
->commit();
$this->_hasDataChanges = false;
$dataCommited = true;
} catch (Exception $e) {
$this->_getResource()->rollBack();
$this->_hasDataChanges = true;
throw $e;
}
if ($dataCommited) {
$this->_afterSaveCommit();
}
return $this;
}

Resources