doctrine 2 how to load doctrine_pager - zend-framework

im trying to use the doctrine pager but its errored:
Fatal error: Class 'Doctrine_Pager' not found
code:
$page = 1;
$results_per_page = 10;
$pager = new Doctrine_Pager(
$query,
$page,
$results_per_page
);
$results = $pager->execute(array(), Doctrine::HYDRATE_ARRAY);
$num_results = $results->getNumResults();
i usually call doctrine EM like this:
$this->_doctrine = Zend_Registry::get('doctrineEm');
$query = $this->_doctrine->createQueryBuilder()
how would i load this doctrine pager?

Its my understanding that the pager from 1.2 has been removed from doctrine2.
However, you can add "doctrine extensions" to the ORM which will give you that functionality.
https://github.com/beberlei/DoctrineExtensions

Related

How to write an extbase Repository-Method for Update in TYPO3?

I have written an update query in TYPO3, Now I need to change it to query-object repository method. How to change the code below?
public function updatePaymentDetails($uid, $txnID, $amt, $stats)
{
$itemUID = $uid;
$transID = $txnID;
$amountPaid = $amt;
$txStatus = $stats;
$tableName = 'tx_paypalpayment_domain_model_transactions AS tpp';
$whereCondition = 'tpp.uid=' . '"' . $itemUID . '"';
$setValues = ['transactionid' => $transID, 'amount' => $amountPaid, 'txnstatus' => $txStatus];
$result = $GLOBALS['TYPO3_DB']->exec_UPDATEquery($tableName, $whereCondition, $setValues);
return $result;
}
I created this much in my own idea (don't know it is correct or not), What should be the remaining portion?
public function paymentUpdate($uid, $txnID, $amt, $stats) {
$query = $this->createQuery();
$query->matching(
$query->logicalAnd(
$query->equals("transactionid", $txnID),
$query->equals("amount", $amt),
$query->equals("txnstatus", $stats)
)
);
/*--- Update Code ---*/
return $query->execute();
}
Is there any way to do that?
The TYPO3/Extbase way is to first fetch your transaction from the persistence layer then apply your changes to the domain object and then update it in your repository.
Something like below in your controller action:
$transaction = $this->transactionRepository->findByIdentifier($itemUid);
$transaction->setTransactionId($transID);
$transaction->setAmount($amountPaid);
$transaction->setStatus($txStatus);
$this->transactionRepository->update($transaction);
If you wants to do a direct update instead of first fetching the record then take a look at the \TYPO3\CMS\Core\Database\Query\QueryBuilder (Only exists in newer versions of TYPO3 - 8.7 and above). In older versions of TYPO3 you could take a look at $GLOBALS['TYPO3_DB']->exec_*.

How to get Filterable Attributes from a category in Magento 2

I have created category "Bag" in Magento 2. having filter attribute:
color
Size
I'm trying to get Filterable Attributes from category "Bag".
I have already done this in Magento 1.9:
Mage::app()->setCurrentStore($store);
$layer = Mage::getModel("catalog/layer");
$category = Mage::getModel("catalog/category")->load($categoryid);
$layer->setCurrentCategory($category);
$attributes = $layer->getFilterableAttributes();
But it does not seem to work for 2.x
I faced the same problem recently.
I documented my investigation here.
I was not able to find framework api to provide filterable attributes for specific category, however I will share workarounds.
Basically all filterable attributes in Magento 2 can be retrived from FilterableAttributeList:
$filterableAttributes = ObjectManager::getInstance()->get(\Magento\Catalog\Model\Layer\Category\FilterableAttributeList::class);
$attributes = $filterableAttributes->getList();
Please use DI instead of ObjectManager::getInstance(). I used it just to have more compact example :)
Retrieving filters involved in layered navigation is a bit more tricky.
$filterableAttributes = ObjectManager::getInstance()->get(\Magento\Catalog\Model\Layer\Category\FilterableAttributeList::class);
$appState = ObjectManager::getInstance()->get(\Magento\Framework\App\State::class);
$layerResolver = ObjectManager::getInstance()->get(\Magento\Catalog\Model\Layer\Resolver::class);
$filterList = ObjectManager::getInstance()->create(
\Magento\Catalog\Model\Layer\FilterList::class,
[
'filterableAttributes' => $filterableAttributes
]
);
$category = 1234;
$appState->setAreaCode('frontend');
$layer = $layerResolver->get();
$layer->setCurrentCategory($category);
$filters = $filterList->getFilters($layer);
However, this is not the final result. To be sure that filters are actual, it is required to check number of items for each filters. (that check is actually performed during core layered navigation rendering)
$finalFilters = [];
foreach ($filters as $filter) {
if ($filter->getItemsCount()) {
$finalFilters[] = $filter;
}
}
Then you can get filter names and values. ie:
$name = $filter->getName();
foreach ($filter->getItems() as $item) {
$value = $item->getValue();
}
Finally, I would like to add alternative solution, that is a bit brutal, thought :)
$categoryId = 1234;
$resource = ObjectManager::getInstance()->get(\Magento\Framework\App\ResourceConnection::class);
$connection = $resource->getConnection();
$select = $connection->select()->from(['ea' => $connection->getTableName('eav_attribute')], 'ea.attribute_id')
->join(['eea' => $connection->getTableName('eav_entity_attribute')], 'ea.attribute_id = eea.attribute_id')
->join(['cea' => $connection->getTableName('catalog_eav_attribute')], 'ea.attribute_id = cea.attribute_id')
->join(['cpe' => $connection->getTableName('catalog_product_entity')], 'eea.attribute_set_id = cpe.attribute_set_id')
->join(['ccp' => $connection->getTableName('catalog_category_product')], 'cpe.entity_id = ccp.product_id')
->where('cea.is_filterable = ?', 1)
->where('ccp.category_id = ?', $categoryId)
->group('ea.attribute_id');
$attributeIds = $connection->fetchCol($select);
Then it is possible to use attribute ids to load collection.
/** #var $collection \Magento\Catalog\Model\ResourceModel\Product\Attribute\Collection */
$collection = $this->collectionFactory->create();
$collection->setItemObjectClass('Magento\Catalog\Model\ResourceModel\Eav\Attribute')
->addStoreLabel($this->storeManager->getStore()->getId());
$collection->addFieldToFilter('attribute_id', ['in' => $attributeIds]);
If you know how to build module then you can take help from 'FiltersProvider.php' from 'module-catalog-graph-ql\Model\Resolver\Layer'.
use Magento\Catalog\Model\Layer\Category\FilterableAttributeList as CategoryFilterableAttributeList;
use Magento\Catalog\Model\Layer\FilterListFactory;
use Magento\Catalog\Model\Layer\Resolver;
use Magento\Framework\UrlInterface;
public function __construct(
Resolver $layerResolver,
FilterListFactory $filterListFactory,
CategoryFilterableAttributeList $categoryFilterableAttributeList,
UrlInterface $urlBuilder
) {
$this->_navigation = $navigation;
$this->layerResolver = $layerResolver;
$this->filterListFactory = $filterListFactory;
$this->urlBuilder = $urlBuilder;
$this->_categoryFilterableAttributeList = $categoryFilterableAttributeList;
}
public function getCatMenu($catid)
{
$fill_arr = [];
$filterList = $this->filterListFactory->create(['filterableAttributes' => $this->_categoryFilterableAttributeList]);
$layer = clone $this->layerResolver->get();
$layer->setCurrentCategory($catid);
$filters = $filterList->getFilters($layer);
return $fill_arr;
}

