Magento - Single Custom Product Attribute with Array of Values - php

I have a need in Magento to provide an array custom product attribute that outputs all of its values as list items. The basic premise is a list of product ingredients... on a per product basis we need to enter (for example) water, salt, colourings - and for those to be rendered as a list on the front end.
My logic so far has been to use the standard text field attribute, entering comma separated values in the back-end and then to try and use that string as an array from which I can use foreach to create the unordered list.
So far I can echo the entire string as just one list item, but rendering the string as an array of its individual values has so far stumped me! See below...
The Ingredients text field attribute has a value of "water", "salt", "colourings". - the addition of quote marks and commas is only the assumption that this would pre-format the list ready to be an array.
<?php
$ingredientsArrayContent = $this->getProduct()->getSpa_productingredients();
$ingredientsArray = array($ingredientsArrayContent);
?>
<ul>
<?php
reset($ingredientsArray);
foreach ($ingredientsArray as $ingredientsValue) {
echo "<li>$ingredientsValue</li>\n";
}
?>
</ul>
So on the front end this is outputting:
<ul>
<li>"water", "salt", "colourings"</li>
</ul>
What of course I am looking to achieve is:
<ul>
<li>water</li>
<li>salt</li>
<li>colourings</li>
</ul>
Am I over complicating this and missing something really obvious even in Magento? Any pointers greatly appreciated!!

Perhaps instead of:
$ingredientsArray = array($ingredientsArrayContent);
try using:
$ingredientsArray = array(explode(",",$ingredientsArrayContent));
Depending on whether your attribute is set as: "water,salt,colourings" or "water, salt, colourings" your delimiter might need to change or how you set your attribute values might need to change.

Related

PHP foreach only returning 1st attribute value of Magento multiselect on product page

Title pretty much says it all. I'm trying to output a static block with the same ID as the attribute value, however my code is only outputing the FIRST attribute value.
The following code is in view.phtml and is outputing the first static block of the 5 multiselect values selected.
Any help is greatly appreciated!!!
<?php
$cmsstatic = $_product->getResource()->getAttribute('collection1')->getFrontend()->getValue($_product);
$blockids = explode(",", $cmsstatic);
foreach($blockids as $kry=>$value)
{
echo $this->getLayout()->createBlock('cms/block')->setBlockID($value)->tohtml();
}
?>
The issue here is that your $value block IDs are wrong. Take a look at the output from $_product->getResource()->getAttribute('collection1')->getFrontend()->getValue($_product) and you will probably notice it actually looks something like this: collection3, collection6. Notice the spaces after the commas. When you run explode(",", $cmsstatic) you are getting the spaces in your resulting array. Since the first block ID contains no extra spaces, it is valid, but none of the following ones will be.
Solution 1
explode(", ", $cmsstatic)
Solution 2
$this->getLayout()->createBlock('cms/block')->setBlockId(trim($value))->toHtml()

