Zend 2 CSV Action - zend-framework

I have created the following action, which successfully returns a CSV. however it still returns the layout within the response. From what i have read the layout is not supposed to be returned. aAnyone know how to disable this?
public function csvAction() {
$content = 'test';
$response = $this->getResponse();
$response->getHeaders()
->addHeaderLine('Content-Type', 'text/csv')
->addHeaderLine('Content-Disposition', "attachment; filename=\"my_filen.csv\"")
->addHeaderLine('Accept-Ranges', 'bytes')
->addHeaderLine('Content-Length', strlen($content));
$response->setContent($content);
return $response;
}

Try adding these at the beginning of your csvAction function:
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();

Related

Where to see out put of Print_r() in codeigniter

i am learning codeigniter and i use methods(functions) in model to get data from the database. i am not sure whether my method is fetching correct data i want to use print_r(); exit; to debug but do not know where and how to see the output. can any one help me
for example my method in a model is
public function get_price($check)
{
$this->db->select('*');
$this->db->where('name', $check);
$this->db->from('group_test');
$query = $this->db->get();
print_r($query); exit;
return $query->result();
}
Your function is fine. The only change you need to do is use print_r function as below
public function get_price($check)
{
$this->db->select('*');
$this->db->where('name', $check);
$this->db->from('group_test');
$query = $this->db->get();
print_r($query->result());
//return $query->result();
}
So the above code will print the result as an array of objects. Let me know if you want anything else.

ZF2 Append value to array in php file with Zend\Config\Factory

I try to add new value to array in php file with Zend\Config\Factory:
public function testFunc($testParam)
{
$testArray = $this->testFunc1($testParam);
if(!is_null($testArray[1])) {
foreach ($testArray[1] as $array) {
$this->testFunc($array);
}
}
$filename = getcwd() . '/data/config/config.php';
$configFile = \Zend\Config\Factory::fromFile($filename);
$configFile[] = $testArray[0];
if(!\Zend\Config\Factory::toFile($filename, $configFile)) {
throw new Exception\RuntimeException("Can't put content to $filename.");
}
return true;
}
The problem is such that in $filename file saves only value from first function call and not from recursion.
[UPDATE]
I debug \Zend\Config\Factory::fromFile and found if I wanna to load php file, function load file that:
........
$config = include $filepath;
in recursion \Zend\Config\Factory::toFile update my php file(i checked config.php file) and then in first function call \Zend\Config\Factory::fromFile get again php file without changes and overwrite config.php. As a consequence , is recorded only value from first function call in config.php.

Zend Framework export Doctrine query results to XML file