How to write native query in Doctrine / Postgres equivalent to a normal PDO_PGSQL

I have the following query in php with (pdo_pgsql) adapter:
$dsn = "pgsql:host=$host;port=5432;dbname=$db;user=$username;password=$password";
$conn = new PDO($dsn);
$query = 'SET search_path TO xyz_de;';
$result = $conn->query($query);
$query = 'Select * FROM "Orders" WHERE vendor_id=189 ';
$statement = $conn->query($query);
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
var_dump($row); // --> working perfectly fine, I see results here
}
I want to reproduce it using doctrine so I'm doing the following:
// given: 1) $this->em = EntityManager
// 2) the conenction is established successfull (I debugged it and sure about it)
$rsm = new ResultSetMapping();
$query = $this->em->createNativeQuery("SET search_path TO xyz_de ", $rsm);
$query->execute();
$query = $this->em->createNativeQuery('SELECT * FROM "Orders" WHERE vendor_id=?', $rsm);
$query->setParameter(1, 189);
$orders = $query->getArrayResult();
var_dump($orders); // Gives empty array (no errors)
as per my comment in the last line, the problem is that I get no results and no errors when using doctrine for this
Many things:
You can use addScalarResult
A simple example:
$rsm->addScalarResult('my_real_column', 'my_alias_column');
$query = $this->em->createNativeQuery('SELECT my_real_column FROM "Orders"');
var_dump($query->getScalarResult());
But I think, the best you can do is to use the queryBuilder.

