Export CSV functionality for gird inside admin edit form tab magento - export-to-csv

I have a magento grid collection inside admin edit form tab.I need a export csv functionality for the grid.Its working fine with full grid list without search filters.How to export csv for the filtered collection as well?

Go to your module or extension folder then /Block/Adminhtml/Blog/Grid.php. Open this Grid.php file and search the function protected function _prepareCollection() and add the following code under this function before return parent::_prepareColumns();.
$this->addExportType('*/*/exportCsv', Mage::helper('blog')->__('CSV'));
$this->addExportType('*/*/exportXml', Mage::helper('blog')->__('XML'));
After add this code it may be looks like that:
Next, in this extension or module folder go to /controllers/Adminhtml/ and open the controller file and add the following code under the class (add the code bottom of the page before last '}')
public function exportCsvAction()
{
$fileName = 'blog.csv';
$content = $this->getLayout()->createBlock('[your-module-name]/adminhtml_[your-module-name]_grid')
->getCsv();
$this->_sendUploadResponse($fileName, $content);
}
public function exportXmlAction()
{
$fileName = 'blog.xml';
$content = $this->getLayout()->createBlock('[your-module-name]/adminhtml_[your-module-name]_grid')
->getXml();
$this->_sendUploadResponse($fileName, $content);
}
protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream')
{
$response = $this->getResponse();
$response->setHeader('HTTP/1.1 200 OK','');
$response->setHeader('Pragma', 'public', true);
$response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
$response->setHeader('Content-Disposition', 'attachment; filename='.$fileName);
$response->setHeader('Last-Modified', date('r'));
$response->setHeader('Accept-Ranges', 'bytes');
$response->setHeader('Content-Length', strlen($content));
$response->setHeader('Content-type', $contentType);
$response->setBody($content);
$response->sendResponse();
die;
}
Now replace the [your-module-name] text with your extension or module name and save then check.
* Please like if this post help you!*

Related

PHP dynamic URL keeps adding/doubling the full path when i click a button on the site

I am running into an issue and I hope someone here can help. I have put together a dynamic URL manipulator that should just work out the path to the file being displayed, which it does and when I click a link, it should process the new link and replace the existing URL. The issue is that instead of replacing the URL with the new url path, it adds it to the end of the existing URL which is why it does not work. an example is as follows:
https://localhost/home/main/localhost/home/main/pages/about
the part from the second localhost... should replace the first url path but it adds to it and therefore it does not work. the code for this is as follows:
class Core {
protected $currentController = 'Pages';
protected $currentMethod = 'index';
protected $params = [];
public function __construct(){
//print_r($this->getUrl());
$url = $this->getUrl();
if(file_exists('../app/controllers/' . ucwords($url[0]). '.php')){
$this->currentController = ucwords($url[0]);
unset($url[0]);
}
require_once '../app/controllers/'. $this->currentController . '.php';
$this->currentController = new $this->currentController;
if(isset($url[1])){
if(method_exists($this->currentController, $url[1])){
$this->currentMethod = $url[1];
unset($url[1]);
}
}
$this->params = $url ? array_values($url) : [];
call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
}
public function getUrl(){
if(isset($_GET['url'])){
$url = rtrim($_GET['url'], '/');
$url = filter_var($url, FILTER_SANITIZE_URL);
$url = explode('/', $url);
return $url;
}
}
}
Hi anyone who cares to know the solution to this, or have a similar issue and is looking to find a solution.
I found out that the issue was with the htaccess file which did not have the full root of the home page.
I had entered
RewriteBase /main/public
my app is in a subfolder called home so after updating it to the following, it works like a charm.
RewriteBase /home/main/public

zend session namespace not working

I am unable to access zend session in included file via layout.
what i have done so far -
//bootstrap
public function _initSession()
{
Zend_Session::start();
$test = new Zend_Session_Namespace('test');
}
//controller
public function init(){
$test = new Zend_Session_Namespace('test');
$test->abc = 'defghi';
}
//layout include file
<?php include_once( APPLICATION_PATH . '/data/ga_test.php');?>
//ga_test.php
$test = new Zend_Session_Namespace('test');
echo 'this is ' . $test->abc;
I am not able to access the variable in ga_test file. I am getting an empty variable. But if I include ga_test end of each view file then it works. Obviously I don't want to go to every view file and include ga_test.php. Can I do this via layout.
I am sure, I am doing something wrong here. Any help would be really appreciated.
Thanks

ZEND - Issue with download file (encoding, not able to open downloaded file)

