How do I get Data in Array format from a 'find('all')' call.
$query->all ()->getResponse ()->getData ()['message']
gives me a json string '{\"_source[]....}'
Below is my code sample
use Cake\ElasticSearch\TypeRegistry;
class PagesController extends AppController {
public function index() {
$english_pages = TypeRegistry::get ( 'EnglishPages' );
$query = $english_pages->find ( 'all' );
// $query = $query->getData();
// $query->all () ;
// $query->all ()->getResponse () );
// json_decode ( stripslashes($query->all ()->getResponse ()->getData ()['message']) , true ) ;
// echo json_last_error_msg ();
// json_encode ( $query->all ()->getResponse ()->getData ()['message'] ) ;
}
}
The Cakephp docs are not inline with the current Cakephp3 Elastic search on Github.
It works the same as using the ORM:
$query = $english_pages->find('all');
$results = $query->toArray();
Related
i would like to use this simple image slider for the joomgallery for my art students:
https://github.com/danielhpavey/joomgallery-slider
the only problem is the ordering. how do i get an ascending image ordering by id and not by filename ?
thanks peter
<?php
class images
{
public function __construct()
{
$file = JPATH_ROOT. '/components/com_joomgallery/interface.php';
if(!file_exists($file)){
JError::raiseError(500, 'JoomGallery seems not to be installed');
} else {
require_once $file;
$this ->interface = new JoomInterface();
}
}
public function getFirstImage()
{
$images = $this ->talkToJoomgallery();
return $images[0];
}
public function getImages()
{
$images = $this ->talkToJoomgallery();
return $images;
}
public function talkToJoomgallery()
{
$images = $this ->interface ->getPicsByCategory( $this ->categoryid );
$imagepath = $this ->joomgalleryImagePath();
$theimages = array();
$c = 0;
foreach ($images as $i){
$theimages[$c]= array(
'imgpath' => JURI::base() . $imagepath . $i->catpath . '/' . $i->imgfilename
,'imgtitle' => $i->imgtitle
,'imgtext' => $i->imgtext
);
$c ++;
}
shuffle($theimages);
return $theimages;
}
private function joomgalleryImagePath()
{
return $this ->interface ->getJConfig( 'jg_pathoriginalimages' );
}
public function __set($property, $value){
$this->$property = $value;
}
}
Your images are loaded according to image id only but this command is reindexing the array i.e shuffle($theimages);
You can comment out that line by
//shuffle($theimages)
Also for ordering images you can change this line in helper.php file
$images = $this->interface->getPicsByCategory($this->categoryid);
to
$images = $this->interface->getPicsByCategory($this->categoryid,null,'ordering' );
This will do the ordering of images the way you did drag and drop of images at the joomla administrator backend.
UPDATE AS PER YOUR LATEST QUERY
Suppose you want to add a param value (sorting) that can be controlled through admin. You ned to change the xml file mod_joomgallery_slider.xml
Just add a new field like this
<field
name = "sorting"
type = "radio"
label = "Sorting"
description = "Sort by Ordering or random"
default = "ordering"
>
<option value = "ordering">Ordering</option>
<option value = "rand()">Random</option>
</field>
Next to get the param in helper.php file then change the function talkToJoomgallery() like this
public function talkToJoomgallery()
{
//Externally calling a module param
jimport( 'joomla.html.parameter' );
jimport( 'joomla.application.module.helper' );
$module = JModuleHelper::getModule('mod_joomgallery_slider');
$moduleParams = new JRegistry();
$moduleParams->loadString($module->params);
$sorting = $moduleParams->get( 'sorting' );
$images = $this ->interface ->getPicsByCategory( $this ->categoryid,null,$sorting );
$imagepath = $this ->joomgalleryImagePath();
$theimages = array();
$c = 0;
foreach ($images as $i){
$theimages[$c]= array(
'imgpath' => JURI::base() . $imagepath . $i->catpath . '/' . $i->imgfilename
,'imgtitle' => $i->imgtitle
,'imgtext' => $i->imgtext
);
$c ++;
}
//var_dump($theimages); exit;
//shuffle($theimages);
return $theimages;
}
UPDATE: To display 2 slider modules on a single page.
Some files needs to changed:
In mod_joomgallery_slider.php file change this line at top
include('helper.php');
To
include_once('helper.php');
This ensures that the file is included once.
Another change will be to remove the function imageText in default.php and including it in helper.php class else a function redeclaration error will be thrown. But now the default.php file still give error, as function imageText will be not defined, but you already added that function to helper.php. So default.php will only work if you change
echo imageText( $i, $params );
To
echo $image->imageText( $i, $params );// You are calling helper object
Remember to change in both if and else conditions.
I am being shown the following error on top of my page when using beforeSave method in my Upload model.
Strict (2048): Declaration of Upload::beforeSave() should be
compatible with Model::beforeSave($options = Array)
[APP/Model/Upload.php, line 5]
Could someone point out what I'm doing wrong?
Here is my model:
<?php
App::uses('AppModel', 'Model');
class Upload extends AppModel {
protected function _processFile() {
$file = $this->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$name = md5($file['name']);
$path = WWW_ROOT . 'files' . DS . $name;
if (is_uploaded_file($file['tmp_name'])
&& move_uploaded_file($file['tmp_name'], $path) ) {
$this->data['Upload']['name'] = $file['name'];
$this->data['Upload']['size'] = $file['size'];
$this->data['Upload']['mime'] = $file['type'];
$this->data['Upload']['path'] = '/files/' . $name;
unset($this->data['Upload']['file']);
return true;
}
}
return false;
}
public function beforeSave() {
if (!parent::beforeSave($options)) {
return false;
}
return $this->_processFile();
}
}
?>
Just change this line
public function beforeSave() {
to this, so you have correct method declaration
public function beforeSave($options = array()) {
The beforeSave() function executes immediately after model data has been successfully validated, but just before the data is saved. This function should also return true if you want the save operation to continue.
This callback is especially handy for any data-massaging logic that needs to happen before your data is stored. If your storage engine needs dates in a specific format, access it at $this->data and modify it.
Below is an example of how beforeSave can be used for date conversion. The code in the example is used for an application with a begindate formatted like YYYY-MM-DD in the database and is displayed like DD-MM-YYYY in the application. Of course this can be changed very easily. Use the code below in the appropriate model.
public function beforeSave($options = array()) {
if (!empty($this->data['Event']['begindate']) &&
!empty($this->data['Event']['enddate'])
) {
$this->data['Event']['begindate'] = $this->dateFormatBeforeSave(
$this->data['Event']['begindate']
);
$this->data['Event']['enddate'] = $this->dateFormatBeforeSave(
$this->data['Event']['enddate']
);
}
return true;
}
public function dateFormatBeforeSave($dateString) {
return date('Y-m-d', strtotime($dateString));
}
Make sure that beforeSave() returns true, or your save is going to fail.
I'm having some issues trying to save an article that has 4 pictures. The thing is that i need to use the article id in order to name the pictures like article_id."-"$i
Since I have only 4 pictures per article this $i should be from 1 to 4 or from 0 to three.
Now the problem is that in order to achieve this i need to create and save Article model so i can have an id to use, but then after performing all the scripting to make the thumbs and form the names, when I go Article->saveAssociated() i have two times the article record created!! i tried to set the id to "-1" before saving but nothing...
Any suggestion will be very much appreciated !!!
Code:
public function add() {
if ($this->request->is ( 'ajax' )) {
$this->layout = 'ajax';
} else {
$this->layout = 'default';
}
if ($this->request->is ( 'post' )) {
$this->Article->create ();
$this->request->data ['Article'] ['time_stamp'] = date ( 'Y-m-d H:i:s', time () );
if ($this->Article->save($this->request->data) ) {
for ($i=0; $i<4; $i++){
$img_path = "./images/";
$extension[$i] = end(explode('.', $this->request->data['Image'][$i]['image']['name']));
$this->request->data['Image'][$i]['image'] = array('name'=>$this->Article->id."-".$i, 'tmp_name' => $this->request->data['Image'][$i]['image']['tmp_name']);
// $this->request->data['Image'][$i]['name'] = $this->Article->id."-".$i;
$this->request->data['Image'][$i]['ext']= $extension[$i];
$target_path[$i] = $img_path . basename($this->request->data['Image'][$i]['image']['name'].".".$extension[$i]);
if(!move_uploaded_file($this->request->data['Image'][$i]['image']['tmp_name'], $target_path[$i])) {
die(__ ( 'Fatal error, we are all going to die.' ));
}else{
$this->Resize->img($target_path[$i]);
$this->Resize->setNewImage($img_path.basename($this->request->data['Image'][$i]['image']['name']."t.".$extension[$i]));
$this->Resize->setProportionalFlag('H');
$this->Resize->setProportional(1);
$this->Resize->setNewSize(90, 90);
$this->Resize->make();
}
}
$this->Article->id;
pr($this->Article->id);
$this->Article->saveAssociated($this->request->data, array('deep' => true));
//$this->redirect ( array ('action' => 'view', $this->Article->id ) );
pr($this->Article->id);
exit;
$this->Session->setFlash ( __ ( 'Article "' . $this->request->data ["Article"] ["name"] . '" has been saved' ) );
} else {
$this->Session->setFlash ( __ ( 'The article could not be saved. Please, try again.' ) );
}
}
$items = $this->Article->Item->find ( 'list' );
$payments = $this->Article->Payment->find ( 'list' );
$shippings = $this->Article->Shipping->find ( 'list' );
$this->set ( compact ( 'items', 'payments', 'shippings' ) );
}
Instead of
$this->Article->saveAssociated();
which would save the Article AGAIN, just save the images separately using something like this:
foreach($this->request->data['Image'] as &$image) {
$image['name'] = 'whatever_you_want' . $this->Article->id;
$image['article_id'] = $this->Article->id;
}
$this->Article->Image->save($this->request->data['Image']);
Another option (not necessarily better - just another option) would just be to append the newly-created Article's id to the existing Article array, then saveAssociated(). If the Article has an id in it's data, it will update instead of create. I would suggest the first answer above, but - just brainstorming other options in case this helps for someone's scenario:
// 1) save the Article and get it's id
// 2) append the `id` into the Article array
// 3) do your image-name manipulation using the id
// 4) saveAssociated(), which updates the Article and creates the Images
I've been researching a bit and I found that CakePHP's form helper doesn't interpret ENUM fields correctly, so it simply outputs a text input. I found a post that suggested to use a helper for that specific purpose. Does anybody know a better way to achieve this? Or if CakePHP devs intend to correct this some day?
Thanks for reading!
Below is one of the helper extention.
App::uses('FormHelper', 'View/Helper');
/**
* APP/View/Helper/MySqlEnumFormHelper.php
* It extends FormHelper to implement ENUM datatype of MySQL.
*
* http://blog.xao.jp/blog/cakephp/implementation-of-mysql-enum-datatype-in-formhelper/
*
* created Oct. 15, 2012
* CakePHP 2.2.3
*/
class MySqlEnumFormHelper extends FormHelper
{
public function input($fieldName, $options = array())
{
if (!isset($options['type']) && !isset($options['options'])) {
$modelKey = $this->model();
if (preg_match(
'/^enum\((.+)\)$/ui',
$this->fieldset[$modelKey]['fields'][$fieldName]['type'],
$m
)) {
$match = trim($m[1]);
$qOpen = substr($match, 0, 1);
$qClose = substr($match, -1);
$delimiter = $qOpen . ',' . $qClose;
preg_match('/^'.$qOpen.'(.+)'.$qClose.'$/u', $match, $m);
$_options = explode($delimiter, $m[1]);
$options['type'] = 'select';
$options['options'] = array_combine($_options, $_options);
}
}
return parent::input($fieldName, $options);
}
}
Cake attempts to be database agnostic and therefore this issue won't be "corrected" since it's not a bug. For example, SQL server doesn't have an exact equivalent of MySQL's ENUM field type.
I would recommend getting your possible list of enum values like so:
YourController.php
// get column type
$type = $this->Model->getColumnType('field');
// extract values in single quotes separated by comma
preg_match_all("/'(.*?)'/", $type, $enums);
// enums
var_dump($enums[1]);
Then use a select field in your view and pass the enums as options. Your current value you'll already have. How does that sound?
I am new to cakephp I found some old code and pieced together an enum select box for you enjoy
/**
* Behavior with useful functionality around models containing an enum type field
*
* Copyright (c) Debuggable, http://debuggable.com
*
*
*
* #package default
* #access public
*
* reworked by Nathanael Mallow for cakephp 2.0
*
*/
/*
*Use case:Add this (EnumerableBehavior.php) to app/Model/Behavior/
* -->in the Model add public $actsAs = array('Enumerable');
* -->in the *_controller add $enumOptions = $this->Categorie->enumOptions('Section');
* -->in the view add print $this->Form->input('{db_field_name}', array('options' => $enumOptions, 'label' => 'here'));
*
*
*/
class EnumerableBehavior extends ModelBehavior {
/**
* Fetches the enum type options for a specific field
*
* #param string $field
* #return void
* #access public
*/
function enumOptions($model, $field) {
//Cache::clear();
$cacheKey = $model->alias . '_' . $field . '_enum_options';
$options = Cache::read($cacheKey);
if (!$options) {
$sql = "SHOW COLUMNS FROM `{$model->useTable}` LIKE '{$field}'";
$enumData = $model->query($sql);
$options = false;
if (!empty($enumData)) {
$enumData = preg_replace("/(enum|set)\('(.+?)'\)/", '\\2', $enumData[0]['COLUMNS']['Type']);
$options = explode("','", $enumData);
}
Cache::write($cacheKey, $options);
}
return $options;
}
}
?>
If you want to use MySqlEnumFormHelper instead of normal and call it by $this->Form-> instead by $this->MySqlEnumFormHelper . You should add this line in your controller to alias MySqlEnumFormHelper as Form.
public $helpers = array('Form' => array(
'className' => 'MySqlEnumForm'
));
/* comments about previus answers ***
Use case:Add this (EnumerableBehavior.php) to app/Model/Behavior/
-->in the Model add public $actsAs = array('Enumerable');
-->in the action of the *_controller add $enumOptions = $this->YourModelName->enumOptions('db_field_name'); $this->set('enumOptions',$enumOptions);
-->in the view add print $this->Form->input('{db_field_name}', array('options' => $enumOptions, 'label' => 'here'));
*
*/
i think the Behaviour way it's good...but the array keys are integer
so i have modified the function like this
function enumOptions($model, $field) {
//Cache::clear();
$cacheKey = $model->alias . '_' . $field . '_enum_options';
$options = Cache::read($cacheKey);
$enumOptions = array();
if (!$options) {
$sql = "SHOW COLUMNS FROM `{$model->useTable}` LIKE '{$field}'";
$enumData = $model->query($sql);
$options = false;
if (!empty($enumData)) {
$enumData = preg_replace("/(enum|set)\('(.+?)'\)/", '\\2', $enumData[0]['COLUMNS']['Type']);
$options = explode("','", $enumData);
foreach ($options as $option) {
$enumOptions["$option"] = $option;
}
}
Cache::write($cacheKey, $enumOptions);
}
return $enumOptions;
}
in order to be able to save the right value in the db field when the form is submitted
I created a function that goes into AppController to handle this. I combined some of the information provided above.
Usage:
$enumList = getEnumValues($ModelField) where ModelField is in this format: 'Model.Field'
Function that I put in AppController:
function getEnumValues($ModelField){
// split input into Model and Fieldname
$m = explode('.', $ModelField);
if ($m[0] == $ModelField) {
return false;
} else {
(! ClassRegistry::isKeySet($m[0])) ? $this->loadModel($m[0]): false;
$type = $this->$m[0]->getColumnType($m[1]);
preg_match_all("/'(.*?)'/", $type, $enums);
foreach ($enums[1] as $value){$enumList[$value] = $value;}
return $enumList;
}
}
I am trying to insert the following array
foreach($list as $l)
{
$data = array(
'source_number'=> $l['Csv']['Source'],
'destination_number'=> $l['Csv']['Destination'],
'seconds'=> $l['Csv']['Seconds'],
'callerID'=> $l['Csv']['CallerID'],
'disposition'=> $l['Csv']['Disposition'],
'cost'=> $l['Csv']['Cost'],
'billing_cost'=> $l['Csv']['newCost']
);
//$total[] = $l['Csv']['newCost'];
debug($data);
$this->CallcenterBilling->save($data);
unset($data);
}
But it dives me this error
( ! ) Fatal error: Call to a member function save() on a non-object in C:\wamp\www\wadic\app\Controller\CallcenterBillingsController.php on line 61
Call Stack
# Time Memory Function Location
1 0.0005 708160 {main}( ) ..\index.php:0
2 0.0169 2775744 Dispatcher->dispatch( ) ..\index.php:96
3 0.0279 3946176 Dispatcher->_invoke( ) ..\Dispatcher.php:89
4 0.0293 4016984 Controller->invokeAction( ) ..\Dispatcher.php:107
5 0.0293 4017992 ReflectionMethod->invokeArgs( ) ..\Controller.php:473
6 0.0293 4018024 CallcenterBillingsController->import( ) ..\CallcenterBillingsController.php:0
what am I missing?
thanks
Firstly you may sure that in CallcenterBillingsController you have CallcenterBilling model in uses:
public $uses = array('CallcenterBilling');
Secondary you can optimize this by saving not in loop:
see saveAll method of the model
so you will get something like:
class CallcenterBillingController extends AppController {
public $uses = array('CallcenterBilling');
public function someaction() {
$data = array();
foreach ($list as $l) {
$data[] = array(
'source_number' => $l['Csv']['Source'],
'destination_number' => $l['Csv']['Destination'],
'seconds' => $l['Csv']['Seconds'],
'callerID' => $l['Csv']['CallerID'],
'disposition' => $l['Csv']['Disposition'],
'cost' => $l['Csv']['Cost'],
'billing_cost' => $l['Csv']['newCost']
);
//$total[] = $l['Csv']['newCost'];
}
debug($data);
$this->CallcenterBilling->saveAll($data);
}
}
ps. if this not helps, please show controller code.
You should implement this:
$this->CallcenterBilling->read(null, 1);
$this->CallcenterBilling->set(array(
'source_number'=> $l['Csv']['Source'],
'destination_number'=> $l['Csv']['Destination'],
'seconds'=> $l['Csv']['Seconds'],
'callerID'=> $l['Csv']['CallerID'],
'disposition'=> $l['Csv']['Disposition'],
'cost'=> $l['Csv']['Cost'],
'billing_cost'=> $l['Csv']['newCost']
));
$this->CallcenterBilling->save();
This might works for you.