How to translate a Drupal Bean programmatically? - drupal-7

I've looked everywhere, but I can't find a way to translate a bean. They rely on entity_translation, but this doesn't seem to work:
$form_state['build_info']['args'] = array ( 0 => $bean );
$form_state['form_id'] = 'bean_form';
$form_state['entity_translation'] = array(
'form_langcode' => $newLangcode,
'source_langcode' => 'en',
'is_translation' => 1,
);
drupal_form_submit('bean_form', $form_state);
It doesn't do anything. Any ideas what I could be missing? Or is there perhaps a better way than trying to submit the form?
My attempt is basically just an attempt at trying to mimmick what happens on this page:
/block/MY_BLOCK/edit/add/en/es

Took me forever to find this:
$translation = array(
'translate' => 0,
'status' => 1,
'language' => $langCode, // here is the language you're translating to
'source' => 'en',
);
$bean = bean_load($bid);
$handler = entity_translation_get_handler('bean', $bean);
$values = array (
// i add the default values here, but you can add whatever you want
);
$handler->setTranslation($translation, $values);
bean_save($bean);

Related

How to get meta value in wp_attachment_metadata

want to get wp_attachment_metadata in my own way. I want to get the file name :
a:5:{s:5:"width";i:500;s:6:"height";i:500;s:4:"file";s:25:"2016/08/sprite_1500ml.jpg";s:5:"sizes";a:5:{s:9:"thumbnail";a:4:{s:4:"file";s:25:"sprite_1500ml-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:25:"sprite_1500ml-300x300.jpg";s:5:"width";i:300;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:14:"shop_thumbnail";a:4:{s:4:"file";s:25:"sprite_1500ml-180x180.jpg";s:5:"width";i:180;s:6:"height";i:180;s:9:"mime-type";s:10:"image/jpeg";}s:12:"shop_catalog";a:4:{s:4:"file";s:25:"sprite_1500ml-300x300.jpg";s:5:"width";i:300;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:11:"shop_single";a:4:{s:4:"file";s:25:"sprite_1500ml-400x400.jpg";s:5:"width";i:400;s:6:"height";i:400;s:9:"mime-type";s:10:"image/jpeg";}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:0:"";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"0";s:8:"keywords";a:0:{}}}
Well, I am stuck. I don’t know how to separate that array. Anyone knows how to separate that array in order I can get the file name (url file).
my code now :
$command = $_GET['command'];
switch ($command) {
case 'list_product':
$loop = new WP_Query(
array(
'post_type' => 'product'
)
);
if( $loop->have_posts() ) :
$data = array( "api_status" => 1, "api_message" => "success");
$meta = array();
while ( $loop->have_posts() ) : $loop->the_post();
$meta[] = array(
"id" => get_the_ID(),
"post_name" => get_the_title(),
"stock_status" => get_post_meta( get_the_ID(), '_stock_status', true ),
"price" => get_post_meta( get_the_ID(), '_price', true ),
"reguler_price" => get_post_meta( get_the_ID(), '_regular_price', true ),
"image" => get_post_meta( get_the__ID(), '_wp_attachment_metadata', true ),
);
endwhile;
endif;
echo json_encode($meta);
break;
i mean when i use :
"image" => get_post_meta( get_the__ID(), '_wp_attachment_metadata', true ),
my result doesnt show anything
what improvement in my code so its can work like what i want ?
If you want an image url, I show you another way to to this. I suppose you want the post thumbnail of a spicific post.
// First we get the image id
$post_thumbnail_id = get_post_thumbnail_id( get_the_ID() );
// Then we get the image data, we will get an array with some informations
$image = wp_get_attachment_image_src( $post_thumbnail_id, 'large' );
// the image url is the first index of this array
$image_url = $image[0];
In this example you get the image url for the largeversion. If you want antoher size, just change it to e.g. meidum or full. Read the documentation of wp_get_attachment_image_src() for more details.
This code must be placed inside the loop. Make sure that get_the_ID() returns the current POST ID. Make also sure that the POST have a post thumbnail.
Basically you can get an image url if you have an ID of an attachmend post (image).

save is not working in cakeph when all is okay

My code:
$this->PackageCustomer->id = $customer_id;
$data['PackageCustomer'] = array(
'shipment' => 2,
'comments' => $this->request->data['Ticket']['content'],
'shipment_equipment' => $this->request->data['Ticket']['shipment_equipment'],
'shipment_note' => $this->request->data['Ticket']['shipment_note'],
'issue_id' => $this->request->data['Ticket']['issue_id']
);
pr($data); exit;
$this->PackageCustomer->save($data['PackageCustomer']);
//var_dump($this->PackageCustomer->invalidFields());
// pr($this->PackageCustomer->error);
echo $this->PackageCustomer->getLastQuery(); exit;
I inspect array $data. Data is being revived properly. And getLastQuery function is:
function getLastQuery() {
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
Which is defined in appModel. I am using cakephp 2.6.9. But last query is :COMMIT which does not make any sense. I check My model convention. It is okay. Now what is the problem in my code?
Try this::
$this->PackageCustomer->id = $customer_id;
$data['PackageCustomer'] = array(
'shipment' => 2,
'comments' => $this->request->data['Ticket']['content'],
'shipment_equipment' => $this->request->data['Ticket']['shipment_equipment'],
'shipment_note' => $this->request->data['Ticket']['shipment_note'],
'issue_id' => $this->request->data['Ticket']['issue_id']
);
pr($data); exit;
$this->loadModel('PackageCustomer');
$this->PackageCustomer->save($data['PackageCustomer']);
//var_dump($this->PackageCustomer->invalidFields());
// pr($this->PackageCustomer->error);
echo $this->PackageCustomer->getLastQuery(); exit;
If the above code doesn't work I need the following answered to help further...
I need bit more information can you confirm the following:
What is the name of the table you are trying to save to?
What is the name of the class relating the to the table you are trying to save to?
Are you trying to edit or create a new record in this table?

Is there an alternative to neighbors in Cakephp

I am coverting my app over to cakephp 3.0 and I am having trouble finding an alternative to using neighbors in the find method.
I need to find the next record in the associated table and neighbors was a great way to do it.
//Open courses
$options = [
'conditions' => ['Employees.user_id' => 1, 'CoursesEmployees.completed' => false],
'limit' => 3,
'contain' => 'Employees'
];
$recentOpen = $this->CoursesEmployees->find('all', $options)->toArray();
// get next module for each open course
foreach ($recentOpen as $key => &$value) {
$currentModule = $value['CourseModule']['id'];
$neighbors = $this->CoursesEmployees->CourseModules->find(
'neighbors',
['field' => 'id', 'value' => $currentModule]
);
$value['CourseModule']['next_module'] = $neighbors['next']['CourseModule']['name'];
};
Another issue with the code I discovered is that $this->CoursesEmployees->find('all', $options)->toArray(); seems to return a complex array with everything cakephp uses to query the table and not the actual results like I got with cakephp 2. I added the ->toArray() as recommended with 3.0
Because I loathe "Answers" that simply point to a URL where you may or may not be able to decipher a half answer today, but could be gone tomorrow, here is my replacement custom finder:
// In src/Models/Table/ExampleTable.php
/**
* Find neighbors method
*/
public function findNeighbors(Query $query, array $options) {
$id = $options['id'];
$previous = $this->find()
->select('id')
->order(['id' => 'DESC'])
->where(['id <' => $id])
->first();
$next = $this->find()
->select('id')
->order(['id' => 'ASC'])
->where(['id >' => $id])
->first();
return ['prev' => $previous['id'], 'next' => $next['id']];
}
Called simply in the Controller:
// In src/Controller/ExamplesController.php
public function view($id = null) {
...
$neighbors = $this->Examples->find('neighbors', ['id' => $id]);
....
}
As explained here
there is no neighbors find method in cakephp 3.
But if you follow the flow of the issue you will find a custom finder to accomplish it, maybe it will work for you.

Hash::extract with HABTM

I'm having difficulty understanding the syntax of Hash::extract when dealing with HABTM.
I have data coming back from a find() that looks like this:
array(
(int) 0 => array(
'EventsGroup' => array(
'id' => '34',
'event_id' => '5',
'group_id' => '1'
)
),
(int) 1 => array(
'EventsGroup' => array(
'id' => '29',
'event_id' => '2',
'group_id' => '1'
)
)
)
I'm trying to get to an array that looks like: array(x,y,z) where x,y,z are event_id's.
The Cake documentation's example looks like:
$users = $this->User->find("all");
$results = Hash::extract($users, '{n}.User.id');
Based on that, I tried:
$eventsGroups = $this->EventsGroup->findAllByGroupId($groupid);
$secEvents = Hash::extract($eventsGroups, '{n}.{EventsGroup}.event_id' );
$secEvents2 = Hash::extract($eventsGroups, '{n}.EventsGroup.event_id' );
$secEvents3 = Hash::extract($eventsGroups, '{n}.[text=EventsGroup].event_id);
None of which worked.
I found a way to get what I wanted without using Hash::extract, but I'd like to use it as some of the other methods will be useful to me down the road.
Any help or pointers would be greatly appreciated!
Thanks
Have you tried:
$eventsGroups = $this->EventsGroup->findAllByGroupId($groupid);
$secEvents = Hash::extract($eventsGroups, '{n}.EventsGroup[event_id]' );
As the docs says to retrieve a field you should use a matcher and not a expression. And the brackets ({}) are not needed, they are used to build expressions like '{n}.{s}'...

CakePHP function to convert dotted arrays to multidimensional

In CakePHP, it seems like a lot of functions can take their arguments as nested, multidimensional arrays, or as dotted strings:
$this->MyModel->contain(array(
'Something', 'Something.Else', 'Something.Else.Entirely'
));
$this->MyModel->contain(array(
'Something' => array(
'Else' => 'Entirely'
)
));
Therefore, I figure there must be a function somewhere in the core to switch from dotted to nested associative, but I can't find it for the life of me. Any ideas?
I've actually figured my own way to get this working leveraging the built-in Set functions.
Given:
$input = array (
'Post.id' => 1,
'Post.title' => 'Some post title.',
'Post.Tag.0.id' => 4,
'Post.Tag.0.name' => 'cakephp',
'Post.Tag.1.id' => 7,
'Post.Tag.1.name' => 'mysql',
);
This code will put that into a nested associative array.
$output = array();
foreach ($input as $key => $value) {
$output = Set::insert($output, $key, $value);
}
Here's the docs for Set::insert()
What you're looking for is Set::flatten(). It's not documented in the CakePHP manual, but take a look at the API definition.
It works something like this (the result might not be exact, this is from my head):
$array = array(
'Post' => array(
'id' => 1,
'title' => 'Some post title.',
'Tag' => array(
0 => array(
'id' => 4,
'name' => 'cakephp',
),
1 => array(
'id' => 7,
'name' => 'mysql',
),
),
);
);
$array = Set::flatten($array);
var_dump($array);
Your $array variable will now look like this:
Array (
'Post.id' => 1,
'Post.title' => 'Some post title.',
'Post.Tag.0.id' => 4,
'Post.Tag.0.name' => 'cakephp',
'Post.Tag.1.id' => 7,
'Post.Tag.1.name' => 'mysql',
)
It's just a convention throughout Cake, but each part does its own, customized parsing. If you look at the function ContainableBehavior::containments() in cake/libs/model/behaviors/containable.php, you'll see a lot of preg_matching and explode('.')ing going on. At least in the case of Containable, the verbose array('name' => array(...)) syntax seems to be the canonical syntax, but it can be abbreviated with the dot syntax, which will just be expanded. I'd guess that the expanding itself is just too varied among different parts to be easily summarized in a central function.
That, or they just haven't gotten to it yet. :)
Great question, I was just searching for the same thing. Apparently it's coming in Cake 2.2.
The new Hash class (a new, improved version of the Set class) has an expand() function which does this. You can view the code on Github if you need to use it in the meantime:
https://github.com/cakephp/cakephp/blob/2.2/lib/Cake/Utility/Hash.php
...However the solution nickf posted works great, too. :-)

Resources