I made a download form in my project, but problem is when i download the file and im trying to open it, Zend renderer is adding to it my layout html code... I read that i have to disable renderer and layout. But the problem is tjat i have to do this in my own helper, not in controller file, cause i need to have download in that helper file.
My download function is something like this:
<?php
class Zend_View_Helper_EditArticles extends Zend_View_Helper_Abstract
{
public function EditArticles()
{
//some code here, getting data from db table
//and now the download
if (isset($_POST['downloadarticle' . $i])) {
//this is probably bad and its not working as it should
//(?)Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
//(?)Zend_Controller_Action_HelperBroker::getStaticHelper('layout')->disableLayout();
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/articles/';
$file = $articles->GetArticleToDownload($_POST['art_id' . $i]);
$name = $file['name'];
$path = $file['path'];
$getfile = str_replace('//', '/', $targetPath) . $path . '.pdf';
$size = $file['size'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=$name.pdf");
header("Content-length: $size");
header('Content-Transfer-Encoding: binary');
readfile($getfile);
break;
}
}
echo $this->view->partial('/index/index.phtml','EditArticles');
And when I download the PDF, Adobe Reader can't open it (when I download other files they can't be opened either). I opened them with notepad and before the PDF content there was a lot of HTML layout code... What am I doing wrong?
In Adobe Reader I get this message:
Adobe Reader could not open 'filename.pdf' because it is either not a supported file type or because the file has been damaged for example, it was sent as an email attachment and wasn't correctly decoded).
That code does not belong in a view helper. It belongs in the controller or maybe an action helper.
Something like this in your controller should work:
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
// ...
$this->getResponse()
->setHeader('Content-Description', 'File Transfer', true)
->setHeader('Content-Type', 'application/pdf', true) // change to application/pdf
->setHeader('Content-Disposition', "attachment; filename={$name}.pdf", true)
->setHeader('Content-length', $size, true)
->setHeader('Content-Transfer-Encoding', 'binary', true)
->appendBody(readfile($getfile));
The following 2 lines of code should accomplish what you need and do it in a fashion that works from anywhere in your Zend application.
Zend_Layout::getMvcInstance()->disableLayout();
Zend_Controller_Front::getInstance()->setParam('noViewRenderer', true);

Magento product imports from csv file

I want to import Magento products from my csv file, but when I import this csv file I get an error like this ( Skip import row, required field "sku" not defined) However, I had this field defined in my csv file.
If any one has any idea about that then please advise me. Which method should I follow to import my csv products to Magento
Thanks for help in advance
I find this solution its very simple:
just go to system->import/export and then u export all product by csv
now enter all other fields or attribute data in csv which u required.
<?php
set_time_limit(0);
define('MAGENTO_MAGE_LOCATION','/your site name path/app/Mage.php');
error_reporting(E_ALL);
$handle = fopen("your csv name path.csv", "r");
$count=0;
while (($data = fgetcsv($handle)) !== FALSE)
{
$count++;
if($data[0] != 'store')
{
require_once MAGENTO_MAGE_LOCATION;
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');
$product->setSku($data[5]);
$product->setName($data[7]);
.
.
.
try {
$product->save();
echo '<br> hi product save successfully in magento uniqe mobile store';
}
catch (Exception $ex) {
echo 'Handle the error';
}
}// end of if statment store
}// end of while loop
fclose($handle);
?>
use this code and set all products but all fields set acourding to ur CSV file. then run this code .
its working i test this code. its my own creation

ZendFramework Zend_Form_Element_File setDestination vs rename filter

The code says Zend_Form_element_File::setDestination() is deprecated and to use the rename filter. However the rename filter is currently codes such that when path is set, only temporary name is given. Original filename is lost.
<?php
$file = new Zend_Form_Element_File();
$file->setDestination('/var/www/project/public');
?>
vs
<?php
$file = new Zend_Form_Element_File();
$file->addFilter('Rename', array('target' => '/var/www/project/public'));
?>
Any solution to upload files so that it preserves original filename structure but checks for existing file and appends _1.ext or _2.ext?
You need to query the name of the file after upload and then add the Rename filter then. Eg:
if ($form->file->isUploaded()) {
$fileinfo = $form->file->getFileInfo();
$filename = $fileinfo['file']['name'];
$extn = pathinfo($filename,PATHINFO_EXTENSION);
$uploadname = $this->_makeFilename($formData, $extn);
$uploadfilepath = UPLOADED_FILES_PATH . '/' . $uploadname;
$form->file->addFilter('Rename', $uploadfilepath);
$receiveStatus = $form->file->receive();
}
After submitting the form you can inspect the $_FILES['file_element']['name'] check for existing files and then set the rename filter on your form element before calling the :
$form->getValues()/isValid() or $form->file_element->receive().