MODX parse error function implode (is it me or modx?) - php

Update 4-June-2010: This appears to be a bug in MODx v 1.0.3, nothing to do with the implode function but rather a problem with mis-matched datatypes in the resulting filter clause. Bug has been filed with JIRA: MODX-2035.
Hi, I cannot for the life of me figure this out, maybe someone can help.
Using MODX a form takes user criteria to create a filter and return a list of documents. The form is one text field and a few checkboxes. If both text field and checkbox data is posted, the function works fine; if just the checkbox data is posted the function works fine; but if just the text field data is posted, modx gives me the following error:
Error: implode() [function.implode]: Invalid arguments passed.
I've tested this outside of modx with flat files and it all works fine leading me to assume a bug exists within modx. But I'm not convinced. Here's my code:
<?php
$order = array('price ASC'); //default sort order
if(!empty($_POST['tour_finder_duration'])){ //duration submitted
$days = htmlentities($_POST['tour_finder_duration']); //clean up post
array_unshift($order,"duration DESC"); //add duration sort before default
$filter[] = 'duration,'.$days.',4'; //add duration to filter[] (field,criterion,mode)
$criteria[] = 'Number of days: <strong>'.$days.'</strong>'; //displayed on results page
}
if(!empty($_POST['tour_finder_dests'])){ //destination/s submitted
$dests = $_POST['tour_finder_dests'];
foreach($dests as $value){ //iterate through dests array
$filter[] = 'searchDests,'.htmlentities($value).',7'; //add dests to filter[]
$params['docid'] = $value;
$params['field'] = 'pagetitle';
$pagetitle = $modx->runSnippet('GetField',$params);
$dests_array[] = ''.$pagetitle.'';
}
$dests_array = implode(', ',$dests_array);
$criteria[] = 'Destinations: '.$dests_array; //displayed on results page
}
if(is_array($filter)){
$filter = implode('|',$filter);//pipe-separated string
}
if(is_array($order)){
$order = implode(',',$order);//comma-separated string
}
if(is_array($criteria)){
$criteria = implode('<br />',$criteria);
}
echo '<br />Order: '.$order.'<br /> Filter: '.$filter.'<br /> Criteria: '.$criteria;
//next: extract docs using $filter and $order, display user's criteria using $criteria...
?>
The echo statement is displayed above the MODX error message and the $filter array is correctly imploded.
Any help will save my computer from flying out the window.
Thanks

I think your problem lies here :
$dests_array = implode(', ',$dests_array);
$dest_array may be empty and not even initialized if $dests is empty.

This really should be posted in the MODx forums. I love stackoverflow, but MODx is more niche.

Related

PHP - Output array value that contains a specific text marker

