Converting an array into a usable string - cakePHP - php

I'm working on a simple cakePHP form. I have a variable $user_name that's populated from my SQL tables.
I've affirmed with
echo '<pre>';
print_r($user_name);
echo '</pre>';
That the $user_name is correctly populated. I'm trying to use the variable that I've populated to auto-fill the following form field
echo $this->Form->input($modelNameField . '.name_of_customer', array('readonly'=> 'readonly','label'=> 'Customer Name', 'type'=> 'text', 'value'=> $user_name));
However, the field remains blank. Any suggestions?
Declaration for $user_name
App::import('model','customerInfo');
$customerInfos = new customerInfo();
$user_name = array();
$user_name = $customerInfos->get_name($id);
--
The get_name method
public function get_name($id)
{
return $this->find('first', array('fields' =>array('usr_name'),'conditions'=>array("customerInfo.id"=>$id)));
}
--
The print out from print_r($user_name); for $id =1 is
Array
(
[CustomerInfo] => Array
(
[usr_name] => Ted Jones
)
)

This is a pretty basic question.
The value option of the form helper needs to be a string, inputs don't know what to do with something like an array.
Your array has this structure
$user_name = array (
'CustomerInfo' => array(
'usr_name' => 'Ted Jones'
)
);
So the string value you want is in $user_name['CustomerInfo']['usr_name']. The form helper has no way of knowing that the string you wanted to put as value was in that part of that array.
Don't know why you tried doing an array_pop before doing an index definition. Accessing values inside an array in php is quite simple, so try to do the simple approach first and go for the array_ php functions if it's something more complicated.
For future reference, if you have an array or a variable and you want to use a value inside of it, do a debug or print_r to know how to access it. And if it's a matter of what types of data an option can take, the cake docs are a very good reference.

Related

Associative array of arrays

Ive come upon the following code and having trouble deciphering its use.
(changed up the variable names a bit for simplicity)
$fooo = array(
'dog' => array('pages', 'home'),
'cat' => array('users', 'login'),
'bird' => array('users', 'reset', 1),
);
I am familiar with associative arrays but have not seen this "nested array" implementation before.
Is this code creating an array of arrays?
For example, $fooo['dog'] returns an array where $dog[0]='pages' and $dog[1]='home'
That seems wrong.
Yes, this is an array of arrays. But it perhaps may be more accurate to describe it as an associative array with an indexed array for every value.
The following can be done with it:
$fooo['dog'] // gets array("pages", "home")
$fooo['bird'][0] // gets "users"
$fooo['cat'][1] // gets "login"
$fooo['cow'] = array('x', 'y'); // adds another value to the outer array
$fooo['bird'][] = 2; // $fooo['bird'] now equals array('users', 'reset', 1, 2)
There is nothing wrong with this code, but your example is lacking practicality. There is plenty of code that uses such structures though. For example, a logical representation of a menu with sub-menus on a website (which seems like the source of your sample), this data structure can then be looped to generate an HTML/CSS menu.

PHP function for adding sub-array to a multi-dim array

I am having trouble finding the right function for this.
I have a session array
$_SESSION['cart_items'][0] = (
'item_name'=>'some name',
'item_price'=>'29.99',
...
)
I need to append another array that has a specific key. The array is from a $_POST object.
$_POST['copy'] = array (
'name'=>'my name',
'office'=>'my office'
)
Appended session to look like this.
$_SESSION['cart_items'][0] = (
'item_name'=>'some name',
'item_price'=>'29.99',
...
'copy'=>array(
'name'=>'my name',
'office'=>'my office'
)
)
I tried array push but this gives me an indexed key for the appended array instead of 'copy'
I know the index of the parent array so i could create the new sub array and then loop the $_POST into it but that doesn't seem right either.
I might be missing the point - but cant you just do:
$_SESSION['cart_items'][0]['copy'] = $_POST['copy'];
$_SESSION['cart_items'][0][$key] = $_POST[$key]; // as you said you know the key .. is it only one?

dynamodb getitem using php - I only want to retrieve the value

