Wordpress - array not treated as array if manually entered - php

I am building a Wordpress site to track user progress. I have created a custom user text field called completed_sections which stores an array of sections of my website the user has completed. I am building that array like this:
<?php
if (is_user_logged_in()) {
global $completed;
$completed = get_field('completed_sections', 'user_'.$userID);
}
function update_completed_sections() {
global $completed;
global $userID;
$completedID = $_POST['quizID'];
$completionDate = $_POST['date'];
$completed_section[] = array(
'ID' => $completedID,
'date' => $completionDate
);
if (!empty($completed)) {
$combined = array_merge($completed, $completed_section);
} else {
$combined = $completed;
}
update_field('completed_sections', $combined, 'user_'.$userID);
}
add_action('wp_ajax_complete_section', 'update_completed_sections');
?>
This is working perfectly fine so long as I am using an AJAX call to fire the update_completed_sections function. The array that is added to the custom user field looks like this:
[{"ID":"58","date":"07\/31\/20"},{"ID":"79","date":"08\/03\/20"}]
However, if I go in to the user section of the Wordpress backend and manually try tp update the array, it breaks it. Even if I don't change anything and I just go in there and hit "Update User" it will cause Wordpress not to treat that field as an array anymore. Any ideas on how to make sure this field is treated as an array, even if it is manually entered through the Users section of Wordpress or through PHPMyAdmin?

Related

How to properly display a calculated value of a non-db field in the ListView?

In Suitecrm/SugarCRM 6.5
I need to modify the ListView. Showing the value of a field based on a certain condition.
In the Account module, the name field may be empty based on certain conditions, I require that when this occurs show the value of a custom field. To do this, first I tryied using 'customCode' + smarty as usual in Edit/Detail vies, but in several posts mention that this is not possible in the ListView. The concession is to use logic hooks + a non-db field to store the calculated field. Following this SO answer I have written the following:
Custom field at custom/Extension/modules/Accounts/Ext/Vardefs/custom_field_name_c.php
<?php
$dictionary['Account']['fields']['name_c']['name'] = 'account_name_c';
$dictionary['Account']['fields']['name_c']['vname'] = 'LBL_ACCOUNT_NAME_C';
$dictionary['Account']['fields']['name_c']['type'] = 'varchar';
$dictionary['Account']['fields']['name_c']['len'] = '255';
$dictionary['Account']['fields']['name_c']['source'] = 'non-db';
$dictionary['Account']['fields']['name_c']['dbType'] = 'non-db';
$dictionary['Account']['fields']['name_c']['studio'] = 'visible';
Label at suitecrm/custom/Extension/modules/Accounts/Ext/Language/es_ES.account_name_c.php
<?php
$mod_strings['LBL_ACCOUNT_NAME_C'] = 'Nombre de cuenta';
Logic hook entry at custom/modules/Accounts/logic_hooks.php
$hook_array['process_record'] = Array();
$hook_array['process_record'][] = Array(
2,
'Get proper name',
'custom/modules/Accounts/hooks/ListViewLogicHook.php',
'ListViewLogicHook',
'getProperName'
);
Logic hook at custom/modules/Accounts/hooks/ListViewLogicHook.php
<?php
class ListViewLogicHook
{
public function getProperName(&$bean, $event, $arguments)
{
if (empty($bean->fetched_row['name'])) {
$bean->account_name_c = $bean->fetched_row['person_name_c'];
} else {
$bean->account_name_c = $bean->fetched_row['name'];
}
// Here I also tried, but same result
// $bean->account_name_c = empty($bean->name) ? $bean->person_name_c : $bean->name;
}
}
listviewdefs.php at custom/modules/Accounts/metadata/listviewdefs.php
I added the field
'NAME_C' =>
array (
'width' => '20%',
'label' => 'LBL_ACCOUNT_NAME_C',
'default' => true,
),
After these modifications and repair I hope to see the field full with the right value. But it appears empty. I have verified that the logic hook is properly called, but the name andperson_name_c fields are always empty. In case it is relevant I have verified in Studio that the name fields in Account is typename I do not know what this means when it comes to obtaining its value.
I appreciate your comments
The problem is in the logic hook is due to first that the $bean does not have access to the custom fields, so I have to invoke them using $bean->custom_fields->retrieve(); Also the name field is always empty, I had to use DBManager to get only the name field.
The logic of the final logic hook is the following:
<?php
class ListViewLogicHook
{
public function getProperName($bean, $event, $arguments)
{
// Get access to custom fields from $bean
$bean->custom_fields->retrieve();
// Get access to name property using DBManager because $bean->name return null
$sql = "SELECT name FROM accounts WHERE id = '{$bean->id}'";
$name = $GLOBALS['db']->getOne($sql);
// Assign a value to non-db field
$bean->name_c = empty($name) ? $bean->nombre_persona_c : $name;
}
}
I was not familiar with the method $bean->custom_fields->retrieve() and at the moment I do not know why is empty the name field and I understand others fields remain empty.
I hope this is useful
We achieved that doing an after_retrieve hook, very fast and simple - This is taken from a working example.
public function RemoveCost(&$bean, $event, $arguments)
{
global $current_user;
include_once(‘modules/ACLRoles/ACLRole.php’);
$roles = ACLRole::getUserRoleNames($current_user->id);
if(!array_search("CanSeeCostRoleName",$roles)){
$bean->cost = 0;
$bean->cost_usdollar = 0;
}
}
All you need is to define and add this function to the module logic_hooks.php
You can even tailor down to specific calls:
if (isset($_REQUEST['module'],$_REQUEST['action']) && $_REQUEST['module'] == 'Opportunities' && $_REQUEST['action'] == 'DetailView')
As some times there are views you do want to show the field, for example quicksearch popup.

