Magento: how to fix customer name search - magento

Under the Magento admin menu Customers -> Manage Customers, we're unable to search for a customer using his name if the string consists of more than one word. Where would I find the core codes that performs this task? We don't have an extension for this section.
Example of the problem:
If I want to search for a customer named John Smith, searching for "john smith" returns no results. Searching for "john" or "smith" separately works, but it will bring up any names that contain "john" or "smith" similar to the SQL queries, LIKE %john% or LIKE %smith%.

Looks like you're using Magento version 1.6
It is a bug and has been fixed in 1.7
Here's the code that need to be modified: app/code/core/Mage/Customer/Model/Resource/Customer/Collection.php
I post the code taken from version 1.7:
Mage_Customer_Model_Resource_Customer_Collection
public function addNameToSelect()
{
$fields = array();
$customerAccount = Mage::getConfig()->getFieldset('customer_account');
foreach ($customerAccount as $code => $node) {
if ($node->is('name')) {
$fields[$code] = $code;
}
}
$adapter = $this->getConnection();
$concatenate = array();
if (isset($fields['prefix'])) {
$concatenate[] = $adapter->getCheckSql(
'{{prefix}} IS NOT NULL AND {{prefix}} != \'\'',
$adapter->getConcatSql(array('LTRIM(RTRIM({{prefix}}))', '\' \'')),
'\'\'');
}
$concatenate[] = 'LTRIM(RTRIM({{firstname}}))';
$concatenate[] = '\' \'';
if (isset($fields['middlename'])) {
$concatenate[] = $adapter->getCheckSql(
'{{middlename}} IS NOT NULL AND {{middlename}} != \'\'',
$adapter->getConcatSql(array('LTRIM(RTRIM({{middlename}}))', '\' \'')),
'\'\'');
}
$concatenate[] = 'LTRIM(RTRIM({{lastname}}))';
if (isset($fields['suffix'])) {
$concatenate[] = $adapter
->getCheckSql('{{suffix}} IS NOT NULL AND {{suffix}} != \'\'',
$adapter->getConcatSql(array('\' \'', 'LTRIM(RTRIM({{suffix}}))')),
'\'\'');
}
$nameExpr = $adapter->getConcatSql($concatenate);
$this->addExpressionAttributeToSelect('name', $nameExpr, $fields);
return $this;
}

Related

Laravel help for optimize command script

I'm working with Lumen framework v5.8 (it's the same as Laravel)
I have a command for read a big XML (400Mo) and update datas in database from datas in this file, this is my code :
public function handle()
{
$reader = new XMLReader();
$reader->open(storage_path('app/mesh2019.xml'));
while ($reader->read()) {
switch ($reader->nodeType) {
case (XMLREADER::ELEMENT):
if ($reader->localName === 'DescriptorRecord') {
$node = new SimpleXMLElement($reader->readOuterXML());
$meshId = $node->DescriptorUI;
$name = (string) $node->DescriptorName->String;
$conditionId = Condition::where('mesh_id', $meshId)->first();
if ($conditionId) {
ConditionTranslation::where(['condition_id' => $conditionId->id, 'locale' => 'fr'])->update(['name' => $name]);
$this->info(memory_get_usage());
}
}
}
}
}
So, I have to find in the XML each DescriptorUI element, the value corresponds to the mesh_id attribute of my class Condition.
So, with $conditionId = Condition::where('mesh_id', $meshId)->first(); I get the Condition object.
After that, I need to update a child of Condition => ConditionTranslation. So I just get the element DescriptorName and update the name field of ConditionTranslation
At the end of the script, you can see $this->info(memory_get_usage());, and when I run the command the value increases each time until the script runs very very slowly...and never ends.
How can I optimize this script ?
Thanks !
Edit : Is there a way with Laravel for preupdate multiple object, and save just one time at the end all objects ? Like the flush() method of Symfony
There is a solution with ON DUPLICATE KEY UPDATE
public function handle()
{
$reader = new XMLReader();
$reader->open(storage_path('app/mesh2019.xml'));
$keyValues = [];
while ($reader->read()) {
switch ($reader->nodeType) {
case (XMLREADER::ELEMENT):
if ($reader->localName === 'DescriptorRecord') {
$node = new SimpleXMLElement($reader->readOuterXML());
$meshId = $node->DescriptorUI;
$name = (string) $node->DescriptorName->String;
$conditionId = Condition::where('mesh_id', $meshId)->value('id');
if ($conditionId) {
$keyValues[] = "($conditionId, '".str_replace("'","\'",$name)."')";
}
}
}
}
if (count($keyValues)) {
\DB::query('INSERT into `conditions` (id, name) VALUES '.implode(', ', $keyValues).' ON DUPLICATE KEY UPDATE name = VALUES(name)');
}
}

Magento - Remove Multiple Product URL Rewrites

