Zend_Paginator stopped working - zend-framework

I'm learning Zend Framework. I had Zend_Paginator working with the array adapter, but I'm having trouble using the Zend_Paginator::factory static method. The problem is the pagination control links send me to the correct URL, but the results disappear when I click next or page 2, 3, etc.
I have two tables from a database: a file table and an origination_office table. The file table has the client's names, address, etc. and the origination office stores office names (like Tampa, Sarasota, etc.). Each file is associated with an origination office.
My controller:
public function searchAction()
{
$searchForm = new Application_Form_SearchForm();
if ($this->_request->getQuery()) {
if ($searchForm->isValid($this->_request->getParams())) {
$officeName = $this->_request->getParam('officeName');
$page = $this->_request->getParam('page');
}
$fileTable = new Application_Model_DbTable_File();
$this->view->paginator = $fileTable->getFilesByOfficeName($officeName, $page);
}
$this->view->searchForm = $searchForm;
}
Here is the getFilesByOfficeName() method:
public function getFilesByOfficeName($officeName = null, $page = 1, $count = 12, $range = 15, $scrolling = 'Sliding')
{
if (is_null($officeName)) {
$query = $this->select();
$paginator = Zend_Paginator::factory($query);
} else {
$oofTable = new Application_Model_DbTable_OriginationOffice();
$query = $oofTable->select();
$query->where('oof_name like ?', $officeName.'%');
if ($oofTable->fetchRow($query)) {
$origination_office = $oofTable->fetchRow($query);
$files = $origination_office->findDependentRowset($this);
$paginator = Zend_Paginator::factory($files);
} else {
return;
}
}
Zend_Paginator::setDefaultScrollingStyle($scrolling);
Zend_View_Helper_PaginationControl::setDefaultViewPartial('_pagination_control.phtml');
$paginator->setDefaultItemCountPerPage($count);
$paginator->setDefaultPageRange($range);
$paginator->setCurrentPageNumber($page);
return $paginator;
}

Ok, I think I am understanding your problem. Your links are not maintaining the state of your initial request and it's URL query string.
You might want to edit your partial view (_pagination_control.phtml) to render the current query string in your links.
I would need to see what your doing in the partial to give an exact answer, but this should work if you add ?$_SERVER['QUERY_STRING'] to the end of your final URL. See Below Example:
<!-- Your href may look different but notice I append the query string to the end -->
Last ยป

Related

Creating cumulative pdf of orders in magento