I have a need to export certain queries to xml files. I have this working in that the file is created and the data are exported, however I'm receiving the following error on screen as the file is being exported and not displayed.
This page contains the following errors:
error on line 3 at column 1: Extra content at the end of the document
I'll admit that I'm new to this as most of you are aware but is there a way I can export and just display a confirmation message to the user that the report has been saved, or am I going about this the wrong way completely?
My code is below
My controller
public function init()
{
// allow certain reports to be exported to xml
// initialize context switch helper
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('newsletterexport', 'xml')
->initContext();
}
public function newsletterexportAction()
{
$q = Doctrine_Query::create()
->select('c.firstname,c.lastname,c.address1,c.address2,c.address3,t.county')
->from('PetManager_Model_Clients c')
->leftJoin('c.PetManager_Model_Counties t')
->where('c.consentToNews=1');
$result = $q->fetchArray();
if (count($result) >= 1) {
$this -> view -> records = $result;
}
}
EDIT
Ok I tried moving the code from the xml.phtml into my controller as suggested and tried to save the document with save, but now I get the start of the xml document as shown below but no records are saved to the document.
<?xml version="1.0" encoding="utf-8"?>
<petmanager:document xmlns:petmanager="http://petmanager"><petmanager:records/></petmanager:document>
My controller code as of this edit
public function newsletterexportAction()
{
$q = Doctrine_Query::create()
->select('c.firstname,c.lastname,c.address1,c.address2,c.address3,t.county')
->from('PetManager_Model_Clients c')
->leftJoin('c.PetManager_Model_Counties t')
->where('c.consentToNews=1');
$result = $q->fetchArray();
if (count($result) >= 1) {
//$this -> view -> records = $result;
$docpref="newsletterexport";
$docDate=date('y-m-d');
$ext=".xml";
$docname=$docpref.$docDate.$ext;
// create XML document
$dom = new DOMDocument('1.0', 'utf-8');
// create root element
$root = $dom->createElementNS('http://petmanager','petmanager:document');
$dom->appendChild($root);
// convert to SimpleXML
$xml = simplexml_import_dom($dom);
// add resultset elements
$records = $xml->addChild('records');
foreach($this->$result as $r){
$record = $records->addChild('record');
$record->addChild('firstName',$this->escape($r['firstName']));
$record->addChild('lastName',$this->escape($r['lastName']));
$record->addChild('address1',$this->escape($r['address1']));
$record->addChild('address2',$this->escape($r['address2']));
$record->addChild('address3',$this->escape($r['address3']));
$record->addChild('county',$this->escape($r['PetManager_Model_Counties']['county']));
}//end of foreach
// saave document
$xml->saveXML();
$dom->save('D:/reports/exports/'.$docname.'');
}
DomDocument::saveXML() doesnt take a file path - it returns the XML document as text. If you want to save it directly as a file like youre doing you use DomDocument::save().
All that logic in your phtml should be in your controller. You have also set the context to xml, so the view is going to output XML to the browser, not HTML... so id doesnt make sense to display a confirmation message unless its encoded in XML, otherwise you need to use the default context (HTML). So if you want to save the file to the webserver and display a confirmation you would do:
public function exportXmlAction(){
// remove the context switch from init
// do your doctrine stuff
// build the xml DOM as $xml
$xml->save('path/to/file');
$this->message = 'File was exported successfully!';
}
// in your phtml
<?php echo $this->message; ?>
If you want to display the xml on screen:
public function exportXmlAction(){
// do your doctrine stuff
// build the xml DOM as $xml
$this->xmlDom = $xml;
}
// in your phtml
<?php echo $this->xmlDom->saveXml(); ?>
The question i have though is whay would a user want ot export xml to the server. When you call DomDocument::save() youre saving that file to a path on the server, not the user's machine so what would be the point of exporting the xml to the server where the user has no access to it?

How to paginate search results?

I want to paginate search results using Zend_Paginator. So I pass my data to a paginator instance:
$paginator = new Zend_Paginator (
new Zend_Paginator_Adapter_DbSelect ( $data )
);
Data is returned this way
public function getData($idArray){
$db = Zend_Db_Table::getDefaultAdapter();
$selectProgramme = new Zend_Db_Select($db);
$selectProgramme->from('programme')
->order('id DESC')
->where('id IN(?)', $idArray);
return $selectProgramme;
}
$idArray is provided by my search implementations. This all works great and I get the correct data and pagination links displayed.
However I can't paginate the result because the pagination links are not valid. So normal pagination would have following link:
mysite.de/home/index/page/1
in search I now have
mysite.de/home/search/page/1
This does not work. Any suggestions how to implement search pagination?
EDIT: I have a HomeController with two actions, index and search action. IndexAction displays all data and I can paginate it.
public function indexAction(){
//...
$paginator = new Zend_Paginator(
new Zend_Paginator_Adapter_DbSelect($data)
);
$paginator->setItemCountPerPage(16)
->setPageRange(20)
->setCurrentPageNumber($this->_getParam('page', 1));
$this->view->data = $paginator;
}
The searchActions handles the search process:
public function searchAction(){
$response = $solr->search($this->getRequest()->getParam('search', null));
//...if items found get the data exactly the same way as in the
// index action, using Zend_Paginator_Adapter_DbSelect
$paginator = new Zend_Paginator(
new Zend_Paginator_Adapter_DbSelect($data)
);
$paginator->setItemCountPerPage(16)
->setPageRange(20)
->setCurrentPageNumber($this->_getParam('page', 1));
$this->view->data = $paginator;
}
So like you see in the search action there is a problem with the search process when I paginate. I need to decide somehow if to search or to paginate. Any suggestions on that?
Since search required the search parameter pagination will fail because when paginating the the search parameter is null.
$sreq = $this->getRequest()->getParam('search', null);
So we need to pass this parameter whenever we paginate our search. I solve this using Zend_Session:
//get search param
$sreq = $this->getRequest()->getParam('search', null);
//store search param in session for pagination
$search = new Zend_Session_Namespace('PSearch');
if($sreq != null){
$search->psearch = $sreq;
}else{
$sreq = $search->psearch;
}
I have this at the top of my searchAction and everything works.
Not sure I understand, but is your problem that the page parameter from the url is not making it's way to the Paginator - e.g. regardless of what page you are on, it is always showing the first 20 results?
If so, have you tried manually setting the page on the paginator:
$page = $this->_getParam('page', 1);
$paginator->setCurrentPageNumber($page);
public function search()
Are you sure that you didn't mistyped here? Should be
public function searchAction()
You put your search data into $response but create paginator instance using $data (which is null)

Youtube API - How to limit results for pagination?

I want to grab a user's uploads (ie: BBC) and limit the output to 10 per page.
Whilst I can use the following URL:
http://gdata.youtube.com/feeds/api/users/bbc/uploads/?start-index=1&max-results=10
The above works okay.
I want to use the query method instead:
The Zend Framework docs:
http://framework.zend.com/manual/en/zend.gdata.youtube.html
State that I can retrieve videos uploaded by a user, but ideally I want to use the query method to limit the results for a pagination.
The query method is on the Zend framework docs (same page as before under the title 'Searching for videos by metadata') and is similar to this:
$yt = new Zend_Gdata_YouTube();
$query = $yt->newVideoQuery();
$query->setTime('today');
$query->setMaxResults(10);
$videoFeed = $yt->getUserUploads( NULL, $query );
print '<ol>';
foreach($videoFeed as $video):
print '<li>' . $video->title . '</li>';
endforeach;
print '</ol>';
The problem is I can't do $query->setUser('bbc').
I tried setAuthor but this returns a totally different result.
Ideally, I want to use the query method to grab the results in a paginated fashion.
How do I use the $query method to set my limits for pagination?
Thanks.
I've decided just to use the user uploads feed as a way of getting pagination to work.
http://gdata.youtube.com/feeds/api/users/bbc/uploads/?start-index=1&max-results=10
If there is a way to use the query/search method to do a similar job would be interesting to explore.
I basically solved this in the same way as worchyld with a slight twist:
$username = 'ignite';
$limit = 30; // Youtube will throw an exception if > 50
$offset = 1; // First video is 1 (silly non-programmers!)
$videoFeed = null;
$uploadCount = 0;
try {
$yt = new Zend_Gdata_YouTube();
$yt->setMajorProtocolVersion(2);
$userProfile = $yt->getUserProfile($username);
$uploadCount = $userProfile->getFeedLink('http://gdata.youtube.com/schemas/2007#user.uploads')->countHint;
// The following code is a dirty hack to get pagination with the YouTube API without always starting from the first result
// The following code snippet was copied from Zend_Gdata_YouTube->getUserUploads();
$url = Zend_Gdata_YouTube::USER_URI .'/'. $username .'/'. Zend_Gdata_YouTube::UPLOADS_URI_SUFFIX;
$location = new Zend_Gdata_YouTube_VideoQuery($url);
$location->setStartIndex($offset);
$location->setMaxResults($limit);
$videoFeed = $yt->getVideoFeed($location);
} catch (Exception $e) {
// Exception handling goes here!
return;
}
The Zend YouTube API seems silly as the included getUserUploads method never returns the VideoQuery instance before it actually fetches the feed, and while you can pass a location object as a second parameter, it's an "either-or" situation - it'll only use the username parameter to construct a basic uri or only use the location, where you have to construct the whole thing yourself (as above).