Wordpress if custom field value is null previous posts' value is displayed - custom-fields

I have this code with a loop that gives me some trouble and strange results.
This particular post type has a few custom fields which I put in an array. Everything works as expected, but if a field has no value it will take the value from the previous post within the loop.
Let's say I have these posts in Wordpress:
Post ID 10
custom_1 = 10
custom_2 = 20
custom_3 = 30
Post ID 20
custom_1 = 40
custom_2 = null
custom_3 = null
If I run my loop I get these results
Post ID 10
custom_1 = 10
custom_2 = 20
custom_3 = 30
Post ID 20
custom_1 = 40
custom_2 = 20 (instead of null)
custom_3 = 30 (instead of null)
Here's the short version of that loop:
$query = new WP_Query($query_arg);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$result[] = array(
"custom_1" => get_post_meta($post->ID, 'custom_1', true),
"custom_2" => get_post_meta($post->ID, 'custom_2', true),
"custom_3" => get_post_meta($post->ID, 'custom_3', true)
);
}
}
wp_reset_postdata();
I can't seem to wrap my head around this one.. tried pretty much everything, but nothing seams to work.
Does anyone know what's happening here?
UPDATE:
Fixed it by changing the loop to this.
$query = new WP_Query($query_arg);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
//set vars to "" which 'resets' the value with every new post in the loop
$custom_1 = "";
$custom_2 = "";
$custom_3 = "";
//set vars to the value of the custom fields
$custom_1 => get_post_meta($post->ID, 'custom_1', true);
$custom_2 => get_post_meta($post->ID, 'custom_2', true);
$custom_3 => get_post_meta($post->ID, 'custom_3', true);
$result[] = array(
"custom_1" => $custom_1,
"custom_2" => $custom_2,
"custom_3" => $custom_3
);
}
}
wp_reset_postdata();

It might be due to how the MYSQL handles null. Null means an absence of value, so they do not get a space in the database, not even an empty one. An empty string however does show in the database.
Try the following
Post ID 10
custom_1 = 10
custom_2 = 20
custom_3 = 30
Post ID 20
custom_1 = 40
custom_2 = ""
custom_3 = ""

Related

Do not include the database column when query string is NULL

I'm trying to make a search functionality. The code below says that if Port, Status and TIN are not null then query the database.
E.g 1. If User has chosen the port and status but not the TIN then the
TIN should not be included when searching the database.
E.g 2. If User has chosen the port only then the Status and TIN should
not be included when searching the database.
Code
int Port = Convert.ToInt32(Request.QueryString["Port"]);
var Status = Request.QueryString["Status"];
var TIN = Request.QueryString["TIN"];
List<Transaction> QueriedTransactionList;
QueriedTransactionList = db.Transactions.ToList();
TransactionViewModel TransactionViewModel = new TransactionViewModel();
List<TransactionViewModel> TransactionDataList = QueriedTransactionList.Select(x => new TransactionViewModel{
TTransactionID = x.TTransactionID,
BatchID = x.BatchID,
TransactionDateTime = x.TransactionDateTime,
TransactionStatus = x.TransactionStatus,
TaxPayerName = x.Card.TaxPayer.TaxPayerName,
TaxPayerEmail = x.Card.TaxPayer.TaxPayerEmail,
TaxPayerTIN = x.Card.TaxPayer.TaxPayerTIN,
DispatchBy = x.User.UserName,
DestinationPort = x.Card.Port.PortName,
BatchCards = Helper.GetBatchQtyByBatchID(x.BatchID)
}).GroupBy(x => x.BatchID).Select(x => x.LastOrDefault()).Where(x => Status.IndexOf(x.TransactionStatus, StringComparison.OrdinalIgnoreCase) >= 0 && TIN.IndexOf(x.Card.TaxPayerTIN, StringComparison.OrdinalIgnoreCase) >= 0).OrderByDescending(x => x.TTransactionID).ToList();

Views hook_views_query_alter JOIN

In hook_views_query_alter i build join query like this:
$join = new views_join();
$join->table = 'table_2';
$join->field = 'field_2';
$join->left_table = 'table_1';
$join->left_field = 'field_1';
$join->type = 'LEFT';
$join->extra = array(
array(
'table' => 'table_2',
'field' => 'field_3',
'value' => 'table_1.field_4',
),
);
The query should looks like this:
LEFT JOIN {table_2} table_2 ON table_1.field_1 = table_2.field_2 AND table_1.field_3 = table_2.field_4
My problem is here 'value' => 'table_1.field_4'. I can't set value as field. It treat it as string value. So at the and in my query i have unwanted single quotes.
So at the end my query looks like this:
LEFT JOIN {table_2} table_2 ON table_1.field_1 = table_2.field_2 AND table_1.field_3 = 'table_2.field_4'
I'm not sure if it's the best solution but this:
$join = new views_join();
$join->table = 'table_2';
$join->field = 'field_2';
$join->left_table = 'table_1';
$join->left_field = 'field_1';
$join->type = 'LEFT';
$join->extra = 'table_1.field_3 = table_2.field_4';
works for me.

TYPO3: HMENU not working in foreign language

