EntityMetadataWrapperException: Invalid data value given when setting file field - exception

Cannot set file_field in field_collection
Has node $order and field_collection called field_blueprints:
<?php
$entity_type = "field_collection_item";
$blueprint_obj = entity_create($entity_type, array('field_name' => "field_blueprints") );
$blueprint_obj->setHostEntity('node', $order);
$blueprint_entity = entity_metadata_wrapper($entity_type, $blueprint_obj);
date_default_timezone_set("UTC");
$blueprint_entity->field_blueprint_file->file->set((array)$file);
$blueprint_entity->field_blueprint_comment = (string) $file->filename;
$blueprint_obj->save();
node_save($order);
And this code throws error:
EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityDrupalWrapper->set() (line 736 of sites//all/modules/entity/includes/entity.wrapper.inc).
I have also tried:
$blueprint_entity->field_blueprint_file->set((array)$file)
$blueprint_entity->field_blueprint_file->set(array('fid'=>$file->fid))

You need to either pass the file object or an array with a fid key to make it work.
So it's either:
// Single value field
$blueprint_entity->field_blueprint_file = array('fid' => $file->fid);
// Multi-value field
$blueprint_entity->field_blueprint_file[] = array('fid' => $file->fid);
or:
// Single value field
$blueprint_entity->field_blueprint_file = $file;
// Multi-value field
$blueprint_entity->field_blueprint_file[] = $file;
Here is complete example using value(), set() and save() from Entity metadata wrappers page:
<?php
$containing_node = node_load($nid);
$w_containing_node = entity_metadata_wrapper('node', $containing_node);
// Load the file object in any way
$file_obj = file_load($fid);
$w_containing_node->field_attachment_content->file->set( $file_obj );
// ..or pass an array with the fid
$w_containing_node->field_attachment_content->set( array('fid' => $fid) );
$w_containing_node->save();
?>
Also when dealing with multiple-valued field (cardinality > 1), make sure you wrap it into extra array.

Related

Keep sort order of json columns in Laravel after inserting new Key Value pair

I have a key value pair that I am inserting into a model with the following:
public function addContactDetail(Request $request){
$data = $request->all();
$contact_id = $data['contact_id'];
$contact = Contact::find($contact_id);
$details = $contact->details;
$details[$data['label']] = $data['value'];
$contact->details = $details;
$contact->save();
return response()->json($contact);
}
After insert it sometimes puts it randomly in the middle of the object. How do I keep it at the end?
If you are using Laravel 5 or greater version,
Try casting your json column into array in eloquent using mutators. like this.
inside your Contact Model
protected $casts = [
'details' => 'array',
];
By doing so, I guess you will get what you want. Try it and let me know

Laravel update json column in postgresql

In postgresql db I have a column type json call it "activities". I would like to add there new (key -> value) pair. Without delete existing data.
At this moment my code look like this:
$user = User::with('userLife')->where(['id' =>$id])->first();
$user->userLife->confirmation_token = null;
$user->userLife->activities = ['emailConfirmed' => Carbon::now()->timestamp];
$user->email_confirmed = true;
$user->push();
In my Model I added:
protected $casts = [
'activities' => 'array',
];
But when I use this code all other data in column is removed and only 'emailConfirmed' appeared there.
So how to do it properly to just add new value in column without removing previous?
Thank you.
You should add it as new element through another variable:
$activities = $user->userLife->activities;
$activities['emailConfirmed'] = Carbon::now()->timestamp;
$user->userLife->activities = $activities;

Store a complex hash in Apache::Sessions:MySQL session

So, I'm trying to store a decoded JSON object into a tied apache session. This is my code:
$url="https://apilink";
$content = get($url);
die "Can't Get $url" if (! defined $content);
$jsonOb = decode_json($content);
%aprecords = %$jsonOb;
#Push the jsonOb in the session
$session{apirecords} = \%aprecords ;
$session{apirecords} does not store the %aprecords reference. Although, when I substitute the statement to $session{apirecords} = \%jsonOb ; , it stores apirecords in the sessions table but the reference to %jsonOb has no values in it.
PS:
I have tried the following and none of them seem to work:
1) $session{apirecords} = \%$jsonOb ;
2) $session{apirecords} = { %aprecords } ;
JSON object is perfectly well structured.
Code for tying a session:
tie %session, "Apache::Session::MySQL", $sessionID,
{
Handle => $dbObject,
LockHandle => $dbObject,
TableName => 'sessions',
};
#If a session ID doesn't exist, create a new session and get new session ID
if (!defined ($sessionID)){
$sessionID = $session{_session_id};
$session{count}=0;
}
A helping hand would be much much appreciated!
JSON Sample: https://jsonblob.com/feed3bba-f1cd-11e8-9450-2904e8ecf943
As pointed out by GMB. The blob size(64 KB) wasn't big enough for the JSON object.
The solution is to change blob datatype to mediumblob .

