How to write an extbase Repository-Method for Update in TYPO3? - 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_*.

Related

Joomla: get all users in a usergroup

I am working on a component where I want to show all users of a specific usergroup. Right now I found two solutions for this but I'm not feeling comfortable with both of them.
Solution 1
$usersID = JAccess::getUsersByGroup(3);
$users = array();
foreach($usersID as $cUserID)
{
$users[] = JFactory::getUser($cUserID);
}
This one seems to produce two database queries every time JFactory::getUser($cUserID) is called. I really don't want this.
Solution 2
function inside model
function getUsers()
{
if(!isset($this->users))
{
$groupID = 3;
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$select = array( 'users.id', 'users.name');
$where = $db->quoteName('map.group_id') . ' = ' . $groupID;
$query
->select($select)
->from( $db->quoteName('#__user_usergroup_map', 'map') )
->leftJoin( $db->quoteName('#__users', 'users') . ' ON (map.user_id = users.id)' )
->where($where);
$db->setQuery($query);
$this->users = $db->loadObjectList();
}
return $this->users;
}
This one works like a charm but I feel there should be a "more Joomla! way" of doing this. I don't like working on their tables.
Right now I'm going with solution 2 but i really wonder if there is some better way to do it.

Magento 2 - change url key programmatically

Is there a way to generate URL Keys for all products and save them using a script?
I deleted all URL keys for products from database, but now I want to generate them again using a script.
// Edit: I need to do this in Magento 2. Forgot to specify.
I got this until now:
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$deploymentConfig = $obj->get('Magento\Framework\App\DeploymentConfig');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$repo = $objectManager->get('Magento\Catalog\Model\ProductRepository');
$collection = $productCollection->create()
->addAttributeToSelect('*')
->load();
foreach ($collection as $product){
$name = $product->getName();
$url = preg_replace('#[^0-9a-z]+#i', '-', $name);
$url = strtolower($url);
echo $url;
$pr = $repo->getById($product->getId());
$pr->setUrlKey($url);
$repo->save($pr);
break;
}
But I get this error:
Fatal error: Call to undefined function Magento\Catalog\Model\Config\Source\Product\Options__() in /home2/magazi70/public_html/vendor/magento/module-catalog/Model/Config/Source/Product/Options/Price.php on line 23
<?php
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$deploymentConfig = $obj->get('Magento\Framework\App\DeploymentConfig');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('\Magento\Catalog\Model\Product');
$collection = $productCollection->create()
->addAttributeToSelect('*')
->load();
foreach ($collection as $product){
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load($product->getId());
$name = $product->getName();
$url = preg_replace('#[^0-9a-z]+#i', '-', $name);
$url = strtolower($url);
$product ->setUrlKey($url);
$product->save($pr);
}
The magento script may take longer time.
1. You can try exporting the products (the csv file will not have url keys)
2. Remove all the attributes and keep only SKU and Name and add a new attribute column url_key
3. Use some Excel Functions to generate url keys using Name
4. Remove the Name column
5. Import the csv
to loading a collection and save the new object of product is slow way to done the job
here is best way to
composer require elgentos/regenerate-catalog-urls
php bin/magento module:enable Iazel_RegenProductUrl
php bin/magento setup:upgrade
more information are available on
https://github.com/elgentos/regenerate-catalog-urls
This code shows how to generate an url key, in a helper class, the same way Magento 2 generates url keys when creating products.
In the example I use dependency injection in order to use Magento\Catalog\Model\Product\Url class in my helper.
namespace Myprojects\Mymodule\Helper;
use Magento\Catalog\Model\Product\Url;
use Magento\Framework\App\Helper\Context as HelperContext;
class Data extends AbstractHelper
{
/**
* #param Url $url
*/
public function __construct(
HelperContext $context,
Url $url
)
{
parent::__construct($context);
$this->url = $url;
}
public function generateUrlKey($string)
{
return $this->url->formatUrlKey($string);
}
}

how to use insert record function in moodle