I'm able to query my dynamodb tables, but I only want to retrieve the actual value. I don't want the formatting output. This same question has been answered here for Java, but I'm looking for the PHP solution:
Retrieving just the item value from a dynamodb table?
Here is my getitem query:
$response = $dynamodb->getItem(array(
"TableName" => $tableName,
"ConsistentRead" => true,
"Key" => array(
"userguid" => array(Type::STRING => $userguid)
),
"AttributesToGet" => array("token")
));
print_r($response["Item"]["token"]);
Here is the output:
Array
(
[S] => 9d194513
)
All I want to get back is:
9d194513
I assumed the logical answer would be to change the last line to:
print_r($response["Item"]["token"]["S"]);
But then my code doesn't return anything at all. Obviously still learning PHP here, and any help would be appreciated.
Don't use print_r function, just either echo your variables
echo $response["Item"]["token"]["S"];
or store in a variable for later use
$res_token = $response["Item"]["token"]["S"];
You can also use the getPath convenience method built into the Model object that the SDK returns for operations.
echo $response->getPath('Item/token/S');
For more information about working with responses in the SDK, see the Response Models page in the AWS SDK for PHP User Guide.
Though it's an old question but for anyone coming to this page for seeking answer, this is how I have done it.
getItem returns a Resultobject. You can call the get() function of the SDK, which will give you an array containing the exact value.
$params = [
"TableName" => "EpgApiAccessCount",
"Key" => $this->marshalJson('
{
"ApiUserKey": "' . $apiUserkey . '"
}
')
];
$result = $this->client->getitem($params);
if (!$result instanceof ResultInterface) {
return 0;
}
$item = $this->unmarshalItem($result->get("Item"));
return $item["AccessCount"];
Of course your value and table name will be different, and you can print or do anything else with the value.

PHP : Formatting multiple arrays for database (laravel)

I've got this input form: (Using the blade template engine with Laravel, but the html should be easy to understand from this and ultimately trivial)
{{ Form::text('amount[]', Input::old('amount')) }}
<?php echo Form::select('unit[]',
array(
'whole' => _('whole'),
'ml' => _('milliliter'),
'l' => _('liter'),
'dl' => _('deciliter'),
'mg' => _('milligram'),
'g' => _('gram'),
'kg' => _('kilogram'),
'tsp' => _('teaspoon'),
'tbs' => _('tablespoon'),
)) ?>
{{ Form::text('ingredient[]', Input::old('ingredient')) }}
I'm trying to format this to my database to return it in a string like this :
<li><span>1</span> liter red wine</li>
I'm considering making it a simpler form and eliminating the unit measurement forcing my users to type it in instead for flexibility, but I'll still have to cramp it all into one table for my database. The span tag is used in a jQuery to dynamically increase the number so is needed. I've been at this for quite a few days on and off but I can't crack how to do this.
Here is my formatting logic:
$amount = Input::get('amount[]');
$unit = Input::get('unit[]');
$ingredient = Input::get('ingredient[]');
for ( $i = 0, $c = count(Input::get('ingredient[]')); $i < $c; $i++ )
{
$ingredients .= '<li><span>'.$amount[$i].'</span>'.$unit[$i].' '.$ingredient[$i].'</li>';
}
and I send it using
$new = Recipe::create(array(
'title' => Input::get('title'),
'curiousity' => Input::get('curiousity'),
'ingredients' => $ingredients,
'steps' => Input::get('recipe')
));
I've tried numerous ways and I get errors like the $ingredients array not being defined or not being able to use [] in the variable. I tried defining the variable as an '$ingredients = '';' variable but that just produced an empty string. My problem must be in the logic.
Build your select list outside the form for brevity as well as (what I do anyway to keep controllers very slim) send the input to the model all at once.
$input = Input::all();
$new = Recipe::create($input);
Build the array for the ingredients elsewhere. In the model (perhaps?):
$ingredients = array(
'dbname1' => 'displayname1',
'dbname2' => 'displayname2'
);
And display it accordingly, then the form inputs should be sent over with the $input in an array that you can parse and then save to your db.
Other notes about Blade syntax. I'm not aware of a need to define the array brackets [].
{{Form::open()}}
{{Form::label('label1','Display Label 1')}}
{{Form::text('fieldname1',Input::old('fieldname1'))}}
With your ingredients array already built (your current syntax will produce a dropdown and I assume you want checkboxes)
{{Form::select('ingredientsFIELDNAME',$ingredients)}}
{{Form::close()}}
In your Input::all() array your ingredientsFIELDNAME field name will have an array if you've built it as checkbox instead of select. Hope this all makes sense.

Drupal 6: Only inserting first character of value to MySQL

I am working with a hook_form_alter on a CCK type (for you drupal-ers). I have a field that is normally a select list in my node form. However, in this instance, I want to hide the select list, and populate its value in the form with an SQL query.
Everything was going nicely. I could see that my desired value was showing up in the HTML source, so I knew my query was executing properly. However, when I submit the form, it only inserts the first character of the value. A few of my tests were values of 566, 784, 1004 - the column values were 5,7,1, respectively.
At first I thought it had to be the DB column attributes, but when I removed my form_alter that makes the field hidden and select the value manually, the correct value is inserted?!?
<?php
function addSR_form_service_request_node_form_alter(&$form, $form_state) {
if (arg(0) == 'user' && is_numeric(arg(1))) {
$account = arg(1);
$club = 2589;
$form['field_sr_account'] = array( '#type' => 'hidden',
'#value' => $club
);
}
}
?>
Can anyone see why only the first character would be inserted??
Note: I have tried deleting and recreating the column, using #value & #default_value, and it is still submitting only the first character of the integer. Also, I eliminated the submit handler as a possible cause by removing it, which still resulted in only one character being submitted
More Updates - Still Searching!
Okay, some good questions. Allow me to answer them:
The DB column type is integer(4)
The HTML the hook produces is :
input type="hidden" name="field_sr_account" id="edit-field-sr-account" value="2589"
Latest Update: I think the issue has been narrowed to the structure of the array. When I do var_dump on this field after the form alter has been processed, this is what I get..
[43] => Array
(
[#type] => hidden
[#default_value] => 2589
[#post] => Array
(
)
[#programmed] =>
[#tree] =>
[#parents] => Array
(
[0] => field_sr_account
)
[#array_parents] => Array
(
[0] => field_sr_account
)
[#weight] => 0.016
[#processed] => 1
[#description] =>
[#attributes] => Array
(
)
[#required] =>
[#input] => 1
[#process] => Array
(
[0] => form_expand_ahah
)
[#name] => field_sr_account
[#id] => edit-field-sr-account
[#value] => 2589
[#defaults_loaded] => 1
[#sorted] => 1
)
What is the structure of the field that I can set the form value to. It's gotta be something like what abhaga is suggesting..
Since the field you are trying to change was originally using a select widget, CCK will be looking for $form_state['values']['field_sr_account'][0]['value']. By setting the field to a #hidden type and setting #value, you will get its value in $form_state['values']['field_sr_account']. CCK will try to access the first element of that and end up with the first character of the value.
Updated: The easiest way to achieve what you need would be to do something:
function addSR_form_service_request_node_form_alter(&$form, $form_state) {
if (arg(0) == 'user' && is_numeric(arg(1))) {
$account = arg(1);
$club = 2589;
// Use this property to store the value to restore back
$form['#field_sr_account'] = $club;
$form['field_sr_account'] = array( '#type' => 'hidden','#value' => $club);
}
}
/*in your submit handler, restore the value in the proper format*/
$form_state['values']['field_sr_account'] = array('0' => array('value' => $form['#field_sr_account']));
Old Answer
One way of accomplishing what you are
trying to do is to copy the whole
$form['field_sr_account'] into
$form['#field_sr_account'] and then
provide the value through the SQL
query in the right format in the
submit handler itself.
Ok take a look at http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html#hidden versus http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html#value
It is also recommended you use value instead of hidden. You can find this info on http://api.drupal.org/api/drupal/developer--topics--forms_api.html/6
Also, type hidden is not allowed to have properties your assigning to it so this may be causing a problem. Any usage problems you may be having with the forms API should be answer in those resources as I"m still a little unclear on what you're trying to accomplish... specifically with the submit button.
Old answer:
Ok if I understand this correctly
$club is not being set correctly. If
the first result from your query is
the number your looking for then this
should work.
Try calling
<?php print_r(db_fetch_array($result)) ?>
to get a look at everything returned
from the query.
I'm a little unclear as to what is
being set incorrectly. If it's
#value inside your associated array
then the culprit must be the query.
If #value is being set correctly and
whatever your doing with it later may
be the culprit (not shown here). If
its the values in your $form_state I
don't see that your using $club here
at all.
Also, in your addSR_submit_function
you don't seem to be using the $form
variable, or using $club for anything
except for setting the message which
appears at the top of the page your on
when it's called.
I may need some further clarification
as to what exactly is going wrong.
Also, when you're calling
drupal_set_message function, are you
just doing this for debugging
purposes?
Shouldn't you check
drupal_set_message($form_state['values']['field_sr_account']);
instead of
drupal_set_message($club);
in addSR_submit_function ?
OK, just a quess: not sure what type db_result returns for your query, may be it has something to do with types conversions? So this is to make sure value is int.
'#value' => (int)$club
cinqoTimo, Out of curiosity what kind of CCK field is this? Is it a Integer, Decimal, Float? and do you have any special parameters on that field not normally on by default? What is the column type in the db?
Can you post the html output of the form. That might give a clue as to what might be going on.
Are you using any javascript to edit any values for this field?
Have you tried outputting the value results from addSR_form_service_request_node_submit hook? Any difference there.
Sorry for all the questions. Just thinking out loud as it seems you have covered most of your bases.

Categories