Undefined offset: 1, getting this error in looping

I have the following code:
$datas = $request->all();
if (!empty($datas)){
for ($i=1; $i<count($datas); $i++){
$value = [
'questionnaire_id' => $datas[$i]->questionnaires_id,
'question_id' => $datas[$i]->id,
'answer' => $datas[$i]->key
];
return $value;
}
}
I am getting error:
Undefined offset: 1
With input form:
<input type="" name="{{$question->id}}" value="{{$key}}">
How can I receive this value in controller?
You're assuming that $datas is a numerical array starting at index 1 with no gaps. That may not be the best assumption.
Based on my knowledge of request()->all(), it's going to return an associative array of all your user input so you wouldn't be able to access an $i key on $datas. Just because it may have 1 element, doesn't mean that index on the array will be 1.
Perhaps you want to retrieve a specific user input, for example, if you had a checkbox named checkbox, you may want to use request()->input('checkbox') instead of request()->all(), but I'd still assume your array keys would start from 0 and not 1.
When all else fails, set a breakpoint and use a debugger to see the value of $datas. If you don't have a debugger (which I highly recommend) you can use dd($datas); to die and dump the value.
You could try initialize the variable i = 0. Also make a dd($datas) to see what you are evaluating.
$datas = $request->all();
if (!empty($datas)){
for ($i=0; $i<count($datas); $i++){
$value = [
'questionnaire_id' =$datas[$i]->questionnaires_id,
'question_id' =$datas[$i]->id,
'answer' =$datas[$i]->key
];
return $value;
}
}

Can't Convert String into Integer - Extract Values from Hash within a Hash

I've found a bunch of topics that were very similar, but I'm just missing something. >.<
Basically, I'm trying to create the a variable called $db_url with the database credentials, host address, and name.
When trying to extract the value of a hash within a hash, I'm getting the following error:
`[]': can't convert String into Integer (TypeError)
on this line:
$credentials = $svc_details["credentials"]
Here's the context:
if (ENV['VCAP_SERVICES'])
$vcap = JSON.parse(ENV['VCAP_SERVICES'])
$svc_details = $vcap["mysql-5.1"]
$credentials = $svc_details["credentials"]
$host = $credentials["host"]
$username = $credentials["username"]
$password = $credentials["password"]
$database = $credentials["name"]
$port = $credentials["port"]
$db_url = "mysql://#{$username}:#{$password}##{$host}/#{$database}"
end
configure do
Sequel.connect($db_url || ENV['DATABASE_URL'] || 'sqlite://blog.db')
require 'ostruct'
Blog = OpenStruct.new(
:title => 'My Title',
:author => 'My Name',
:url_base => ENV['SITE_URL'],
:admin_password => 'My Password',
:admin_cookie_key => 'cookie_key',
:admin_cookie_value => 'cookie_value',
:disqus_shortname => nil
)
end
EDIT:
Here's an example of the JSON I'm trying to work:
{"mysql-5.1":[
{
"name":"mysql-4f700",
"label":"mysql-5.1",
"plan":"free",
"tags":["mysql","mysql-5.1","relational"],
"credentials":{
"name":"d6d665aa69817406d8901cd145e05e3c6",
"hostname":"mysql-node01.us-east-1.aws.af.cm",
"host":"mysql-node01.us-east-1.aws.af.cm",
"port":3306,
"user":"uB7CoL4Hxv9Ny",
"username":"uB7CoL4Hxv9Ny",
"password":"pzAx0iaOp2yKB"
}
},
{
"name":"mysql-f1a13",
"label":"mysql-5.1",
"plan":"free",
"tags":["mysql","mysql-5.1","relational"],
"credentials":{
"name":"db777ab9da32047d99dd6cdae3aafebda",
"hostname":"mysql-node01.us-east-1.aws.af.cm",
"host":"mysql-node01.us-east-1.aws.af.cm",
"port":3306,
"user":"uJHApvZF6JBqT",
"username":"uJHApvZF6JBqT",
"password":"p146KmfkqGYmi"
}
}
]}
I'm a programming newbie, so I apologize if I'm missing information or don't understand something.
The can't convert String into Integer (TypeError) error is because $svc_details is an array i.e. a list of entries where you use a numeric index to select the one you want but you're trying to use a string "credentials" as an index for the array.
If you look at your JSON you'll see that "mysql-5.1" at the start refers to an array (enclosed by the [] brackets) with 2 entries in it: the one that begins { "name":"mysql-4f700"... and the second one that begins { "name":"mysql-f1a13"...
This means that when you write:
$svc_details = $vcap["mysql-5.1"]
then $svc_details is an array with 2 elements so you can't go straight to the "credentials"
If you know whether you want the first or second entry then you can use $svc_details = $vcap["mysql-5.1"][0] or $svc_details = $vcap["mysql-5.1"][1] to select the appropriate section of the JSON, or you could write some code to find the entry with a particular name.