cakePHP pagination and passedArgs

I am trying to build in a "search" box on a results page in my cakephp app. The page uses the cakePHP pagination component to show and "page" results. This is perfect, but I am having difficulties to get the next part to work.
The desired outcome:
A cakephp form (post) with an input box and a couple of select boxes, including a date selector so that I can select between dates. The user should be able to populate these fields and submit
On submit, the user selection should change the cakePHP pagination conditions in the controller
In the view I want the pagination bar to keep record of the user selection, so that when I filter through different pages, it keeps the users search. I understand this can be achieved using $this->passedArgs, hence why I am using post and not get.
The code:
// Form:
<?php
echo $this->Form->create('search', array('class' => false));
echo $this->Form->input('searchFor');
echo $this->Form->input('dateFrom');
echo $this->Form->input('dateTo');
echo $this->Form->end();
?>
// Controller:
if($this->request->is("post")) {
$filters = $this->request->data["search"];
$this->passedArgs["searchFor"] = $filters["searchFor"];
$this->passedArgs["dateFrom"] = $filters["dateFrom"]." 00:00:00";
$this->passedArgs["dateTo"] = $filters["dateTo"]." 00:00:00";
// Assign search parameters:
if($this->passedArgs["searchFor"] != "") {
$conditions["Model.field LIKE"] = "%".$this->passedArgs["searchFor"]."%";
}
$conditions["Model.created >="] = $this->passedArgs["dateFrom"];
$conditions["Model.created <="] = $this->passedArgs["dateTo"];
} else {
$conditions = array("Result.status_id >=" => 12);
}
$this->paginate = array(
'conditions' => $conditions,
'order' => array('Result.created ASC'),
'limit' => 20
);
$this->set("results",$this->paginate("Model");
// The view file:
<?php
$this->Paginator->options(array('url' => $this->passedArgs));
?>
Where I am now:
The initial page loads with all of the results
When I populate the search boxes it does return my results
The problem:
I am convinced the way I am doing it is incorrect as I now need to do 2 checks, a) being if results has been posted and b) check if there is passedArgs available. I am 100% convinced this is not the right way of doing it.
Let's say I have 2 free form fields for search, say name and surname, if I leave surname blank my url would be written as below, and this does not look or appear to be correct. That means I have to assign default values to ensure the items below does not happen, which does not appear to be very dynamic.
http://localhost/site/controller/action/surname:0/name:John/date:0/
On refresh it says the page does not exist because the posted values is not available anylonger.
usually I proceed like this in the controller:
//transform POST into GET
if($this->request->is("post")) {
$url = array('action'=>'index');
$filters = array();
if(isset($this->data['searchFor']) && $this->data['searchFor']){
//maybe clean up user input here??? or urlencode??
$filters['searchFor'] = $this->data['searchFor'];
}
//redirect user to the index page including the selected filters
$this->redirect(array_merge($url,$filters));
}
$conditions = array();
//check filters on passedArgs
if(isset($this->passedArgs["searchFor"])){
$conditions["Model.field LIKE"] = "%".$this->passedArgs["searchFor"]."%";
}
//paginate as normal
$this->paginate = array(
'conditions' => $conditions,
'order' => array('Result.created ASC'),
'limit' => 20
);
The idea is to transform the POST sent by your form into GET. so you wont have problems with the paginator nor the refresh
Hope this helps
What you want can be done a lot more simple and DRY by using this search plugin.
It automates what you want more or less plus it already can do more than your code.
So I suggest you to use the plugin directly or take a look at it how it does the trick. :)