I'm using a function to output a collection of products in Shopify, onto a WordPress page.
I've got most of the data displaying correctly, except a custom value that is entered as a tag in Shopify. Using the api, I'm then trying to get this specific tag for the product subtitle which is formatted with att:Subtitle: before each product custom value/text.
This is the code I have got to (I've commented other unsuccessful attempts in the middle) - this is inside the overall code to show the 4 products in the Shopify collection:
// Using tags to output custom data from products
$tags = $current_product['tags'];
// $tags is a string, this turns the values into an array
$product_tags = explode(',', $tags);
// Evaluate if there is a string with att:Subtitle in the product tags
// https://tecadmin.net/check-string-contains-substring-in-php/
$subtitle_attribute_key = "att:Subtitle:";
if (strpos($tags, 'att:Subtitle:') !== false) {
// Returns a numbered value corresponding to my subtitle attribute
// $key = array_search($subtitle_attribute_key, $product_tags);
$sub = strpos($tags, $subtitle_attribute_key);
// Turns the numbered value into a text value
// $numArray = explode(" ", $sub);
// var_dump($numArray);
$value = print_r($sub, true);
// $value = array_search("att:Subtitle:",$product_tabs);
// $value = array_search("att:Subtitle:", $tabs); // Warning: array_search() expects parameter 2 to be array, null given
// $result = $product_tags['$value']; // my attempt to return the text
// Remove att:Subtittle: in front of the subtitle value to output the clean final value
$subtitle = ltrim($value, 'att:Subtitle:');
}
So far it comes out as a number value where I'm displaying $subtitle... but I can't figure out how to display the custom text value instead.
Any ideas?
Thanks
EDIT: I am working with products that have multiple tags and I do not control these. Out of the tags I'm trying to find the one that starts with att:Subtitle: but only show the custom value after that marker.
When I echo $tags, the ist comes out something like this:
att:Benefit:balance, att:Perfect:Combination Skin, att:Size: 1.8 oz, att:Subtitle: Multi-Tasking Product, Key Ingredient 1, Key Ingredient 2, Essentials, meta-related-product-xyz, meta-related-product-brandname
They will all have a different list of tags
Of course it comes out as a number. You're getting a number from the strpos() and ultimate trying to run ltrim() on it.
If you're expecting the desired text to be in $tags immediately following 'att:Subtitle:' and have nothing else in that string, $subtitle = substr($tags, strpos('att:Subtitle:') + strlen('att:Subtitle:')); should give it to you. If you're expecting it to possibly be an element in the $product_tags array, need to loop (I'm assuming it shows up once, at most):
foreach ($product_tags as $product_tag) {
if (strpos($product_tag, 'att:Subtitle:') !== false) {
$subtitle = substr($product_tag, strpos($product_tag, 'att:Subtitle:') + strlen('att:Subtitle:'));
break;
}
}
So for what I understand you're trying to get rid of 'att:Subtitle:' from the tags on your products descriptions? maybe you should try replacing that value on your tags array
// Using tags to output custom data from products
$tags = $current_product['tags'];
// $tags is a string, this turns the values into an array
$product_tags = explode(',', $tags);
// Get rid of attribute on product tag
for($i = 0; $i < count($product_tags); $i++){
$subtitle = str_replace(':att:Subtitle','',$product_tags[i]);
}

Woocommerce Order / AFC get_sub_field / get_sub_field_object (array)

Have setup ACF repeater field that stores various amount of tracking numbers in the order. Having 0 success with retrieving this information so need some advice.
Am using this to put information in subfields and it does the job
foreach ($base->DocumentLines->DocumentLine as $item) {
foreach ($item->MiscData as $misc) {
foreach ($misc->PackageNo as $package) {
$trackno = (string)$package->TrackingNo;
update_post_meta("$order_id", $field_rep, $count);
$sub = $count +1;
update_sub_field(array($field_key_rep, $sub, $field_key_sub), $trackno, "$order_id");
$count = $count + 1;
update_field($field_key, $trackno, "$order_id");
}
}
}
This works well, but then i need to retrieve this numbers and write em out. They are getting included in an email so need to retrieve the data outside of order.
Before rebuilding the function to be able to handle multiple numbers i did use a single field and could retrieve the information with
get_post_meta($order_id, 'tracking', true);
Feels like i have been trying everything now but got absolutely nothing.
Image from one of the orders, in this one it’s 10 tracking numbers but it varies from 1 to 20 if it's to any help.
The feeling when you realize after 10 hours that your missed a capital letter in sub field name.
Just wanted to submit my solution and hopefully it can help someone else having issues with ACF Repeater fields + Woocommerce
For my specific case i did make a function that could extract all the tracking numbers my function above did add from XML files.
$function trackingNo($postID) {
$field_rep = 'trackingNo';
$field_sub = 'no';
if (have_rows($field_rep, $postID)) {
$trackingNo = array();
// loop through the rows of data
while (have_rows($field_rep, $postID)):
the_row();
// Add to array
$trackingNo[] = get_sub_field($field_sub);
endwhile;
$foo = implode('&consignmentId=', $trackingNo);
$bar = 'urlzz/tracktrace/TrackConsignments_do.jsp?&consignmentId=';
$value = $bar . $foo;
return $value;
}
}
Any advice for improvement is always welcome, my PHP is so'n'so :)

String from an array from an array from the database

Okay so, first of all, I searched through the www for this question, and I found some question related to arrays but not exactly to mine.
Okay so as you may know, paypal only allows one custom variable to be $POST but I need to gather the product id AND the quantity of the item bought. So to do this I made my custom variable into something that would get the post like (25-1,12-3,13-4) it means, the user bought 3 items(separated by commas), where the first number is the product id (then the separator '-' comes in) and the second one is the quantity. (so they're all in the same row and column)
Now my problem is displaying it from the database. I need to get the product name and details that's why I need to separate the numbers from each array as a string and fetch the data from the database for the information of the product. (I'm using an older version of php anyway, 5.2, I guess.)Now the problem is:
1.) It returns the word 'Array' (literally) so it would say like ArrayArrayArray
2.) How do I explode/separate those data so I can get it because I need the product ID to fetch some other data... I tried exploding it into array, then exploding it again but doesn't work (most likely my code is wrong?)
Here is my code: (I've already connected to the database)
$data = mysql_query("SELECT * from transactions") or die(mysql_error());
/* My table tag and headers goes here */
while($info = mysql_fetch_array( $data )) {
echo "<tr>";
echo '<td>' . $info['id'] . '</td>';
echo "<td>";
$array = $info['product_id_array'];
$explode_array = explode(",", $array);
foreach($explode_array as $explode_more){
$explode_more = explode("-", $explode_array);
$prod_id = $explode_more[0];
$quantity = $explode_more[1];
print_r($prod_id); //should echo the 25 in the array (25-1), right?
print_r($quantity);
}
echo"</td>";
echo"<tr>";
}
If only paypal would allow multiple custom variables T_T Thank you guys. Forgive me if I can't express my question very well or my language is not good, as english is not my first language :), Good day!
Your variable names are mixed up. Inside the foreach-loop, you should do something like this
foreach($explode_array as $explode_more){
$explode_even_more = explode("-", $explode_more);
$prod_id = $explode_even_more[0];
$quantity = $explode_even_more[1];
print_r($prod_id); //should echo the 25 in the array (25-1), right?
print_r($quantity);
}
Note, that $explode_more is used inside the loop and $explore_array is left as is.
Separate this in multiple tables, never store non-atomic values in 1 column.
Certainly not when they have relation with another table.
Suppose you want to know the sales from a certain product in some period.

PHP4 Valid code stopped working in PHP5?

Okay, so I have some code that worked fine in PHP4 but since upgrading to PHP5 it does not produce the results I want.
This is some code I have that displays some news posts in a nice 3-column format. It checks where the news post shall go and adds it to the corresponding array. Then it prints out the array.
Assume $data is an array containing news post content such as title, date and content.
// Add to columns.
for($i=0; $i<sizeof($data); $i++) {
// Convert Date Format.
$old_date = $data[$i]['post_date'];
$middle = strtotime($old_date);
$new_date = date('F d, Y', $middle);
// Calculate amount of text to display.
if(strlen($nh->getContents($data[$i]['post_content'])) > 100) {
$post_content = $nh->getSnippet($data[$i]['post_content'], 500, TRUE);
$post_content .= "...<br /><br />Read more...";
} else $post_content = $nh->getContents($data[$i]['post_content']);
// Setup content variable.
$content = "
<div class=\"content post\">
<h1 class=\"title\">{$data[$i]['post_title']}</h1>
<h2 class=\"subtitle\">Posted on {$new_date}</h2>
{$post_content}
</div>
";
// Add to appropriate column array.
if(in_array($i, $leftIDs)) $left[] = $content;
else if(in_array($i, $midIDs)) $mid[] = $content;
else if(in_array($i, $rightIDs)) $right[] = $content;
}
The problem is where I have the $content variable and add it to an array stack. For some reason it is not adding it. When dumping $content it displays the news contents--so the data is being fetched properly from the $data array.
Printing out the $left, $mid, and $right arrays returns empty arrays. I've checked if the if-statements at the bottom were returning true--and they were. So why is my data not being added?
EDIT: The entirety of my code can be found here
P.S.: The reason for the arrays xxID is to figure out in which column the current news post will go. Then I just print everything out so that everything is displayed nicely.
Old: old
New: new
UPDATE: The lines that add the closing </div> to the end of the array: $leftWrapper = sizeof($left) - 1; $left[$leftWrapper] = '</div>'; was overwriting the content that was added to array... odd because it worked in PHP4.... What a silly reason for not working. Thanks everyone for your input.
My bet is you are a victim of http://php.net/manual/en/ini.core.php#ini.register-globals being defaulted to off in PHP5, as it should be since it can be security risk leaving them on. I would verify that, if that is true the solution can be complicated or easy, depending if you want security or not. In order to verify, you will need to either post a bit more code, or test on your server.

autocomplete search form cakephp

Hey there, I'm a total newbie and I'm looking for a way to have a search box with autocomplete just like google does.
I've searched and the best prospect that I've found seems to be http://www.pengoworks.com/workshop/jquery/autocomplete.htm which I found on a forum. The guy who suggested it says he uses it with http://code.google.com/p/searchable-behaviour-for-cakephp/ which is dead on because I've managed to install searchable on my last attempt at figuring out cakephp.
The thing is, I've not used much javascript before and I'm a bit confused as to what exactly I'm meant to be doing. The documentation with the autocomplete codes doesn't go into any detail that I can understand.
If we assume that I manage to get searchable behaviour installed correctly, could any kind person explain to me how I would go about making the autocomplete work?
It says to just use:
$("selector").autocomplete(url [, options]);
eg:
$("#input_box").autocomplete("autocomplete_ajax.cfm");
Autocomplete expects an input element with the id "input_box" to exist. When a user starts typing in the input box, the autocompleter will request autocomplete_ajax.cfm with a GET parameter named q
thats the bit I don't get. Where am I meant to put that? And once I've put it somewhere then do I just need to name one of my inputs "input_box"?
thanks in advance.
There are three steps:
1) create a totally normal form with an input field, using the Html helper in your view:
// app/views/foo_bars/search.ctp
<?php
echo $this->Form->create('FooBar');
echo $this->Form->input('field');
echo $this->Form->end('Submit');
?>
2) Have a jquery autocomplete fired:
// app/views/foo_bars/search.ctp
<?php
echo $this->Html->scriptBlock(
.'$("#FooBarField").autocomplete({'
.'source:"/foo_bars/find",'
.'delay: 100,'
.'select:function(event,ui){$(this).parent().parent().children("input").val(ui.item.id);},'
.'open:function(event,ui){$(this).parent().parent().children("input").val(0);}'
.'});'
array('inline' => false));
?>
3) Query a database through a controller to get possible values:
// app/controllers/foo_bars_controller.php
<?php
public function find() {
if ($this->RequestHandler->isAjax()) {
$this->autoLayout = false;
$this->autoRender = false;
$this->FooBar->recursive = -1;
$results = $this->FooBar->find('all', array('fields' => array('id', 'name'), 'conditions' => array('name LIKE "%'.$_GET['term'].'%"')));
$response = array();
$i = 0;
foreach($results as $result){
$response[$i]['value'] = $result['FooBar']['name'];
$response[$i]['id'] = $result['FooBar']['id'];
$i++;
}
echo json_encode($response);
}
}
?>
echo $this->Html->scriptBlock(
'$("#FooBarField").autocomplete({'
.'source:"/Search/find",'
.'delay: 100,'
.'select:function(event,ui){$(this).parent().parent().children("input").val(ui.item.id);},'
.'open:function(event,ui){$(this).parent().parent().children("input").val(0);}'
.'});'.
array('inline' => false));

Categories