The footer menu is defined as follows:
temp.footerNav = HMENU
temp.footerNav {
special = userfunction
special.userFunc = \MyNamespace\Helper->footerNavArray
wrap = <ul>|</ul>
1 = TMENU
1 {
wrap = |
expAll = 0
NO = 1
NO.ATagParams = class="footer-navigation-link"
NO.stdWrap.htmlSpecialChars = 1
NO.wrapItemAndSub = <li class="footer-navigation__item">|</li>
NO.stdWrap.field = title // nav_title
}
}
The array returned by the function footerNavArray looks good in both German
array (size=7)
0 =>
array (size=2)
'title' => string 'Unternehmen' (length=11)
'_OVERRIDE_HREF' => string 'de/unternehmen.html' (length=19)
...
...
and English:
array (size=7)
0 =>
array (size=2)
'title' => string 'Company' (length=7)
'_OVERRIDE_HREF' => string 'en/company.html' (length=15)
...
...
The footer menu works perfectly in English (default language), however, the only output I can see on the German page (L=1) is <ul></ul>.
Any ideas?
First of all, the above behaviour was caused by [FE][hidePagesIfNotTranslatedByDefault] = 1, which is required by Solr for TYPO3 to work correctly in a multi-language site. By adding '_SAFE' = true to the menu array, I was finally able to solve the problem:
array (size=7)
0 =>
array (size=3)
'title' => string 'Company' (length=7)
'_OVERRIDE_HREF' => string 'en/company.html' (length=15)
'_SAFE' => boolean true
...
...
I've found the solution in line 1213 (core version 7.6.2) of TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject->filterMenuPages():
you can also use global env condition for different language.
#setup the default language in case of bad L variable
config.sys_language_mode = content_fallback
config.uniqueLinkVars=1
config.sys_language_overlay = 1
config.sys_language_uid = 0
config.language = en
config.linkVars = L
# Spanish language, sys_language.uid = 1
[globalVar = GP:L = 1]
config.sys_language_uid = 1
config.language = es
config.locale_all = spanish
[global]
# English language, sys_language.uid = 0
[globalVar = GP:L = 0]
config.sys_language_uid = 0
config.language = en
[global]

sfWidgetFormDoctrineChoice: bug, error or what?

I'm using sfWidgetFormDoctrineChoice to build select elements in a form. This is how I'm using:
// Fill maquinaemisorid
$this->widgetSchema['maquinaemisorid'] = new sfWidgetFormDoctrineChoice(array('model' => 'SdrivingMaquina', 'add_empty' => 'Seleccione una Máquina', 'table_method' => 'fillChoice'));
// Fill idoperador
$this->widgetSchema['idoperador'] = new sfWidgetFormDoctrineChoice(array('model' => 'SdrivingOperador', 'add_empty' => 'Seleccione un Operador', 'table_method' => 'fillChoice'));
// Fill idturno
$this->widgetSchema['idturno'] = new sfWidgetFormDoctrineChoice(array('model' => 'SdrivingTurno', 'add_empty' => 'Seleccione un Turno', 'table_method' => 'fillChoice'));
For the first widget all is fine and values are taken from DB as should be but for the second one and the third is not working. As you may notice I'm calling a method fillChoice in all widgets table_method. This is the code for the three:
SdrivingMaquinaTable.class.php
public function fillChoice() {
$id_empresa = sfContext::getInstance()->getUser()->getGuardUser()->getSfGuardUserProfile()->getIdempresa();
return Doctrine_Core::getTable('SdrivingMaquina')->createQuery('a')->where('a.idempresa = ?', $id_empresa)->execute();
}
SdrivingOperadorTable.class.php
public function fillChoice() {
$id_empresa = sfContext::getInstance()->getUser()->getGuardUser()->getSfGuardUserProfile()->getIdempresa();
return Doctrine_Core::getTable('SdrivingOperador')->createQuery('a')->where('a.idempresa = ?', $id_empresa)->execute();
}
SdrivingTurno.class.php
public function fillChoice() {
$id_empresa = sfContext::getInstance()->getUser()->getGuardUser()->getSfGuardUserProfile()->getIdempresa();
return Doctrine_Core::getTable('SdrivingTurno')->createQuery('a')->where('a.idempresa = ?', $id_empresa)->execute();
}
The method is the same always just changes the table used for each class. I check the generated queries and all are fine and if I run each on phpMyAdmin for example more than one value is fetched altough in idoperador and idturno just the latest is rendered. This is a very rare behavior and I can't find the error or mistake so I need some help or advice here.
As an adition I tried this in SdrivingRegistrosEmisoresForm.class.php (this is where the widgets are being generated):
$id_empresa = $this->current_user->getSfGuardUserProfile()->getIdempresa();
$choices_operador = Doctrine_Core::getTable('SdrivingOperador')->createQuery('a')->where('a.idempresa = ?', $id_empresa)->execute();
$this->widgetSchema['idoperador'] = new sfWidgetFormSelect(array('choices' => $choices_operador));
And this way works fine but the id for each item fetched isn't right meaning:
id item real_id
0 Item1 2
1 Item2 16
2 Item4 3
I talked about this in this topic but didn't get any answer, any help?
As stated in sfWidgetFormDoctrineChoice, if option *table_method* returns a collection like your methods, it renders choices with options *key_method* and method. By default , they are respectively getPrimaryKey() and *__toString()*.
Can we check you schema.yml and the __toString() ?
As for your last example the option choices of sfWidgetFormSelect should be an array an not a *Doctrine_Collection*