Drupal: How to display part of an author's profile in a node

I have been trying to do display a custom field I created in the manage fields section of user accounts for nodes in addition to the profile page. The problem I am having with this code is that it will display the first field it finds and display that for every user, not the field for that particular user.
And ideas? I believe it's finding the first value in the array and not the value for the particular user in the array.
Here is m setup so far:
Added this to my template.php of my theme:
function mythemename_preprocess_node(&$vars) {
global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$team = field_get_items('user', $user, 'field_team');
if ($team) {
$vars['field_team'] = $team[0]['value'];
}
}
Then, added this to my node.tpl.php in order to display it on nodes.
if (isset($field_team) && !empty($field_team)) :
echo '$field_team.'</div>';
endif;
UPDATE:
Found my own aswer here:
http://drupal.org/node/1194506
Code used:
<?php
$node_author = user_load($node->uid);
print ($node_author->roles[3]);
print ($node_author->field_biography['und'][0]['value']);
?>
You can use drupal's 'Author Pane' module for that. Try this:
http://drupal.org/project/author_pane

drupal adding a user reference field to a template

I have a template file that I want to print a the cck user reference form field on.
Is this possible? Note, this is not the field value, but the field form. Also asking for just the field, not creating a form first and then using drupal_get_form()
Thanks!
Edit: If this is not possible that's fine too, I just would like to know
Edit2: i just need the autocomplete mechanism so I can grab the uid in js from searching for the username
If you just need autocomplete mechanism I would suject you to use jQuery autocomplete plugin - http://docs.jquery.com/Plugins/autocomplete.
you can just output in the template something like that:
print '<input type="text" id="user-autocomplete">';
Then in javascript code
$(document).ready('function(){
$('#user-autocomplete').autocomplete(some-ajax-url-here)
}');
you also will need to create an ajax callback page somewhere in your module:
function YOUR_MODULE_NAME_menu(){
$items = array();
$items['user-autocomplete-ajax-page'] = array(
'title' => 'AJAX:get user',
'page callback' => 'get_user'
);
}
function get_user(){
$sql = 'SELECT uid, name FROM {users} WHERE name LIKE ("%s")';
$result = db_query($sql,$_GET['request']);
$res_str = '';
while($object = db_fetch_object($result)){
$res_str .= $object->name.' ['.$object->uid."]\n";
}
print $res_str;
}
I didn't test the code, but I guess it should work, may be with some minor changes.

Why can't I see the database updates unless I refresh the page?