I am trying to insert record into my database using moodle.
I am using version 1.9.19. i am trying the following code :
<?php
require_once('config.php');
require_once('uplo.php');
$mform = new uplo();
$mform->display();
if(isset($_POST['submitbutton'])){
$name = $mform->get_data('name');
$email = $mform->get_data('email');
$table='mdl_tet';
$res=insert_record($table, '$name','$email') ;
}
?>
But this is not working correctly. How to do that correctly.
Note : Why am using 1.9.19 means my client using this version so i cant change the version.
The insert_record() function takes two parameters - the name of the table (without the prefix) and an object containing the data to insert into the table.
So, in this case, you should write something like:
$ins = (object)array('name' => $name, 'email' => $email);
$ins->id = insert_record('tet', $ins);
OR:
$ins = new stdClass();
$ins->name = $name;
$ins->email = $email;
$ins->id = insert_record('tet', $ins);
(As an aside - make sure you turn on debugging - https://docs.moodle.org/19/en/Debugging - it will make your life a lot easier).

OR condation in symfony find Query query

Hi I am unable to use OR condation in my following Symfony findBy query.
$searchArrayTasks = array(
"name" => new \MongoRegex('/.*'.trim($_POST['keyword']).'.*/')
);
$documents = $dm->getRepository('WorkOrganisationBundle:Tasks')->findBy($searchArrayTasks)->sort($sortArray )->limit($limit)->skip($skip);
Can any one suggest please how to use OR condation in this query.Because i want to make a search basis on different parameters Like Name OR class OR Type.
Thanks Advance
This way (certainly in your Manager) is a bad practice.
Its purpose is for really dumb request.
2 things :
-Put your code in a Repository
-And code your query in sql or dql :
public function common($qb, $limit)
{
$qb->setMaxResults($limit)
->orderBy('task.id', 'DESC');
return $qb;
}
public function findByNameClassOrType($keyword, $limit)
{
$qb = $this->createQueryBuilder('task');
$qb->select('task')
->where('task.name LIKE ?', '%'.$keyword.'%')
->orWhere('task.class LIKE ?', '%'.$keyword.'%')
->orWhere('task.type LIKE ?', '%'.$keyword.'%');
$qb = $this->common($qb, $limit);
return $qb->getQuery()->getResult();
}
Use ? symbol to be sure that Doctrine escape your strings.
EDIT (mongodb) : with Mongo use addOr($expr)
$q = $doctrineOdm->createQueryBuilder('Work\OrganisationBundle\Document\Tasks');
$q->addOr($q->expr()->field('task.name')->equals($keyword));
$q->addOr($q->expr()->field('task.type')->equals($keyword));
$result = $q->getQuery()->execute();
For more informations see https://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/query-builder-api.html

Zend get foreign ID from login table

I am using Zend and Doctrine to login using a table containing also a foreign ID to another table. I need to get this ID in order to use it in a Doctrine query (through the controller) to the database like this:
$q = Doctrine_Query::create()
->from('Lost_Model_Item i')
->where('i.StatID = ?', 'I need the ID here')
$result = $q->fetchArray();
I have tried to get it like this:
Zend_Auth::getInstance()->getIdentity()->ID
But it seems to not work. I am new to Zend and a bit lost here. Could you please help?
As I ma working with doctrine I have created an adapter as follow:
public function authenticate()
{
$q = Doctrine_Query::create()
->from('Lost_Model_Station u')
->where('u.username = ? AND u.password = MD5(?)',
array($this->username, $this->password)
);
$result = $q->fetchArray();
if (count($result) == 1) {
$this->_resultArray = $result[0];
return new Zend_Auth_Result(
Zend_Auth_Result::SUCCESS, $this->username, array());
} else {
return new Zend_Auth_Result(
Zend_Auth_Result::FAILURE, null,
array('Authentication unsuccessful')
);
}
}
How about using getIdentity to get the username and then use a sql join on Lost_Model_Item and Lost_Model_Station
$q = Doctrine_Query::create()
->from('Lost_Model_Item i')
->leftJoin('i.Lost_Model_Station u')
->where('u.username = ?', Zend_Auth::getInstance()->getIdentity())
$result = $q->fetchArray();
This assumes that there is a doctrine "hasOne" relation defined for Lost_Model_Station (in the base class):
public function setUp()
{
parent::setUp();
$this->hasOne('Lost_Model_Item', array(
'local' => 'StatID',
'foreign' => 'whatever_id_StatID_relates_to'));
}
Zend_Auth::getInstance()->getIdentity()->ID
well you got what you store in Identity . You need to post the code where you ask user to login . Because there you are not storing the ID inside the session storage which Zend_Auth uses . Basically do this there
$row = $this->_adapter->getResultRowObject();
Zend_Auth::getInstance()->getStorage()->write($row);
where $this->_adapter is
$this->_adapter = new Zend_Auth_Adapter_DbTable();
$this->_adapter->setTableName('users')
->setIdentityColumn('email')
->setCredentialColumn('password');