Joomla 3.0 component $params = $app->getParams();

I'm using Joomla 3.0 but at this point I can not use component because of a small problem.
This is the error, all other errors I could easily solve by adding Legacy to the class like this JView became JViewLegacy
However for the error beneath I couldn't find a solution:
Any help would be great!
The error:
Fatal error: Call to a member function getParams() on a non-object in
/var/www/g35003/mywebsite.nl/HTML/administrator/components/
com_taxonomy/taxonomy.php on line 16
The code line 16 is marked.
defined( '_JEXEC' ) or die( 'Restricted access' );
global $mainframe;
$params = $app->getParams(); /** <-- Line 16 */
require_once (JPATH_COMPONENT.DS.'controller.php');
$controller = new TaxonomyController();
$controller->execute(JRequest::getCmd('task'));
$controller->redirect();
global $mainframe; has been deprecated since Joomla 2.5 I believe. To get the parameters, you can use the following code:
$params = JComponentHelper::getParams('com_taxonomy');
$test = $params->get('param_name');
Try this
defined( '_JEXEC' ) or die( 'Restricted access' );
$app = &JFactory::getApplication();
$params = $app->getParams(); /** <-- Line 16 */
require_once (JPATH_COMPONENT.DS.'controller.php');
$controller = new TaxonomyController();
$controller->execute(JRequest::getCmd('task'));
$controller->redirect();
For getting the menu item's params in my view I used the following:
$menu = JFactory::getApplication('site')->getMenu()->getActive();
$this->params = $menu->params;

Integrating Zend Framework 1.11 with MongoDB using Doctrine ODM

Does any know of a way to integrate zend framework with Mongo using Doctrine 2 beta ODM?
I've viewed the zendcast video on integrating with Doctrine 2 ORM for MySQL but Bisna was never updated to support Mongo.
I guess I can try and hack Bisna to get it working but I'd like to know if someone else has already found a way to get it working.
It's pretty easy to write a Zend Bootstrap Resource.
Here is one I use:
<?php
namespace Cob\Application\Resource;
use Doctrine\Common\Annotations\AnnotationReader,
Doctrine\ODM\MongoDB\DocumentManager,
Doctrine\MongoDB\Connection,
Doctrine\ODM\MongoDB\Configuration,
Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver,
Doctrine\Common\EventManager;
/**
* Creates a MongoDB connection and DocumentManager instance
*
* #author Andrew Cobby <cobby#cobbweb.me>
*/
class Mongo extends \Zend_Application_Resource_ResourceAbstract
{
/**
* #return \Doctrine\ODM\MongoDB\DocumentManager
*/
public function init()
{
$options = $this->getOptions() + array(
'defaultDB' => 'my_database',
'proxyDir' => APPLICATION_PATH . '/domain/Proxies',
'proxyNamespace' => 'Application\Proxies',
'hydratorDir' => APPLICATION_PATH . '/domain/Hydrators',
'hydratorNamespace' => 'Application\Hydrators'
);
$config = new Configuration();
$config->setProxyDir($options['proxyDir']);
$config->setProxyNamespace($options['proxyNamespace']);
$config->setHydratorDir($options['hydratorDir']);
$config->setHydratorNamespace($options['hydratorNamespace']);
$config->setDefaultDB($options['defaultDB']);
$reader = new AnnotationReader();
$reader->setDefaultAnnotationNamespace('Doctrine\ODM\MongoDB\Mapping\\');
$config->setMetadataDriverImpl(new AnnotationDriver($reader, $this->getDocumentPaths()));
$evm = new EventManager();
$evm->addEventSubscriber(new SlugSubscriber());
return DocumentManager::create(new Connection(), $config, $evm);
}
public function getDocumentPaths()
{
$paths = array();
foreach(new \DirectoryIterator(APPLICATION_PATH . '/modules') as $module){
$path = $module->getPathname() . '/src/Domain/Document';
if((!$module->isDir() || $module->isDot()) || !is_dir($path)){
continue;
}
$paths[] = $path;
}
if(!count($paths)){
throw new \Exception("No document paths found");
}
return $paths;
}
}
Though you'll have to update the getDocumentPaths() method to suit your application directory structure.
I wrote my own very simple application resource plugin and container, using Guilherme's integration suite for inspiration.
I'm sure this could be much more featured in terms of capturing options but I figured I'll add those in as I need them.
See https://gist.github.com/891415