In my CE-1.9.0 store my products currently create the following url rewrites:
http://example.com/product-name
http://example.com/category/product-name
http://example.com/another-category/subcategory/product-name
However in my store I want to be able to stop creating the rewrites for the category versions. I have System > Configuration > Catalog > Catalog > Use Categories Path for Product URLs set to No so these extra rewrites are unnecessary. Plus my store has around 500,000 products and counting so these extra url's are taking up a lot of space in the core_url_rewrite` table.
So my aim is to only be left with these versions:
http://example.com/product-name
If I truncate the core_url_rewrite table and reindex then only these versions get created so it is only when new products are created. My catalog is so large so I cannot keep truncated and rebuilding the table from scratch as the rebuilding takes several hours.
With help from this question I have found the file that is responsible for creating the rewrites when a product is created. It is:
app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php
However the answer is no longer valid as the code has changed in the core file.
In this file on line #538 there is the _afterLoad function it is the line
$this->_addUrlRewrite($this->_urlRewriteCategory);
And this function _addUrlRewrite however i've tried changing a lot inside this function but have had no luck. The function in full is:
protected function _addUrlRewrite()
{
$urlRewrites = null;
if ($this->_cacheConf) {
if (!($urlRewrites = Mage::app()->loadCache($this->_cacheConf['prefix'] . 'urlrewrite'))) {
$urlRewrites = null;
} else {
$urlRewrites = unserialize($urlRewrites);
}
}
if (!$urlRewrites) {
$productIds = array();
foreach($this->getItems() as $item) {
$productIds[] = $item->getEntityId();
}
if (!count($productIds)) {
return;
}
$select = $this->_factory->getProductUrlRewriteHelper()
->getTableSelect($productIds, $this->_urlRewriteCategory, Mage::app()->getStore()->getId());
$urlRewrites = array();
foreach ($this->getConnection()->fetchAll($select) as $row) {
if (!isset($urlRewrites[$row['product_id']])) {
$urlRewrites[$row['product_id']] = $row['request_path'];
}
}
if ($this->_cacheConf) {
Mage::app()->saveCache(
serialize($urlRewrites),
$this->_cacheConf['prefix'] . 'urlrewrite',
array_merge($this->_cacheConf['tags'], array(Mage_Catalog_Model_Product_Url::CACHE_TAG)),
$this->_cacheLifetime
);
}
}
foreach($this->getItems() as $item) {
if (empty($this->_urlRewriteCategory)) {
$item->setDoNotUseCategoryId(true);
}
if (isset($urlRewrites[$item->getEntityId()])) {
$item->setData('request_path', $urlRewrites[$item->getEntityId()]);
} else {
$item->setData('request_path', false);
}
}
}

How to create in Magento with custom code?

I am using this code to create categories and subcategories. This code works fine but the problem is I can't create my own category codes. And I need it to use it for the requeriments.
$category = Mage::getModel('catalog/category');
$category->setStoreId(0); // 0 = default/all store view. If you want to save data for a specific store view, replace 0 by Mage::app()->getStore()->getId().
//if update
if ($id) {
$category->load($id);
}
$general['name'] = "My Category";
$general['path'] = "1/3/"; // catalog path here you can add your own ID
$general['description'] = "Great My Category";
$general['meta_title'] = "My Category"; //Page title
$general['meta_keywords'] = "My , Category";
$general['meta_description'] = "Some description to be found by meta search robots. 2";
$general['landing_page'] = ""; //has to be created in advance, here comes id
$general['display_mode'] = "PRODUCTS"; //static block and the products are shown on the page
$general['is_active'] = 1;
$general['is_anchor'] = 0;
$general['page_layout'] = 'two_columns_left';
//$general['url_key'] = "cars";//url to be used for this category's page by magento.
//$general['image'] = "cars.jpg";
$category->addData($general);
try {
$category->setId(255); // Here you cant set your own entity id
$category->save();
echo "Success! Id: ".$category->getId();
}
catch (Exception $e){
echo $e->getMessage();
}
I tried to do something like that:
$general['id'] = $myCustomId;
But it's not working.
The key needs to map the column header, which is entity_id. So, change $general['id'] to
$general['entity_id'] = $myCustomId;

Magento - Get Country Id from Name - is there a easier/quicker way?

I need to load the 2 letter ISO2 country ID for a given country name.
Right now, I use the following method to do this:
// Method to Get countryId from CountryName
function getCountryId($countryName) {
$countryId = '';
$countryCollection = Mage::getModel('directory/country')->getCollection();
foreach ($countryCollection as $country) {
if ($countryName == $country->getName()) {
$countryId = $country->getCountryId();
break;
}
}
$countryCollection = null;
return $countryId;
}
Usage:
var_dump(getCountryId('Germany'));
Outputs:
string(2) "DE"
Is there a easier/quicker way to do this instead of loading the country collection and iterating through it every time?
Surprisingly, looping is the only way you'll achieve this.
The country names are stored in XML files in lib/Zend/Locale/Data/ and they're organized by locale (en, es, fr) and then country code, not country name.
Since it's not a SQL table you can't add a WHERE clause (using Magento's addFieldToFilter()), so you'll be looping through the XML nodes anyway.
There is no other way, because of translations. This is function for getting country name, you can't reverse it
public function getName()
{
if(!$this->getData('name')) {
$this->setData(
'name',
Mage::app()->getLocale()->getCountryTranslation($this->getId())
);
}
return $this->getData('name');
}

Bringing in value of Coupon Code into "tax" calculation.php in magento

Im trying to pull in the name of the discount code currently applied to the cart into the calculation.php file. The name of the discount code is optionalTax but Im having trouble passing it through or retrieving it directly. Its appears to be referenced as $quote->getCouponCode() in mage/sales/model/quote.php and I want to use it in
mage/tax/model/calculation.php
Anyone have any idea on how to call it in as I've tried using the model as per (which I think is correct)
public function calcTaxAmount($price, $taxRate, $priceIncludeTax=false, $round=true)
{
$taxRate = $taxRate/100;
if ($priceIncludeTax) {
$amount = $price*(1-1/(1+$taxRate));
} else {
$cModel = Mage::getModel('catalog/sales');
$thisDiscountCode = $cModel->$quote->getCouponCode();
die($thisDiscountCode);
$amount = $price*$taxRate;
}
if ($round) {
return $this->round($amount);
} else {
return $amount;
}
}
Chris
you need to get the quote from right model i guess:
Mage::getSingleton('checkout/session')->getQuote();

Resources