WordPress PHP htmlspecialchars(get_field... cannot read arrays?

I am working on a WordPress Website/Blog with two main functions.
Create reports.
Compile final report.
People can write reports, selecting the fields they need and publish it. Then at the end of the day, they can "compile" a final report from all of the reports (it concatenate the fields of all reports).
The theme is twentyten (in case it might be useful).
In my function.php file, I concatenate everthing for the final report using a foreach and lines like that:
$Urgences_Environnementales .= htmlspecialchars("<br/>".get_field('Urgences_Environnementales', $idnumber->ID));
$avezvous_regardé_des_indices_de_temps_violent_aujourdhui .= htmlspecialchars(get_field('avezvous_regardé_des_indices_de_temps_violent_aujourdhui', $idnumber->ID));
$quelle_est_cette_raison .= htmlspecialchars(get_field('quelle_est_cette_raison', $idnumber->ID));
One line per field, all the same way. After the loop is done, I update the fields:
update_field('Urgences_Environnementales',preg_replace('/(<br[\s]?[\/]?>[\s]*){2,}/', '<br/><br/>', htmlspecialchars_decode($Urgences_Environnementales)), $identificationRapport);
update_field('avezvous_regardé_des_indices_de_temps_violent_aujourdhui',preg_replace('/(<br[\s]?[\/]?>[\s]*){2,}/', '<br/><br/>', htmlspecialchars_decode($avezvous_regardé_des_indices_de_temps_violent_aujourdhui)), $identificationRapport);
update_field('quelle_est_cette_raison',preg_replace('/(<br[\s]?[\/]?>[\s]*){2,}/', '<br/><br/>', htmlspecialchars_decode($quelle_est_cette_raison)), $identificationRapport);
Then it's printed for the final report like this (this is a single field):
if(strip_tags(html_entity_decode(get_field('Urgences_Environnementales')))!=''){
simplebox(strip_tags(html_entity_decode(get_field('Urgences_Environnementales')))!='', get_field('Urgences_Environnementales'));
}
And for those fields it works perfectly.
My problem is that all my fields composed of arrays (checkboxes that people can select multiple choices using the ACF plugin) are empty in my databse... They appear perfectly in the single reports, but they appear blank in the final report.
As an exemple, this is what I see in my database for a single report for one of my arrays:
a:4:{i:0;s:49:"L’indice d’intensité d’orage violent (STI)";i:1;s:35:"L’indice d’orage violent (TMPV)";i:2;s:34:"Potential Severe Storm Environment";i:3;s:6:"Autres";}
The corresponding field in my final report is empty.
Would someone have an idea on how to read those arrays and record them correctly in my databse? Could I transform them in strings in my foreach loop? Should I do something differently?
If you need more code don't hesitate to ask. I didn't put all my 3 functions (functions.php, report.php, finalreport.php) that I have in my WordPress theme as it would take tons of lines and I'm pretty sure the most important ones are right here. If I'm wrong, I could post the functions.
I searched and searched, but I can't seem to find the answer by myself, so I'm searching for help here.
PS: This is my 1st post, if you have any reccomandations, you can send them to me and I will change my post.
Thank you very much for your help!
PPS: I'm sorry for my english, I'm french, from Montreal, Qc, Canada.
Advanced Custom Fields stores some values as serialized arrays (checkboxes, repeaters, etc). Your code is assuming that you will be getting a string back. As you suggested in your answer, the easiest way to account for this in your current code would be to use the is_array() method to check the type of the returned value, and then another inner loop to handle the summary. This code assumes you just want to concatenate all the values, you could just as easily use another array to make sure they are unique, etc.
// get the value from acf
$value = get_field( 'Urgences_Environnementales', $idnumber->ID );
// if it's already an array, use that, if not make it into an array with a single element
$value_arr = ( is_array( $value ) )? $value : array( $value );
$text = ""; // reset since this is in a loop
// concatenate each checkbox value
foreach ( $value_arr as $val ){
$text .= $val . ', ';
}
// append it to the main summary
$Urgences_Environnementales .= htmlspecialchars( "<br/>". $text );

PHP Extract Single String from List of Values

I need some assistance with php. I have been trying several things for the past several days including str_replace to no avail.
I have a field that may contain from 1 to 20 values, all listed on their own line, there is no html code in that field to separate them and some of the values may have their own spaces in between, so separating by space doesnt work.
What I need is to extract every single string of each line and convert it to code.
<p>For example, my field with values looks like this: </p>
<p><b>lang_fld </b><br>
------
<br>
English<br>
Spanish<br>
German<br>
French</p>
What I have in mind is to extract each line, ex. "English" from that string, and create a line of code like
<img src="images/flags/english.png> English
Basically I want to add the flag graphic to the word
I already tried
echo str_replace('English','<img src="images/flags/english.png>,lang_fld)<br>
...and so on
what I get after going through every single possible value is a bunch error
messages (different every time since I keep making changes - by guessing)
Can someone offer an easier option to do this? Not all 20 values will be in
that areatext field, some may contain just one language, some ten, some all 20,
etc.
Thank you!
Assuming you have all the values on a separate line, you can do explode() on the string to convert it to array of separate items, then loop through the array with foreach and perform any modifications with the single item. After you are done with the items and you would like to get them back together, you can use implode() to combine them into a single string.
A short sample ( you can of course use a for loop, I just prefer foreach here as it shows you better what is happening with the data ):
$text =
"French language
Italian language
English language";
$items = explode( "\n", $text ); // Split by newline ( you can also use "<br>" as separator )
$result = array(); // Modified data will be placed here
foreach ( $items as $item )
{
// Do something with $item
$item = "<img src=\"images/flags/$item.png\"> $item";
$result[] = $item;
}
// Merge them back together
$text = implode("\n", $result);

Getting multi Values from a dropdown list in PHP

This is my drop down list.
<p align="center"><select size="1" name="bo_chose" id="boID">
<option selected value="Select...">Select...</option>
<?php
while ($list_bo = mysql_fetch_array($select_brof)) {
echo "<option value=\"$list_bo[bo_name] $list_bo[bo_code]\">$list_bo[bo_code],$list_bo[bo_name]</option>"; }
?>
</select></p>
So the drop down will show first "select..."
and then will retrieve data andlist the bo_name, bo_code in <option>
It works well.
The problem is, I want to carry the value to another PHP page which will delete the
selected option in the drop down.
Of course the MySQL and PHP will complain that it does not exist ...why?
Its taking the new value $bo_chose (name of the dropdown list) as a new value
as (bo_name, bo_code) — as one value not as a split values.
So if the dropdown list is (george Mike GM)
the data will complain that there is no value called "George Mike GM"
when I want it to carry only "GM" which is the bo_code.
Can anyone help?
Just split the value with space as delimiter and pick the first value. May I know why do you
need to carry both name and id in first place.
You should just add $list_bo['bo_code'] as option value instead of both.
If I understand you correctly you have this select inside a POST form or you are sending it by ajax to the script you want to parse the value. Use a separator to merge these two variables. The separator should be a char that you are sure, it will never be in either of two variables. So, you can for example use ; for the separator and write $list_bo[bo_name].';'.$list_bo[bo_code]. In the recieving script you just explode the value by separator and you will get both values as array. If you are unsure which chars will be in both variables, you can either json_encode or serialize it before puting it into html.

include PHP in shortcode

Hi I have a string replace:
$sHTML = str_replace( "[+fs.area.'{$member[ "town" ]}'+]", hello", $sHTML );
I have multiple towns in the database and i cannot go adding static short codes for each town as the user maybe adding towns later, i basically want to put into the html:
[+fs.area.townname+] which in this case will show hello am i doing something wrong or is there another way i can go about it?
This is not wordpress, i did some searching and found there was a way to do it in wordpress but thats not what i want.
You can populate $member array from db
You can use +fs.area.*+ regular expressions
But I think you want to create key/value table
key: +fs.area.glasgow+
value: Glasgow
key: +fs.area.Glasgowe+
value: Glasgow
and you want to select record from table for key and replace occurence with value in string.

Categories