I want to create a pdf of first 300 orders in magento. I want a functionality in which i will get first 300 orders and print their images(each order has different image) in a pdf. So how can i implement this functionality in magento. Is there any extension for that?
Take a look at /app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
public function pdfinvoicesAction(){
$orderIds = $this->getRequest()->getPost('order_ids');
$flag = false;
if (!empty($orderIds)) {
foreach ($orderIds as $orderId) {
$invoices = Mage::getResourceModel('sales/order_invoice_collection')
->setOrderFilter($orderId)
->load();
if ($invoices->getSize() > 0) {
$flag = true;
if (!isset($pdf)){
$pdf = Mage::getModel('sales/order_pdf_invoice')->getPdf($invoices);
} else {
$pages = Mage::getModel('sales/order_pdf_invoice')->getPdf($invoices);
$pdf->pages = array_merge ($pdf->pages, $pages->pages);
}
}
}
if ($flag) {
return $this->_prepareDownloadResponse(
'invoice'.Mage::getSingleton('core/date')->date('Y-m-d_H-i-s').'.pdf', $pdf->render(),
'application/pdf'
);
} else {
$this->_getSession()->addError($this->__('There are no printable documents related to selected orders.'));
$this->_redirect('*/*/');
}
}
$this->_redirect('*/*/');
}
From the above function you could assign the first 300 order ids to $orderIds (or modify Mage::getResourceModel('sales/order_invoice_collection to get the first 300 records)
See magento orders list query
Changes :
public function pdfinvoicesAction(){
$orderIds = $this->getRequest()->getPost('order_ids');
To (something like)
public function pdfinvoices($orderIds){
$orderIds = (array) $orderIds; // first 300 record ids
Change line to save pdf to file
return $this->_prepareDownloadResponse(
'invoice'.Mage::getSingleton('core/date')->date('Y-m-d_H-i-s').'.pdf', $pdf->render(),
'application/pdf'
);
To
$pdf->render();
// use the order_id for the pdf name like
$pdf->save("{$orderId}.pdf");
see Error in generated pdf file using zend_pdf under Magento
You could also delete the $this->_redirect('//')

Zend Paginate - find a specific record within the result

I appreciate that this may not be possible, but is there a way to make Zend Paginate go to a specific item (record)?
The result I would like would allow me to seek a specific record in a tabled list of results, and display the appropriate page (within all available pages) combined with a name anchor tag to display the specific record.
To clarify: If I had the results as a Zend_Db_Table_Rowset_Abstract I would use the seek() method in a similar fashion to $rowset->seek(8); Although I don't believe the result returned by the DbSelect adapter is a SeekableIterator?
The code within my Mapper (using the Table Data Gateway pattern):
public function paginate($where = array(), $order = null)
{
$select = $this->getDbTable()->select()->from($this->getTableName(), $this->getTableFields());
foreach ($where as $key => $value) {
$select->where($key, $value);
}
$select->order($order);
$adapter = new Zend_Paginator_Adapter_DbSelect($select);
$paginator = new Zend_Paginator($adapter);
return $paginator;
}
Within my controller:
$cache_id = sha1('list');
$mapper = new Application_Model_Galleries_Mapper();
if(!($data = Zend_Registry::get('cache')->load($cache_id))) {
$data = $mapper->paginate(array(), $sort);
Zend_Registry::get('cache')->save($data, $cache_id, array('list'), 7200);
}
$data->setCurrentPageNumber($this->_getParam('page'));
$data->setItemCountPerPage(30);
$this->view->paginator = $data;
To return a Zend_Paginator with a seekable iterator (Zend_Db_Table_Rowset) use the Zend_Paginator_Adapter_DbTableSelect() as it returns a rowset object, as opposed to Zend_Paginator_Adaoter_DbSelect() which returns an array().
Zend_Paginator

Zend Dojo FilteringSelect from joined tables How can this be done with Doctrine

I have a number of FilteringSelect elements within my Zend Framework application that are working fine but they are based on simple queries.
I now need to create a FilteringSelect that will allow me to select the id of one table while displaying the text of field in a related table, i.e. I have two tables groomservices and groomprocedures which are related (i.e. groomprocedures.groomProceduresID has many groomservices.procedure).
The form I'm trying to create is for an appointments table which has many groomservices.groomServicesID values. I want the user to be able to see the name of the procedure while saving the value of the groomservices.groomServicesID using the FilteringSelect.
So far I've not been able to do this in that my FilteringSelect displays nothing, I'm sure this can be done just that the fault is with my inexperience with Zend,Doctrine and Dojo
I'm not sure if my problem is with my autocomplete action(including the query) or with the FilteringSelect element.
Can anyone spot where I've gone wrong in the code sections below, I need to get this working.
My autocomplete action within my controller
public function gserviceAction()
{
// disable layout and view rendering
$this->_helper->layout->disableLayout();
$this->getHelper('viewRenderer')->setNoRender(true);
// get a list of all grooming services IDs and related procedures
$qry= Doctrine_Query::create()
->select('g.groomServicesID,p.groomProcedure')
->from('PetManager_Model_Groomservices g')
->leftJoin('g.PetManager_Model_Groomprocedures p');
$result=$qry->fetchArray();
//generate and return JSON string
$data = new Zend_Dojo_Data('g.groomServicesID',$result);
echo $data->toJson();
}
My FilteringSelect element code
// Create a autocomplete select input for the service
$gservice = new Zend_Dojo_Form_Element_FilteringSelect('gapmtService');
$gservice->setLabel('Proceedure');
$gservice->setOptions(array(
'autocomplete' => true,
'storeID' => 'gserviceStore',
'storeType' => 'dojo.data.ItemFileReadStore',
'storeParams' => array('url' => "/groomappointments/appointment/gservice"),
'dijitParams' => array('searchAttr' => 'groomProcedure')))
->setRequired(true)
->addValidator('NotEmpty', true)
->addFilter('HTMLEntities')
->addFilter('StringToLower')
->addFilter('StringTrim');
Many thanks in advance,
Graham
P.S. orgot to mention I tried the following query in mysql and I gave me what I'm looking for I believe the Doctine query evaluates to the same.
select groomservices.groomservicesID,groomprocedures.groomprocedure from groomprocedures left join groomservices on groomprocedures.groomproceduresID =groomservices.groomProcedure
But I'm not sure if I formatted the query correctly in Doctrine.
EDIT in relation to the flammon's comments
Ok I've set the code to the following but I'm still not getting anything to display.
public function gserviceAction()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContexts(array(
'gservice' => 'json'
));
// get a list of all grooming services IDs and related procedures
$qry= Doctrine_Query::create()
->select('g.groomServicesID AS id,p.groomprocedure AS name')
->from('PetManager_Model_Groomservices g')
->leftJoin('g.PetManager_Model_Groomprocedures p');
$this->view->model = (object) array();
$this->view->model->identifier = 'id';
$this->view->model->label = 'name';
$this->view->model->items = array();
$tableRows = $this->dbTable->fetchAll($qry);
foreach ($tableRows as $row) {
$this->view->model->items[] = $row->toArray();
}
}
I'm sure the fault lies with me.
It looks like there's a problem with the data that you're putting in the ItemFileReadStore.
Here are a few pointers.
Consider extending Zend_Rest_Controller for your services. It'll be easier to manage your contexts and your views. You'll be able to do something like this:
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContexts(array(
'gservice' => 'json'
));
}
And it will eliminate the need for the following in each of you service actions.
// disable layout and view rendering
$this->_helper->layout->disableLayout();
$this->getHelper('viewRenderer')->setNoRender(true);
You'll need to either pass the format parameter or use the following plugin to help with the context switch. Passing the format parameter is simpler but it pollutes the url with ?format=json. Here's the Zend documentation on AjaxContext.
Here's a plugin that you can use if you don't want to pass the format parameter.
class Application_Plugin_AcceptHandler extends Zend_Controller_Plugin_Abstract
{
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
if (!$request instanceof Zend_Controller_Request_Http) {
return;
}
$header = $request->getHeader('Accept');
switch (true) {
case (strstr($header, 'application/json')):
Zend_Registry::get('logger')->log('Setting format to json', Zend_Log::INFO);
$request->setParam('format', 'json');
break;
case (strstr($header, 'application/xml')
&& (!strstr($header, 'html'))):
Zend_Registry::get('logger')->log('Setting format to xml', Zend_Log::INFO);
$request->setParam('format', 'xml');
break;
default:
Zend_Registry::get('logger')->log('Setting format to html', Zend_Log::INFO);
break;
}
}
}
In your controller, instead of echoing the data, create view variables that dojo expects. See this document for the format.
$this->view->model = (object) array();
$this->view->model->identifier = 'id';
$this->view->model->label = 'name';
$this->view->model->items = array();
In your controller, fetch your table rows:
$tableRows = $this->dbTable->fetchAll($select);
or, if you've put model code in a function, it might look more like:
$tableRows = $this->dbTable->fetchGroomProcedures();
Put your row data in the model->items[] array:
foreach ($tableRows as $row) {
$this->view->model->items[] = $row->toArray();
}
Create a view, view/scripts/appointment/gservice.json.phtml and in it put
Zend_Json::encode($this->model)
Use Firebug to see what is returned from your service.

How can I improve the performance of this Zend_Search_Lucene query?

How can I improve the query as seen below?
My index is fully optimized and all fields are unstored except for item_id which is a keyword field.
The problem is in the "if ($auth) {" section. If this section is removed search times are always under 1 sec but when this section is added in search times are 5 sec or more. Obviously it's a more complex query but I can't live without it. I need the logic in that section to get only search results that the user is authorized to view. I know the slowdown is in the search effort itself because if I remove the line "if ($authQuery) { $query->addSubquery($authQuery, true); }" the search is quite fast.
I'm trying to basically effect the following logic in the "if ($auth) {" section:
lucene fields gi_aro, gc_aro, i_access and c_access all consist of nothing more than a single integer each
if ((array_in({gi_aro}, $gmid) OR {i_access} <= $gid)
AND (array_in({gc_aro}, $gmid) {OR c_access} <= $gid)) {
include in search results
}
{} = lucene fields
// keywords query
$keywords = explode(' ', $keyword);
$keywordQuery = new Zend_Search_Lucene_Search_Query_Multiterm();
foreach ($keywords as $term) {
$keywordQuery->addTerm(new Zend_Search_Lucene_Index_Term($term, 'content'));
$keywordQuery->addTerm(new Zend_Search_Lucene_Index_Term($term, 'search_display_name'));
}
// topcat query
if (!empty($topcat)) {
$term = new Zend_Search_Lucene_Index_Term($topcat, 'topcats');
$topcatQuery = new Zend_Search_Lucene_Search_Query_Term($term);
}
// cat query
if (!empty($cat)) {
$term = new Zend_Search_Lucene_Index_Term($cat, 'cats');
$catQuery = new Zend_Search_Lucene_Search_Query_Term($term);
}
// only authorized items query
if ($auth) {
$user = JFactory::getUser();
$gid = (int)$user->get('aid');
$gmid = explode(',', $user->gmid);
// flexicontent cat auth
$gcQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach ($gmid as $g) {
$gcQuery->addTerm(new Zend_Search_Lucene_Index_Term($g, 'gc_aro'));
}
// stock joomla cat auth
$lowCAccessTerm = new Zend_Search_Lucene_Index_Term(0, 'c_access');
$highCAccessTerm = new Zend_Search_Lucene_Index_Term($gid, 'c_access');
$cAccessQuery = new Zend_Search_Lucene_Search_Query_Range($lowCAccessTerm, $highCAccessTerm, true);
// ORed flexicontent cat auth & stock joomla cat auth
$catAuthQuery = new Zend_Search_Lucene_Search_Query_Boolean();
$catAuthQuery->addSubquery($gcQuery);
$catAuthQuery->addSubquery($cAccessQuery);
// flexicontent itm auth
$giQuery = new Zend_Search_Lucene_Search_Query_MultiTerm();
foreach ($gmid as $g) {
$giQuery->addTerm(new Zend_Search_Lucene_Index_Term($g, 'gi_aro'));
}
// stock joomla itm auth
$lowIAccessTerm = new Zend_Search_Lucene_Index_Term(0, 'i_access');
$highIAccessTerm = new Zend_Search_Lucene_Index_Term($gid, 'i_access');
$iAccessQuery = new Zend_Search_Lucene_Search_Query_Range($lowIAccessTerm, $highIAccessTerm, true);
// ORed flexicontent itm auth & stock joomla itm auth
$itmAuthQuery = new Zend_Search_Lucene_Search_Query_Boolean();
$itmAuthQuery->addSubquery($giQuery);
$itmAuthQuery->addSubquery($iAccessQuery);
// ANDed itmAuthQuery & catAuthQuery
$authQuery = new Zend_Search_Lucene_Search_Query_Boolean();
$authQuery->addSubquery($catAuthQuery, true);
$authQuery->addSubquery($itmAuthQuery, true);
}
// composite query
$query = new Zend_Search_Lucene_Search_Query_Boolean();
$query->addSubquery($keywordQuery, true);
// if cat query is set we don't need topcat to restrict result set
if ($catQuery) {
$query->addSubquery($catQuery, true);
} elseif ($topcatQuery) {
$query->addSubquery($topcatQuery, true);
}
if ($authQuery) { $query->addSubquery($authQuery, true); }
// search
$execTime = new JProfiler();
$this->hits = $index->find($query);
echo $execTime->mark('executed');
What about checking only the results not inside the index? Save some sort of key into the index (db primary key, guid, practically anything). Then fetch the results and remove those which the user is not allowed to see.
$allowedArray = $acl->getAllowedIds();
// check happens when echoing the content to prevent double cycling (filtering and echoing in view)
foreach ($result as $item) {
if (in_array($item->keyVaue, $allowedArray)) {
//echo
}
}
Edit: Note it depends on the result of most queries. If there are say <50 result in regular query, then doing it in PHP is OK. But if common query returns like 10,000 results, it might not be a good idea ;)

