I'm trying to prepare a module.
I need the module_id value.
I will draw data with the module_id value.
How do I get module_id in the controller on the front side.
you should create model file with some name mymodule.php where you should place something like this:
public function getModules() {
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "module` ORDER BY `code`");
return $query->rows;
}
you will get all modules data.
or can get just only one by module code:
public function getModulesByCode($code) {
$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "module` WHERE `code` = '" . $this->db->escape($code) . "' ORDER BY `name`");
return $query->rows;
}
Then in your controller with corresponding name mymodule.php file you can call it:
$modules = $this->model_extension_module->getModulesByCode($code);
or
$modules = $this->model_extension_module->getModules();
Your suggestion may apply to single module.
My module has sub-modules.
But I found the solution.
Design layout have solved the work with files.
catalog / controller / common / common_left.php
catalog / controller / common / common_right.php
catalog / controller / common / head_top.php
catalog / controller / common / head_bottom.php
etc.
I added a starred code.
if (isset($part[1])) {
$setting_info = $this->model_setting_module->getModule($part[1]);
if ($setting_info && $setting_info['status']) {
***** $setting_info["module_id"] = $part[1]; *****
$output = $this->load->controller('extension/module/' . $part[0], $setting_info);
if ($output) {
$data['modules'][] = $output;
}
}
}
Related
I created a TYPO3 extension which allows to select several images. I activated metadata via the filemetadata extension. When I browse the image files in a fluid template loop, I try to display the metadata. This works {file.properties.uid}
{file.properties.categories}, but for the categories I get a number. Now I would like to have the category selected.
I used this:
https://coding.musikinsnetz.de/typo3/fluid-viewhelpers/access-system-categories-in-content-elements-templates
<f: if condition = "{files}">
<f: for each = "{files}" as = "file">
<f: for each = "{bg2yg: CategoriesOutput (recUid: data.uid)}" as = "category">
<b style = 'color: blue'> <span class = "{category.title}"> CATEGORY: {category.title} </span> </b> <br />
</ f: for>
</ f: for>
</ f: if>
This displays the main category because 'data.uid': {bg2yg: CategoriesOutput (recUid: data.uid)}
However, I want the categories of images, I tested this:
<f: for each = "{bg2yg: CategoriesOutput (recUid: file.properties.uid)}" as = "category">
Without success ! Do you have an idea ?
Best regards,
Bruno
thank you for your respective help. Here I coded this:
<?php
/**
* This file is part of the "hexagonalgallery" Extension for TYPO3 CMS.
*
* For the full copyright and license information, please read the
* LICENSE file that was distributed with this source code.
*/
namespace BG2YG\Hexagonalgallery\ViewHelpers;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
/**
* will return certain system categories (sys_category) data of an element
* either as an array or as a string with certain parameters
*
* EXAMPLES:
*
* EMBEDDING IN TEMPLATE: {namespace my = YourVendor\YourExtension\ViewHelpers}
*
* call an array with all category data to be used in a loop, e.g. for an HTML tag for each files:
* <f:if condition="{file}">
* <f:for each="{my:FileCategoriesOutput(recUid: data.uid)}" as="category">
* <span class="{category.title}">{category.title}</span>
* </f:for>
* </f:if>
*
* call a “data-categories” attribute with the slug field of the categories, comma-separated (default):
* {my:FileCategoriesOutput(recUid: file.properties.uid, tableName: 'sys_file_metadata', fieldString: 'title', htmlAttr: 'data-categories')}
* output: ' data-categories="catx,caty"'
*
* call all categories as CSS classes (space as string separator, prefix 'cat-' for each files)
* {my:FileCategoriesOutput(recUid: file.properties.uid, tableName: 'sys_file_metadata', fieldString: 'title', stringSeparator: ' ', catPrefix: 'cat-')}
* output: 'cat-catx cat-caty'
*/
class FileCategoriesOutputViewHelper extends AbstractViewHelper
{
protected $escapeOutput = false;
public function initializeArguments()
{
$this->registerArgument('recUid', 'integer', 'record UID, e.g. of a content element', true);
$this->registerArgument('tableName', 'string', 'optional: table of records you want the categories returned for (default: tt_content)', false, 'tt_content');
$this->registerArgument('fieldString', 'string', 'optional: name of sys_categories table field – if given, the return value will be a string', false, null);
$this->registerArgument('stringSeparator', 'string', 'optional: separator for string', false, ',');
$this->registerArgument('htmlAttr', 'string', 'optional: wrap in attribute for HTML tag (in case of fieldString given)', false, null);
$this->registerArgument('catPrefix', 'string', 'optional: prefix for each category (e.g. for CSS classes)', false, null);
}
/**
* #return mixed
*/
public function render()
{
$recUid = $this->arguments['recUid'];
$tableName = $this->arguments['tableName'];
$fieldString = $this->arguments['fieldString'];
$stringSeparator = $this->arguments['stringSeparator'];
$htmlAttr = $this->arguments['htmlAttr'];
$catPrefix = $this->arguments['catPrefix'];
define(DEBUG,false);
/*
SELECT uid_local FROM sys_file_reference WHERE uid = 152
*/
if (DEBUG)
echo "<b style='color:blue;'>\$recUid=".$recUid."</b><br />";
/**
* default query for sys_file_reference table
* SQL : SELECT uid_local FROM sys_file_reference WHERE uid = $recUid
*/
$queryBuilder0 = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_file_reference');
$queryBuilder0->select('uid_local');
$queryBuilder0->from('sys_file_reference');
$queryBuilder0->where(
$queryBuilder0->expr()->eq('sys_file_reference.uid', $queryBuilder0->createNamedParameter($recUid, \PDO::PARAM_INT)));
$result_uid = $queryBuilder0->execute();
$uid=$result_uid->fetch();
$uid=$uid['uid_local'];
if (DEBUG)
echo "<b style='color:blue;'>\$uid=".print_r($uid)."</b><br />";
/**
* default query for sys_category table
*/
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_category');
/**
* select the fields that will be returned, use asterisk for all
*/
$queryBuilder->select('sys_category.uid', 'sys_category.title', 'sys_category_record_mm.uid_foreign', 'sys_category_record_mm.tablenames');
$queryBuilder->from('sys_category');
$queryBuilder->join(
'sys_category',
'sys_category_record_mm',
'sys_category_record_mm',
$queryBuilder->expr()->eq('sys_category_record_mm.uid_local', $queryBuilder->quoteIdentifier('sys_category.uid'))
);
$queryBuilder->where(
$queryBuilder->expr()->eq('sys_category_record_mm.uid_foreign', $queryBuilder->createNamedParameter($uid, \PDO::PARAM_INT)),
$queryBuilder->expr()->like('sys_category_record_mm.tablenames', $queryBuilder->createNamedParameter($tableName))
);
$result = $queryBuilder->execute();
$res = [];
$returnString = '';
$i = 1;
while ($row = $result->fetch()) {
$res[] = $row;
if ($fieldString !== null) {
if (isset($row[$fieldString])) {
$returnString .= ($i === 1) ? '' : $stringSeparator;
$returnString .= ($catPrefix !== null) ? $catPrefix : '';
$returnString .= $row[$fieldString];
}
}
$i++;
}
if (DEBUG) {
echo "\$returnString=" . $returnString . "<br />";
echo "\$res=<b style='color:red;'>" . print_r($res) . "</b><br />";
}
if ($returnString !== '') {
return ($htmlAttr !== null)
? ' ' . $htmlAttr . '="' . $returnString . '"'
: $returnString;
} elseif ($fieldString !== null) {
return '';
} else {
return $res;
}
}
}
And it works. Thank you for indicating to me if this code seems to you written in the rules of art.
Best regards,
Bruno
It looks like categories are not handled in the model, so the fastest thing you can do is to create your own ViewHelper for fetching them as suggested in answer to a similar question, my fast test for TYPO3 9.5
IMPORTANT! for ver.: 10+ check annotation changes at the bottom of this post.
<?php
namespace VENDOR\Toolbox\ViewHelpers;
use TYPO3\CMS\Core\Resource\FileReference;
use TYPO3\CMS\Extbase\Persistence\Generic\QueryResult;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
/**
*
* #package TYPO3
* #subpackage toolbox
* #license http://www.gnu.org/licenses/gpl.html GNU General Public License, version 2 or later
* #author Marcus Biesioroff biesior#gmail.com>
*
* Sample ViewHelper for listing file's categories
*
* Usage:
* {namespace toolbox=VENDOR\Toolbox\ViewHelpers}
* or in ext_tables.php:
* $GLOBALS['TYPO3_CONF_VARS']['SYS']['fluid']['namespaces']['toolbox'] = ['VENDOR\Toolbox\ViewHelpers'];
*
* <toolbox:fileCategories file="{file}" />
* or
* {toolbox:fileCategories(file: file)}
*/
class FileCategoriesViewHelper extends AbstractViewHelper
{
/**
* #var \TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository
* #inject
*/
protected $categoryRepository;
public function initializeArguments()
{
parent::initializeArguments();
$this->registerArgument('file', 'mixed', 'File');
}
public function render()
{
/** #var FileReference $fileRef */
$fileRef = $this->arguments['file'];
$file = $fileRef->getOriginalFile();
$uid = $file->getUid();
/** #var QueryResult $res */
$res = $this->getCategories($uid);
return $res->toArray();
}
private function getCategories($uid)
{
$query = $this->categoryRepository->createQuery();
$sql = "SELECT sys_category.* FROM sys_category
INNER JOIN sys_category_record_mm ON sys_category_record_mm.uid_local = sys_category.uid AND sys_category_record_mm.fieldname = 'categories' AND sys_category_record_mm.tablenames = 'sys_file_metadata'
INNER JOIN sys_file_metadata ON sys_category_record_mm.uid_foreign = sys_file_metadata.uid
WHERE sys_file_metadata.file = '" . (int)$uid . "'
AND sys_category.deleted = 0
ORDER BY sys_category_record_mm.sorting_foreign ASC";
return $query->statement($sql)->execute();
}
}
So you can use it within your Fluid template like:
<h3>File categories:</h3>
<ul>
<f:for each="{toolbox:fileCategories(file: file)}" as="file_cat">
<li>{file_cat.title}</li>
</f:for>
</ul>
Don't forget to use your own vendor and subpackage key.
Of course, after injecting anything don't forget to flush your caches, sometimes maaaany times.
Important info for ver.: 10.* +
According to this article #inject annotation is depreciated in ver. 9.x and removed in ver." 10.x You should use #TYPO3\CMS\Extbase\Annotation\Inject instead.
So proper injection of the categoryRepository in TYPO3 10.x and newer should look like:
/**
* #var \TYPO3\CMS\Extbase\Domain\Repository\CategoryRepository
* #TYPO3\CMS\Extbase\Annotation\Inject
*/
protected $categoryRepository;
You can also search for deprecated annotations within your ext via Upgrade module > Scan Extension Files
I am refactoring a code base, because this is a legacy code with a lot of raw sql, and the whole thing is spaghetti code.
I am sadly facing that doctrine has no REPLACE INTO functionality, I know the reasons why.
I found some workaround, like merge but that is deprecated.
I spend a lot of hours to learn doctrine, because it is widely used ORM, and a lot of hours while I built the entities.
Is there any "legal" solution to achieve this REPLACE INTO?
You can handle duplicates by catching UniqueConstraintViolationException.
$entity = new PossibleDuplicatedEntity();
try {
$em->persist($entity);
$em->flush();
}
catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
// handle duplicated values
}
But beware – Doctrine uses implicit transaction. When exception is thrown, transaction is rolled-back and EntityManager is closed (entities are detached). See documentation.
Better would be handling cause of duplication occurring. I.e. if it's because of concurrency, try to use table locking etc.
If you just want to 'upsert' rows into the database and you don't care about change tracking you could use the piece of code below. It's probably more performant than relying on UniqueConstraintViolationException's.
I use it for batch-uploading rows into a table.
/**
* #throws Exception
*/
public static function replaceInto(EntityManagerInterface $em, iterable $entities): void
{
$i = 0;
$values = [];
$metadata = $fieldNames = $sql = null;
foreach ($entities as $entity) {
if (!isset($metadata)) {
$metadata = $em->getClassMetadata(get_class($entity));
$fieldNames = $metadata->getFieldNames();
$tableName = $metadata->getTableName();
$sql = "REPLACE INTO `$tableName` VALUES ";
}
$params = [];
foreach ($fieldNames as $fieldName) {
$paramName = ':' . $metadata->getColumnName($fieldName) . '_' . $i;
$params[] = $paramName;
$values[] = [$paramName, $metadata->getFieldValue($entity, $fieldName), $metadata->getTypeOfField($fieldName)];
}
if ($i > 0) {
$sql .= ",";
}
$sql .= "\n(" . join(', ', $params) . ")";
$i++;
}
$stmt = $em->getConnection()->prepare($sql);
foreach ($values as $value) {
$stmt->bindValue(...$value);
}
$stmt->executeQuery();
}
I use wamp 2.5
I successfully included the phalcon extension by copying the dll file into the ext folder of the wamp php folder , and editing the php.ini file by including extension=php_phalcon.dll. I created a simple project. But when I wanted to open the project on the browser then it shows the list of folders but not the desired page ! Here is the captured photo of the result :
So how to fix it ?
edit :
here is code of the index.php in the public folder :
<?php
use Phalcon\Loader;
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Session\Adapter\Files as SessionFiles;
include("../app/config_const.php");
include("../app/config_inc.php");
include("../app/lib/PSR.php");
require_once RP_BIRT . 'runReport.php';
try {
// Register an autoloader
$loader = new Loader();
$loader->registerDirs(array(
'../app/controllers/',
'../app/models/'
))->register();
// Create a DI
$di = new FactoryDefault();
// Start the session the first time when some component request the session service
$di->setShared('session', function () {
$session = new SessionFiles();
$session->start();
return $session;
});
// Setup the database service
$di->set('db', function(){
$cnx = new DbAdapter(array(
"host" => SERVEUR,
"username" => LOGIN_DB,
"password" => PWS_DB,
"dbname" => BDD
));
return $cnx;
});
// Setup the view component
$di->set('view', function(){
$view = new View();
$view->setViewsDir('../app/views/');
$view->registerEngines(array(
".phtml" => 'Phalcon\Mvc\View\Engine\Volt'
));
return $view;
});
// Setup a base URI so that all generated URIs include the "phalcon" folder
$di->set('url', function(){
$url = new UrlProvider();
$url->setBaseUri('/'.SITE.'/');
return $url;
});
//Register the flash service with custom CSS classes
$di->set('flash', function(){
$flash = new \Phalcon\Flash\Direct(array(
'error' => 'alert alert-error',
'success' => 'alert alert-success',
'notice' => 'alert alert-info',
));
return $flash;
});
//Handle the request
$app = new Application($di);
echo $app->handle()->getContent();
} catch(\Exception $e) {
echo "Exception: ", $e->getMessage();
}
?>
code of ../app/config_const.php :
<?php
define("BDD","resto_vide");
define("SITE", "resto");
define('HTTP_MAIN', 'http://'. $_SERVER["HTTP_HOST"] .'/'.SITE.'/') ;
define('RP_LANG', HTTP_MAIN . 'lang/');
define('RP_SSP', HTTP_MAIN . 'ssp/');
define("SERVEUR",$_SERVER["HTTP_HOST"]);
define("LOGIN_DB","root");
define("PWS_DB","admin");
define("BDD_PORT" ,3306);
define('HTTP_CSS', HTTP_MAIN . "css/");
define('HTTP_JS', HTTP_MAIN . "javascript/");
define('HTTP_IMG', HTTP_MAIN . "images/");
define('HTTP_IMG_LOGO', HTTP_IMG . "logo/");
define('HTTP_IMG_ART', HTTP_IMG . "articles/");
define('HTTP_IMG_TMP', HTTP_IMG . "tmp/");
define('HTTP_IMG_MODE_REGLEMENT', HTTP_IMG . "mode_reglement/");
define('HTTP_IMG_BILLETAGE', HTTP_IMG . "billetage/");
define('HTTP_IMG_CHAMBRE', HTTP_IMG . "chambre/");
define('HTTP_IMG_SALLE', HTTP_IMG . "salle/");
define('HTTP_IMG_TABLE_CLIENT', HTTP_IMG . "table_client/");
define('RP_MAIN', substr($_SERVER["DOCUMENT_ROOT"],-1) == '/' ? $_SERVER["DOCUMENT_ROOT"] . SITE.'/' : $_SERVER["DOCUMENT_ROOT"].'/' . SITE.'/');
define('RP_IMG', RP_MAIN . 'public/images/');
define('RP_IMG_LOGO', RP_IMG . 'logo/');
define('RP_IMG_ART', RP_IMG . 'articles/');
define('RP_IMG_TMP', RP_IMG . 'tmp/');
define('RP_IMG_BILLETAGE', RP_IMG . "billetage/");
define('RP_IMG_CHAMBRE', RP_IMG . "chambre/");
define('RP_IMG_SALLE', RP_IMG . "salle/");
define('RP_IMG_TABLE_CLIENT', RP_IMG . "table_client/");
define('RP_LIB', RP_MAIN . 'app/lib/');
define('CODE_LANG','sess_code_lang');
define('DEFAULT_LANG', '/fr/');
define('RP_RESSOURCES', RP_MAIN . 'app/ressources/');
define('RP_BIRT' , RP_LIB . 'birt/');
define('RP_REPORT' , RP_MAIN . "public/report/");
// SQL server connection information
$sql_details = array(
'user' => LOGIN_DB,
'pass' => PWS_DB,
'db' => BDD,
'host' => SERVEUR
);
?>
code of ../app/config_inc.php :
<?php
require_once RP_LIB . 'ressources.lib.php';
require_once RP_LIB . 'pagination.lib.php';
require_once RP_LIB . 'debug.php';
require_once RP_LIB . 'datetime.lib.php';
require_once RP_LIB . 'mysql.lib.php';
require_once RP_LIB . 'string.lib.php';
require_once RP_LIB . 'numberFormat.lib.php';
require_once RP_LIB . 'file.lib.php';
#ini_alter('error_log', RP_MAIN . 'log/error.log');
#ini_alter('default_charset', 'iso-8859-1');
loadRessource('main') ;
loadRessource('global') ;
?>
code of ../app/lib/PSR.php :
<?php
/*
+------------------------------------------------------------------------+
| Phalcon Framework |
+------------------------------------------------------------------------+
| Copyright (c) 2011-2015 Phalcon Team (http://www.phalconphp.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file docs/LICENSE.txt. |
| |
| If you did not receive a copy of the license and are unable to |
| obtain it through the world-wide-web, please send an email |
| to license#phalconphp.com so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Piyush Rajesh <mba.piyushgupta#gmail.com> |
| Serghei Iakovlev <sadhooklay#gmail.com> |
+------------------------------------------------------------------------+
*/
namespace Phalcon\Loader;
use Phalcon\Loader;
/**
* Phalcon\Loader\PSR.
* Implements PSR-0 autoloader for your apps.
*
* #package Phalcon\Loader
*/
class PSR extends Loader
{
/**
* Namespace separator
* #var string
*/
protected $namespaceSeparator = '\\';
/**
* Loads the given class or interface.
*
* #param string $className The name of the class to load.
*
* #return bool
*/
public function autoLoad($className)
{
// Reduce slashes
$className = ltrim($className, $this->namespaceSeparator);
$array = explode($this->namespaceSeparator, $className);
if (array_key_exists($array[0], $this->_namespaces)) {
$array[0] = $this->_namespaces[$array[0]];
$class = array_pop($array);
array_push($array, str_replace("_", DIRECTORY_SEPARATOR, $class));
$file = implode($array, DIRECTORY_SEPARATOR);
foreach ($this->_extensions as $ext) {
if (file_exists($file . ".$ext")) {
require $file . ".$ext";
return true;
}
}
}
// If it did not fit standard PSR-0, pass it on to the original Phalcon autoloader
return parent::autoLoad($className);
}
}
The folder you are pointing to doesn't contain an index.php so apache doesn't know to look in your /public/ folder for your index.php. You'd either need to visit http://localhost/resto/public/ to see your site, add an index.php to the base directory (that maybe just includes the one in public) or what is probably best is to create a virtual host that points to your public folder (this does what it would need to in production and makes your business code not directly accessible).
Info on setting up vhosts in WAMP https://john-dugan.com/wamp-vhost-setup/
Phalcon documention for what a vhost should look like https://docs.phalconphp.com/en/3.3/webserver-setup#apache
Is there any php code to change store? So for example if php detects the language is Spanish I would like it to change the whole store to other store.
So it can be used for example anytime when language is changed - then the store is changed also.
So for example if anyone is viewing the store1 in English and change language to Spanish then automatically the store1 is also changed to store2 toghether with the language. Any idea?
If you open file: index.php or startup.php (based on the OpenCart version you use) you will see that there is a code that checks the url of which the user has visited and then searches the database to see if it's default store (store_id = 0) or other store. If it's the default store, then nothing changes. If it's not though, then session variable (store_id) is changed to the specified store_id and the whole opencart will operate based on this store_id.
OpenCart 1.5.x index.php
// Store
if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {
$store_query = $db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`ssl`, 'www.', '') = '" . $db->escape('https://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
} else {
$store_query = $db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`url`, 'www.', '') = '" . $db->escape('http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
}
if ($store_query->num_rows) {
$config->set('config_store_id', $store_query->row['store_id']);
} else {
$config->set('config_store_id', 0);
}
OpenCart 2.x / 3.x - catalog/controller/startup/startup.php
// Store
if ($this->request->server['HTTPS']) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`ssl`, 'www.', '') = '" . $this->db->escape('https://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
} else {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "store WHERE REPLACE(`url`, 'www.', '') = '" . $this->db->escape('http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/') . "'");
}
if (isset($this->request->get['store_id'])) {
$this->config->set('config_store_id', (int)$this->request->get['store_id']);
} else if ($query->num_rows) {
$this->config->set('config_store_id', $query->row['store_id']);
} else {
$this->config->set('config_store_id', 0);
}
So, you can extend this code and you will check the browser's language and based on every language you will change the store_id to the one you need.
A sample code is the following, it's not the ideal, but it will give you the idea on how to implement it by yourself.
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
case "fr":
$this->config->set('config_store_id', 1);
break;
case "it":
$this->config->set('config_store_id', 2);
break;
case "en":
$this->config->set('config_store_id', 3);
break;
case "el":
$this->config->set('config_store_id', 4);
break;
default:
//else default store
$this->config->set('config_store_id', 0);
break;
}
Hope the above answer will help you. It's easy, but you need to understand how OpenCart works. Also, just my advice..."Don't wait for ready-made extensions, try to make yours." ;)
Cheers!
My Select function of my QueryManager:
/**
* Führt eine SELECT - Query durch
*
* #param $select = array( array(column, [...]), table, shortcut )
* $orderby = array(column, sorting-type)
* $where = array( array( column, value, type[or, and] ), [...] )
* $innerjoin = array( table, shortcut, condition )
* $pagination = array( page, limit )
*
* #return array $data
*/
public function select($select,$orderby, $where, $innerjoin, $pagination)
{
$qb = $this->conn->createQueryBuilder()
->select($select[0])
->from($select[1], $select[2])
;
if ($orderby) {
$qb->orderBy($orderby);
}
if ($where) {
foreach($where as $cond) {
$x = 0;
if ( key($cond) == 0 ) {
$qb
->where($cond[0] . ' = ?')
->setParameter($x,$cond[1]);
}
elseif ( $cond[2] == 'and' ) {
$qb
->andWhere($cond[0] . ' = ?')
->setParameter($x,$cond[1]);
}
elseif ( $cond[2] == 'and' ) {
$qb
->orWhere($cond[0] . ' = :' . $x)
->setParameter($x,$cond[1]);
}
$x++;
}
}
if ($innerjoin) {
$qb->join($select[2],$innerjoin);
}
$this->sql = $qb->getSQL();
$this->totalRowCount = count( $qb->execute() ) ;
if ($pagination) {
$max = $pagination[0] * $pagination[1];
$first = $max - $limit;
$qb
->setFirstResult($first)
->setMaxResults($max)
;
}
$stmt = $qb->execute();
return $stmt->fetchAll();
}
I don't know why, but in action, this function produces a select query without inserted values for the parameters:
/**
* Lädt einen User nach dessen Username
*
* #param $username
* #return User $user | null
*/
public function getUser($username)
{
if($data = $this->select(array('*','users','u'), null, array( array('username',$username) ), null,null)) {
return $user = $this->hydrate($data);
}
return null;
}
I didn't get a result, and the query is not setup correctly:
array(0) { }
SELECT * FROM users u WHERE username = ?
In my opinion the Builder doesn't supstitute my parameters with the provided values ...
I got the latest version of Doctrine DBAL (2.4) and this version should support this features!
Thanks for Help and Suggestions :)
I also had this Problem. I have readed here doctrine 2 querybuilder with set parameters not working that:
You cant bind parameters to QueryBuilder, only to Query
But im creating SQL conditions as collected AND & OR experssions in deep nested objects, and the toppest object creates the query object. So i cant create the query object before, i always return expression objects.
So i solved the problem with direct including the variable into the prepared variable's position.
$qb->where($cond[0] . '=' . $cond[1]);
And because i expect strings there i added hard coded quotes. This is not the desired way, but at the moment i dont know how to solve that in an other way with binding parameters to the QueryBuilder object.
$expr = $d_qb->expr()->between($t_c, "'" . $date_from . "'", "'" . $date_from . "'");
Other suggestions?
Following codes results:
$expr = $d_qb->expr()->between($t_c, ':from', ':to');
$d_qb->setParameter('from', 1);
$d_qb->setParameter('to', 1);
or
$expr = $d_qb->expr()->between($t_c, ':from', ':to');
$d_qb->setParameter(':from', 1);
$d_qb->setParameter(':to', 1);
Results:
e0_.created BETWEEN ? AND ?