I'm creating a registration form and want to check to see if an email is not already associated with an account. All the ways I can see will create the entire User entity, but I just need to know if it exists.
public function isUnusedEmail($email) {
$em = static::$pimple['em'];
$dql = 'SELECT 1 FROM App\Model\User user WHERE user.email = :email';
$query = $em->createQuery($dql);
$query->setParameter('email', $email);
$res = $query->getResult();
return empty($res);
}
Consider the following method:
/**
* #param string $token
* #return bool
*/
public function isTokenUnique($token)
{
$manager = $this->getEntityManager();
/** #var Doctrine\ORM\Query $query */
$query = $manager->
createQuery('SELECT 1 FROM AppBundle:Member m WHERE m.token = :token')
->setParameter('token', $token)
->setMaxResults(1)
;
return (count($query->getResult()) == 0);
}
Notice a call to setMaxResults(). It can be important in some cases.
Related
I am using FOSElasticaBundle and Symfony. I have a method to return some results merged from two types of objects:
public function getMergedResults($query)
{
//See https://github.com/FriendsOfSymfony/FOSElasticaBundle/blob/master/doc/cookbook/multi-type-search.md
$indexManager = $this->get('fos_elastica.index_manager');
$transformer = $this->get('app.elastica_to_model.transformer.snapshot');
/* #var \Elastica\Search $search */
$search = $indexManager->getIndex('app')->createSearch();
$search->addType('snapshot');
$search->addType('traffic_company');
$search->setQuery($query);
$resultSet = $search->search();
$transformer = $this->get('fos_elastica.elastica_to_model_transformer.collection.app');
$resultSet = $transformer->transform($resultSet->getResults());
return $resultSet;
}
... which works well. Now I want to add a filter that was left to me by a previous developer:
protected function addSiteFilter(Query\BoolQuery $boolFilter, SiteInterface $site = null)
{
if ($site) {
$termFilter = new Query\Term(array('site' => array('value' => $site->getId())));
$boolFilter->addMust(array(
$termFilter
));
}
}
... but I'm not sure how to glue these two pieces together. What code can I add to the first function so that it integrates the second one?
I'll provide an example, If it wouldn't be so clear for you, ping me.
/**
* #param string $ownerId
* #return Query
*/
public function getByOwnerId(string $ownerId): Query
{
$terms = new Terms('ownerId', [$ownerId]);
$boolQuery = (new BoolQuery())->addMust($terms);
return (new Query())->setQuery($boolQuery);
}
I want to change a constant in my Extension in the Controller via initializeAction.
It works the half way. Let me explain this:
TYPO3 Version 8.7.7 Extension build with Extension Builder.
If i use the following code in my UserController.php
/**
* initialize the controller
*
* #return void
*/
protected function initializeAction()
{
...
$this->settings['groupDefaultId'] = (string)$newUserGroup[$key]->getUid();
...
}
and i'll debug it after that in php i got the following Debuginformation:
settings
array(12 items)
groupDefaultId => '53' (2 chars)
This is the correct value in PHP for now. But if i check that value in the Backend under Template > Constant Editor the value isn't stored any more.
I tried the code above and the setConfiguration API function.
When i got the new ID, which one i want to set in constants i start the function with the following command:
File: BaseController.php
(my UserController extends BaseController, for splitting CRUD-function from Other-functions).
I give a string to it, because at the end of this "way" all Settings are stored as string in $this->settings.
// Set current Group Uid as defaultGroupId in Constants
$currentGroupIdHasSetInConstants = $this->setNewGroupIdInConstants((string)$newUserGroup[$key]->getUid());
We jumpt to the setNewGroupIdInConstants function:
File: BaseController.php
/**
* Sets the Constant 'defaultGroupId' with new Value
*
* Incoming Requirement for this function: defaultGroupId = 0 this means
* defaultGroupId is not set in Constants
*
* #param string $newdefaultGroupId New Default Group ID for New Users
* #return bool TRUE defaultGroupId has changed | FALSE no changes done
*/
public function setNewGroupIdInConstants(string $newdefaultGroupId)
{
// Rebuild constants with new property and value
$newConstantsValue = $this->addConstantsConfigurationForDefaultGroupId($newdefaultGroupId);
// Add the new property with value to constants
return $this->userRepository->updateConstants($newConstantsValue);
}
First this function jumps to addConstantsConfigurationForDefaultGroupId function:
In File: BaseController.php
/**
* Build new constants value for defaultGroupId
*
* #param string $value The new value for defaultGroupId
* #return string The complete Constants value
* including the defaultGroupId Configuration
*/
public function addConstantsConfigurationForDefaultGroupId($value)
{
$getConstants = $this->userRepository->fetchConstants()['constants'];
// This Value has to look like this with the new line (for getting original code incl. \n for constants)
$buildAdditionalConstant = '
plugin.tx_rmregistration.settings.defaultGroupId = '.$value;
return $getConstants.$buildAdditionalConstant;
}
fetchConstants function:
In File: UserRepository.php
(Usually it belongs to a SysTemplatesRepository.php, but those one doesn't exist. "Hello Core Team, we need a SysTemplatesRepository ;)".
/**
* Find Constants via sys_template Database Table
*
* #return array|NULL Result is array('constants' => queryResult) or NULL
*/
public function fetchConstants()
{ //
// Query Builder for Table: sys_template
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
// Get Constants of Row, where RM Registration is included
$query = $queryBuilder
->select('constants')
->from('sys_template')
->where(
$queryBuilder->expr()->like(
'include_static_file',
$queryBuilder->createNamedParameter('%' . $queryBuilder->escapeLikeWildcards('EXT:rmregistration/Configuration/TypoScript') . '%')
)
);
// Execute Query and Return the Query-Fetch
$query = $queryBuilder->execute();
return $query->fetch();
}
Here is my code of the updateConstants function
In File: UserRepository.php
/**
* Update Constants via sys_template Database Table ( Updates $this->settings )
*
* #param string $constants The new settings, that has to be stored in $this->settings
*/
public function updateConstants(string $constants)
{
// Query Builder for Table: sys_template
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
$query = $queryBuilder
->update('sys_template')
->where(
$queryBuilder->expr()->like(
'include_static_file',
$queryBuilder->createNamedParameter('%' . $queryBuilder->escapeLikeWildcards('EXT:rmregistration/Configuration/TypoScript') . '%')
)
)
->set('constants', $constants);
$query = $queryBuilder->execute();
return ($query > 0) ? TRUE : FALSE;
}
I'm building the admin for a Magento2 store (currently on 2.1.7, they want to use the newest version until we go live and then want to stabilize a particular version). The module in question is supposed to display all existing orders, with an actionsColumn that contains links to cancel, edit, and open a detailed overview of the purchased items associated with that order. The order detail page contains a grid view that should display all order items associated with an order number passed in the URL.
In order to filter out Order Items that don't relate to the specific Order Number, I've extended the \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult class. This works except for one weird caveat. If, in the addFieldToFilter call, I replace $ordNum with, say, '10000', it grabs the correct data. When using $ordNum to call this dynamically, however, it returns no rows at all. This despite trying all sorts of casting and === checks to ensure that there's no difference between the hardcoded and dynamic values. Is this a Magento bug? I can't at all figure out why this would be the case.
<?php
class OrderItems extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
{
protected function _initSelect()
{
$this->filterByOrderNum();
parent::_initSelect();
return $this;
}
private function filterByOrderNum()
{
$request = \Magento\Framework\App\ObjectManager::getInstance()
->get('Magento\Framework\App\Request\Http');
$ordNum = $request->getParam('order_num');
$this->addFieldToFilter('order_num', ['eq' => $ordNum]); //if I switch this to hardcoded 10000, this works. With the variable, no dice.
return $this;
}
}
I just fixed it by using mentioned below steps
Store param value in session in controller
public function execute() {
$this->_catalogSession->setTokenId($this->request->getParam('entity_id'));
$this->_view->loadLayout();
$this->_view->loadLayoutUpdates();
$this->_view->getPage()->getConfig()->getTitle()->set(__('Redeem Token History'));
$this->_view->renderLayout();
}
Use session value in dataprovider
$tokensCollection->addFieldToFilter('token_id', ['eq' => $this->_catalogSession->getTokenId()]);
Enjoy :)
Try this in place of the getParam statement:
$url = parse_url($request);
$path = explode('/',$url['path']);
$ordNum = $path[3];
Just to make sure we are on the same page, this is the full code:
<?php
class OrderItems extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
{
protected function _initSelect()
{
$this->filterByOrderNum();
parent::_initSelect();
return $this;
}
private function filterByOrderNum()
{
$request = \Magento\Framework\App\ObjectManager::getInstance()
->get('Magento\Framework\App\Request\Http');
$url = parse_url($request);
$path = explode('/',$url['path']);
$ordNum = $path[3];
$this->addFieldToFilter('order_num', $ordNum); //if I switch this to hardcoded 10000, this works. With the variable, no dice.
return $this;
}
}
We have solved this issue by doing the following :
/**
* CcCustompriceProductListingDataProvider constructor.
* #param string $name
* #param string $primaryFieldName
* #param string $requestFieldName
* #param \Magento\Framework\Api\Search\ReportingInterface $reporting
* #param \Magento\Framework\Api\Search\SearchCriteriaBuilder $searchCriteriaBuilder
* #param \Magento\Framework\App\RequestInterface $request
* #param \Magento\Framework\Api\FilterBuilder $filterBuilder
* #param array $meta
* #param array $data
* #throws \Exception
*/
public function __construct(
$name,
$primaryFieldName,
$requestFieldName,
ReportingInterface $reporting,
SearchCriteriaBuilder $searchCriteriaBuilder,
RequestInterface $request,
FilterBuilder $filterBuilder,
array $meta = [],
array $data = []
) {
$data['config']['filter_url_params']['product_id'] = $request->getParam('cppc_product_id', 0);
parent::__construct($name, $primaryFieldName, $requestFieldName, $reporting, $searchCriteriaBuilder, $request, $filterBuilder, $meta, $data);
}
You do not need to use any other function. The reason why this is is because it is also updated with an update URL and that does not have that parameter. By using adding that to the data it also parses that into the update url.
You can see that here (Parent function)
/**
* #return void
*/
protected function prepareUpdateUrl()
{
if (!isset($this->data['config']['filter_url_params'])) {
return;
}
foreach ($this->data['config']['filter_url_params'] as $paramName => $paramValue) {
if ('*' == $paramValue) {
$paramValue = $this->request->getParam($paramName);
}
if ($paramValue) {
$this->data['config']['update_url'] = sprintf(
'%s%s/%s/',
$this->data['config']['update_url'],
$paramName,
$paramValue
);
$this->addFilter(
$this->filterBuilder->setField($paramName)->setValue($paramValue)->setConditionType('eq')->create()
);
}
}
}
I have this function:
/**
* #Secure(roles="IS_AUTHENTICATED_FULLY")
* #Route("/chequearFabricanteDistribuidor", name="chequearFabricanteDistribuidor", condition="request.headers.get('X-Requested-With') == 'XMLHttpRequest'")
* #Method("GET")
*/
public function chequearFabricanteAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('AppBundle:FabricanteDistribuidor')->findOneBy(
array( 'nombre' => $request->query->get('fabricante')['nombre'] )
);
$response['valid'] = true;
if ($entities) {
$response['valid'] = false;
}
return new JsonResponse($response);
}
The function needs to be called from two different forms and the only different is the request var that holds the value. In the first form is: $request->query->get('fabricante')['nombre'] while in the second is $request->query->get('distribuidor')['nombre'] so I'm asking if the right way to handle this could be:
if (isset($request->query->get('fabricante')))
{
$nombre = $request->query->get('fabricante')['nombre'];
}
else
{
$nombre = $request->query->get('distribuidor')['nombre'];
}
Is this right? Exists a better one?
As Cerad posted on the responses, you could use:
$request->query->has('distribuidor')
So I've been trying to get data from a single item from the database using the MVC method in Joomla. I've been inspecting com_content how to do this, but I can't seem to get the id from the URL
This is my model to get the data for a single item
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla modelitem library
jimport('joomla.application.component.modelitem');
/**
* Issuu Model
*/
class IssuuModelItem extends JModelItem
{
/**
* #var string msg
*/
protected $item;
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* #since 1.6
*
* #return void
*/
protected function populateState()
{
$app = JFactory::getApplication('site');
// Load state from the request.
$id = $app->input->getInt('id');
$this->setState('item.id', $id);
$offset = $app->input->getUInt('limitstart');
$this->setState('list.offset', $offset);
// Load the parameters.
$params = $app->getParams();
$this->setState('params', $params);
// TODO: Tune these values based on other permissions.
$user = JFactory::getUser();
if ((!$user->authorise('core.edit.state', 'com_issuu')) && (!$user->authorise('core.edit', 'com_issuu')))
{
$this->setState('filter.published', 1);
$this->setState('filter.archived', 2);
}
$this->setState('filter.language', JLanguageMultilang::isEnabled());
}
/**
* Returns a reference to the a Table object, always creating it.
*
* #param type The table type to instantiate
* #param string A prefix for the table class name. Optional.
* #param array Configuration array for model. Optional.
* #return JTable A database object
* #since 2.5
*/
public function getTable($type = 'Item', $prefix= 'IssuuTable', $config = array()) {
return JTable::getInstance($type,$prefix,$config);
}
/**
* Get the message
* #return string The message to be displayed to the user
*/
public function getItem($id = null)
{
$id = (!empty($id)) ? $id : (int) $this->getState('item.id');
if(!is_array($this->item)) {
$this->item = array();
}
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('id', 'title', 'username', 'docname', 'docid','date', 'pages', 'description')));
$query->from($db->quoteName('#__issuu_publications'));
$query->where($db->quoteName('state') . ' = `1` AND ' . $db->quoteName('id') . ' = ' . $db->qouteName($id));
$query->order('date ASC');
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$this->items = $db->loadObjectList();
return $this->items;
}
}
I get a SQL error because the $id is empty.. (I removed the prefix from the table)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY date ASC' at line 4 SQL=SELECT `id`,`title`,`username`,`docname`,`docid`,`date`,`pages`,`description` FROM `#__issuu_publications` WHERE `state` = `1` AND `id` = ORDER BY date ASC
Any help is appreciated!
Try replacing your where clause with the following:
$query->where($db->quoteName('state') . ' = 1 AND ' . $db->quoteName('id') . ' = ' . $db->quote((int) $id));
I've removed the quotes around 1
replaced $id with (int) $id
And corrected a spelling mistake on quoteName