Indexing Adds/Changes not working using Lucene in Zend Framework

I am pretty new to programming and definitely to Zend/Lucene indexing. From what I can tell, though, my code is correct. I feel like I may be overlooking a step or something trying to upload changes and adds to the database so that they appear in the search on my website. I'm not getting any kind of an error message though. Below is the code from the controller. I guess let me know if you need anything else to help this make sense. Thanks in advance for any direction you can give.
class SearchController extends Zend_Controller_Action
{
public function init()
{
$auth = Zend_Auth::getInstance();
if($auth->hasIdentity()) {
$this->view->identity = $auth->getIdentity();
}
}
public function indexAction()
{
// action body
}
public function buildAction()
{
// create the index
$index = Zend_Search_Lucene::open(APPLICATION_PATH . '/indexes');
$page = $this->_request->getParam('page');
// build product pages
if ($page == 'search') {
$mdl = new Model_Search();
$search = $mdl->fetchAll();
if ($search->count() > 0) {
foreach ($search as $s) {
$doc = new Zend_Search_Lucene_Document();
$doc->addField(Zend_Search_Lucene_Field::unIndexed('id', $s->id));
$doc->addField(Zend_Search_Lucene_Field::text('name', $s->name));
$doc->addField(Zend_Search_Lucene_Field::text('uri', $s->uri));
$doc->addField(Zend_Search_Lucene_Field::text('description', $s->description));
$index->addDocument($doc);
}
}
$index->optimize();
$this->view->indexSize = $index->numDocs();
}
}
public function resultsAction()
{
if($this->_request->isPost()) {
$keywords = $this->_request->getParam('query');
$query = Zend_Search_Lucene_Search_QueryParser::parse($keywords);
$index = Zend_Search_Lucene::open(APPLICATION_PATH . '/indexes');
$hits = $index->find($query);
$this->view->results = $hits;
$this->view->keywords = $keywords;
} else {
$this->view->results = null;
}
}
}
Lucene indexes won't stay in sync with your database automatically, you either need to rebuild the entire index or remove and re-add the relevant documents when they change (you cannot edit an existing document).
public function updateAction()
{
// something made the db change
$hits = $index->find("name: " . $name);
foreach($hits as $hit) {
$index->delete($hit->id)
}
$doc = new Zend_Search_Lucene_Document();
// build your doc
$index->add($doc);
}
Note that lucene documents had their own internal id property, and be careful not to mistake it for an id keyword that you provide.