Export products from Mysql Magento

I have some problems with Magento DB, i cannot match the attributes for my custom products export file.
I need help to get attributes, i have finished this script only with this header
But attribute_set, visibility and size_cloth is returning number not name. maybe this can be resolved with a match function.
I need to get more attributes, ex: category_ids, i cannot get this...
color, size_shoes, size_etc.
Please check my script.
'store', '_website', 'attribute_set', 'type', 'sku', 'name', 'description', 'short_description', 'visibility', 'has_option', 'price', 'special_price', 'size_cloth', 'link', 'image'
<?php
//Setup Connection information
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'pass';
//Connect to the database
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
//Point to specific DB
$dbname = 'database_name';
mysql_select_db($dbname);
//Create the Query to get the products
$sql = "SELECT DISTINCT P.attribute_set_id, P.type_id, P.sku, P.has_options, V.value AS Name, T1.value AS ProdDesc, T2.value AS ShortDesc,
T5.value AS visibility, D.value AS Price, S.value AS Special_Price, SIZE_CLOTH.value AS size_cloth, CONCAT('http://www.website.com/', V1.value) AS Link,
CASE
WHEN V2.Value IS NULL
THEN NULL
ELSE CONCAT('http://www.website.com/media/catalog/product', V2.value)
END AS Image
FROM catalog_product_entity AS P INNER JOIN
catalog_product_entity_varchar AS V ON P.entity_id = V.entity_id AND V.attribute_id = 60 LEFT JOIN
catalog_product_entity_varchar AS V1 ON P.entity_id = V1.entity_id AND V1.attribute_id = 87 LEFT JOIN
catalog_product_entity_varchar AS V2 ON P.entity_id = V2.entity_id AND V2.attribute_id = 74 LEFT JOIN
catalog_product_entity_text AS T1 ON P.entity_id = T1.entity_id AND T1.attribute_id = 61 LEFT JOIN
catalog_product_entity_text AS T2 ON P.entity_id = T2.entity_id AND T2.attribute_id = 62 LEFT JOIN
catalog_product_entity_int AS T5 ON P.entity_id = T5.entity_id AND T5.attribute_id = 91 LEFT JOIN
catalog_product_entity_decimal AS D ON P.entity_id = D.entity_id AND D.attribute_id = 64 LEFT JOIN
catalog_product_entity_int AS SIZE_CLOTH ON P.entity_id = SIZE_CLOTH.entity_id AND SIZE_CLOTH.attribute_id = 122 LEFT JOIN
catalog_product_entity_decimal AS S ON P.entity_id = S.entity_id AND S.attribute_id = 65";
//Run the query
$query = mysql_query($sql);
//But after this i will prepare the csv file for export.
$file = fopen('products_export.csv', 'w');
// Custom header for csv file
$header = array('store', '_website', 'attribute_set', 'type', 'sku', 'name', 'description', 'short_description', 'visibility', 'has_option', 'price', 'special_price', 'size_cloth', 'link', 'image');
// this will arrange all data by comma
fputcsv($file, $header, ',', '"');
//Loop through and print each products info
while($row = mysql_fetch_array($query))
{
$item = array();
$value1 = ("admin");
$value2 = ("base");
$value3 = ($row['attribute_set_id']);
$value4 = ($row['type_id']);
$value5 = ($row['sku']);
$value6 = ($row['Name']);
$value7 = ($row['ProdDesc']);
$value8 = ($row['ShortDesc']);
$value9 = ($row['visibility']);
$value10 = ($row['has_options']);
$value11 = ($row['Price']);
$value111 = ($row['Special_Price']);
$value112 = ($row['size_cloth']);
$value12 = ($row['Link']);
//$value13 = ($row['Image']);
$item[] = $value1;
$item[] = $value2;
$item[] = $value3;
$item[] = $value4;
$item[] = $value5;
$item[] = $value6;
$item[] = $value7;
$item[] = $value8;
$item[] = $value9;
$item[] = $value10;
$item[] = $value11;
$item[] = $value111;
$item[] = $value112;
$item[] = $value12;
// put all data in csv file
fputcsv($file, $item, ',', '"');
}
{
// close csv file and finish.
fclose($file);
}
?>
I think that the best solution will be the data.
Example:
if ( $value112 == need to array the list of numbers, 1, 2, 3, 4, 5) {
echo "S, M, L, XL";
} else {
echo " ";
}
But i dont know how to insert this to my array items...
Interacting directly with Magento's DB wouldn't be my 1st choice.
Alternatives that actually work:
Use Magento Import/Export module
Use Magento Dataflow Import/Export
Use Magento's product collection to generate the export file
http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-8-varien-data-collections

Resources