Hmmmmm I worked on some PHP code that pulls stock levels from my supplier and inserts the stock level into the database based on the product's SKU. I've inserted it into the class.product.php file which contains all the code used for the individual product page. The issue I'm having is that when the product page loads, it doesn't show the updated inventory levels unless you hit refresh. I've moved the code all over the place and can't get it to update the database and have the updated number loaded before the page is displayed.
Even when placed before all other code, I still have to refresh the page to see the update. I don't know what else to do about this. I feel like perhaps, I don't truly understand how PHP loads code. I've been working on this every day for weeks. I tried running it as an include file, on a separate page, at the top, in the middle, all over the place.
In the class file, it looks like I have the code before it calls the code to display the stock levels, that's why I'm so confused as to why it won't load the updates.
Any thoughts on why I'm unable to see the changes unless I refresh the page?
Thanks!
PHP loads the content when you request it ,
so opening a page gets the content ONCE,
The thing you want to do to get data updated is have AJAX calls to a php function that return data in JSON or XML format
Here you can see some examples but consider googling around for more detailed examples.
The problem was my code was not running until after the code to get and display the product data because I was using info from the product data that was only being called once. So the product data had be be called first in order for my code to run. So to fix this, I had to create a new function that would get the sku and pass it to my code before the code that called the product data to be displayed on the page. I copied the existing function to get the product data, renamed it to GetRealTimeStockLevels and added my code to the bottom of it. I put the call for the function above the call for the product data and it worked like I wanted. I'm glad I got this worked out, now I can add the same feature to the checkout page.
Below is the function call at the start of the page and then the function I created to run my update code.
public function __construct($productid=0)
{
// Get the stock level from supplier and update the database
$this->_GetRealtimeStockLevels($productid);
// Load the data for this product
$this->_SetProductData($productid);
public function _GetRealtimeStockLevels($productid=0)
{
if ($productid == 0) {
// Retrieve the query string variables. Can't use the $_GET array
// because of SEO friendly links in the URL
SetPGQVariablesManually();
if (isset($_REQUEST['product'])) {
$product = $_REQUEST['product'];
}
else if(isset($GLOBALS['PathInfo'][1])) {
$product = preg_replace('#\.html$#i', '', $GLOBALS['PathInfo'][1]);
}
else {
$product = '';
}
$product = $GLOBALS['ISC_CLASS_DB']->Quote(MakeURLNormal($product));
$productSQL = sprintf("p.prodname='%s'", $product);
}
else {
$productSQL = sprintf("p.productid='%s'", (int)$productid);
}
$query = "
SELECT p.*, FLOOR(prodratingtotal/prodnumratings) AS prodavgrating, pi.*, ".GetProdCustomerGroupPriceSQL().",
(SELECT COUNT(fieldid) FROM [|PREFIX|]product_customfields WHERE fieldprodid=p.productid) AS numcustomfields,
(SELECT COUNT(reviewid) FROM [|PREFIX|]reviews WHERE revstatus='1' AND revproductid=p.productid AND revstatus='1') AS numreviews,
(SELECT brandname FROM [|PREFIX|]brands WHERE brandid=p.prodbrandid) AS prodbrandname,
(SELECT COUNT(imageid) FROM [|PREFIX|]product_images WHERE imageprodid=p.productid) AS numimages,
(SELECT COUNT(discountid) FROM [|PREFIX|]product_discounts WHERE discountprodid=p.productid) AS numbulkdiscounts
FROM [|PREFIX|]products p
LEFT JOIN [|PREFIX|]product_images pi ON (pi.imageisthumb=1 AND p.productid=pi.imageprodid)
WHERE ".$productSQL;
if(!isset($_COOKIE['STORESUITE_CP_TOKEN'])) {
// ISC-1073: don't check visibility if we are on control panel
$query .= " AND p.prodvisible='1'";
}
$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
$row = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
if (!$row) {
return;
}
$this->_product = $row;
$this->_prodid = $row['productid'];
$this->_prodname = $row['prodname'];
$this->_prodsku = $row['prodcode'];
$GLOBALS['CurrentProductLink'] = ProdLink($this->_prodname);
$server_url = "http://ms.com/fgy/webservices/index.php";
$request = xmlrpc_encode_request("catalog.getStockQuantity", array($this->_prodsku));
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml",
'content' => $request
)));
$file = file_get_contents($server_url, false, $context);
$response = xmlrpc_decode($file);
$query = sprintf("UPDATE [|PREFIX|]products SET prodcurrentinv='$response' where prodcode='%s'", $GLOBALS['ISC_CLASS_DB']->Quote($this->_prodsku));
$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
}

Categories