Using not equal to in where clause cakephp - cakephp

Why doesn't this work?
I want to display files which are
available (in my case is = 0)
everyone (Privacy settings which in my case is =1)
Not equal to the author of the file
it doesn't display me anything for which the user that created it, it is supposed to show a file that is
within those conditions
it seems like I have a problem within the 'Files.user_id !=' => $auth->user_id but I can't figure out what is wrong with it
$filesTable->find('all')->where(['available' => 0,'Privacy.privacy_id' => 1,'Files.user_id !=' => $auth->user_id])->contain(['Users','Privacy'])->toArray();
Neither of these are being displayed
click here

To include null IDs in your query, you need to match on that explicitly:
$filesTable->find('all')->where([
'available' => 0,
'Privacy.privacy_id' => 1,
'OR' => [
'Files.user_id !=' => $auth->user_id,
'Files.user_id IS' => null,
],
])->contain(['Users','Privacy'])->toArray();

Related

drupal form field not loading correct data

I am building my first Drupal 7 module and am having trouble with the screen to edit a fieldable entity. I am using field_attach_form and it is working great for all accept one field which is displaying the field default rather than the current content of that field for that entity.
I have a text field, a number field, a number of Boolean fields and the one list_text field which is failing.
Any ideas what I a doing incorrectly? Code below is what I think is needed but please do let me know if you need more.
Code to create the field in hook_enable:
if (!field_info_field('field_available')) {
$field = array (
'field_name' => 'field_available',
'type' => 'list_text',
'settings' => array(
'allowed_values' => array('No', 'Provisionally', 'Yes'),
),
);
field_create_field($field);
Code to create the instance, also in hook_enable:
if (!field_info_instance('appointments_status', 'field_available', 'appointments_status')) {
$instance = array(
'field_name' => 'field_available',
'entity_type' => 'appointments_status',
'bundle' => 'appointments_status',
'label' => t('Available?'),
'required' => TRUE,
'default_value' => array(array('value' => 'No')),
'description' => t('Set to No if appointments with this status make this slot unavailable, Provisionally means that it will only reserve a space temporarily'),
);
field_create_instance($instance);
This entity has only the one bundle with the same name as the entity.
The code to create the URL in hook_menu:
$items['admin/appointments/appointments_statii/%/edit'] = array(
'title' => 'Edit appointment status',
'description' => 'Edit the parameters of the selected status code',
'page callback' => 'drupal_get_form',
'page arguments' => array('appointments_status_edit_form',3),
'access arguments' => array('access administration pages'),
'type' => MENU_CALLBACK,
);
The form function is:
function appointments_status_edit_form($form, &$form_state) {
// Get the status id from the form_state args
$status_id = $form_state['build_info']['args'][0];
// Load the chosen status entity
$status = entity_load_single('appointments_status', $status_id);
// Set up the fields for the form
field_attach_form('appointments_status', $status, $form, $form_state);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Save changes',
'#weight' => 99,
);
return $form;
}
I have used the Devel module's dpm to check that the data is loaded correctly by entity_load_single and it is.
Thanks
Rory
I have answered my own question!
I was also programmatically loading some entities and was not loading this field with the numbers that a list_text field stores, instead I was loading the visual text.
I used a metadata wrapper and the code looked like this:
$w_appointments_status->$appointments_availability= 'Yes';
I changed it to:
$w_appointments_status->$appointments_availability = 2;
In this example 'Yes' was the third allowed value - hence 2.
So the code in my question was in fact correct although I have since added 'widget' and 'formatter' parameters to the instance.
I am sorry if this got some of you scratching your heads thinking ' but that code is correct'!!
Regards
Rory

cakephp correct array to use updateAll

I am using cakephp 2.5 and I have an array that I wish to update many records at once in the Page model. I can't seem to get the format of the array correct. I get the error:
Notice (8): Undefined index: newOrder [APP/Controller/PagesController.php, line 133]
$newOrder = array(
'Page' => array(
0 => array(
'id' => 3,
'order' => 0),
1 => array(
'id' => 4,
'order' => 0),
2 => array(
'id' => 7,
'order' => 0
)
));
$this->Page->updateAll($newOrder);
One of the parts I think I am missing is using 'data' as part of the array. But I am unsure where to place it.
I have also tried:
$this->Page->updateAll($newOrder['Page']);
You should use saveMany for your requirement. Find the explanation below -
updateAll
updateAll(array $fields, array $conditions) - is used to update one or more records with the same value based on a condition or multiple conditions. eg: If you want to update all your pages & set all of them to order = 0, you can use updateAll without passing the primary keys -
$this->Page->updateAll(
array('Page.order' => 0)
);
If you want to update some pages based on a condition you will do something like -
$this->Page->updateAll(
array('Page.order' => 0),
array('Page.type' => 'PROMOTED')
);
Assuming you have a type field in your page model, the above query will set order 0 for all pages with type PROMOTED
Ref - http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions
saveMany
Now if you want to update some specific records with some specific values which you want to create in an array, you should use a saveMany(array $data = null, array $options = array())
To save/update multiple records using a data array, you should first create the data array in this format -
$data = array(
array('Page' => array('id' => 1, 'order' => 0)),
array('Page' => array('id' => 2, 'order' => 0)),
array('Page' => array('id' => 3, 'order' => 0))
);
$this->Page->saveMany($data);
Now you can use saveMany to update the three records with the given id(primary key) with order 0. Note if you don't pass primary keys i.e id in the arrays, saveMany will just create new records for the given array.
Ref - http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array

Drupal 7 Rules custom action assign return data to a replacement pattern

How can I create a custom Rule-Action which will successfully save a value as a replacement pattern for use in the other actions?
I got some very good help here on retrieving Product-Display information from a Product-Order.
As I said, the linked answer helped a great deal but the returned path data for the Product-Display comes back in the http://www.mysite/node/77 format. However, I really just need the numeric value only so I can load the node by performing a Fetch entity by id action supplying the numeric value and publishing the Product-Display node etc.
So, I implemented a custom action which will take the Product-Display URL(node/77) and return 77.
I copied the Fetch entity by id code and modified it so my returned numeric value can be saved and used in other Actions. The code is below:
function my_custom_action_info(){
$actions['publish_product_display_node'] = array(
'label' => t('Fetch product-display id'),
'parameter' => array(
'type' => array(
'type' => 'uri',
'label' => t('My Action'),
'options list' => 'rules_entity_action_type_options2',
'description' => t('Specifies the product-display url.'),
),
),
'provides' => array(
'entity_fetched' => array('type' => 'integer', 'label' => t('Fetched entity')),
),
'group' => t('Entities'),
'access callback' => 'rules_entity_action_access',
);
return $actions;
}
function publish_product_display_node($path = null){
$parts = explode('node/', $path);
return $parts[1];
}
function rules_entity_action_type_options2($element, $name = NULL) {
// We allow calling this function with just the element name too. That way
// we ease manual re-use.
$name = is_object($element) ? $element->getElementName() : $element;
return ($name == 'entity_create') ? rules_entity_type_options2('create') : rules_entity_type_options2();
}
function rules_entity_type_options2($key = NULL) {
$info = entity_get_info();
$types = array();
foreach ($info as $type => $entity_info) {
if (empty($entity_info['configuration']) && empty($entity_info['exportable'])) {
if (!isset($key) || entity_type_supports($type, $key)) {
$types[$type] = $entity_info['label'];
}
}
}
return $types;
}
function rules_action_entity_createfetch_access2(RulesAbstractPlugin $element) {
$op = $element->getElementName() == 'entity_create' ? 'create' : 'view';
return entity_access($op, $element->settings['type']);
}
As I said I copied the modified code so I don't claim to thoroughly understand all the functions aside from publish_product_display_node.
My code modifications work as far as setting the Product-Display URL token as the argument and also setting an entity variable label(Display NID) and value(display_nid).
The problem is when I check display_nid in newly created actions, the value is empty.
I need help figuring out the how to successfully save my entity value so I can use it in following Actions.
in the function publish_product_display_node, can you verify that you don't need to be returning $parts[0], instead of $[parts[1]?
It's just that Drupal paths are frequently in the form 'node/7' or 'taxonomy/term/6', and if you explode with 'node/' as the separator, you'd only have a single value which would start at index 0 for nodes...
So, just wondering if that would solve your issue...

CakePHP: how to get total number of records retrieved with pagination

When you retrieve records using $this->paginate('Modelname') with some page limit, how do you get the total number of records retrieved?
I'd like to display this total count on the view, but count($recordsRetrieved) returns the number displayed only on the current page. So, if total number of records retrieved is 99 and limit is set to 10, it returns 10, not the 99.
You can debug($this->Paginator->params());
This will give you
/*
Array
(
[page] => 2
[current] => 2
[count] => 43
[prevPage] => 1
[nextPage] => 3
[pageCount] => 3
[order] =>
[limit] => 20
[options] => Array
(
[page] => 2
[conditions] => Array
(
)
)
[paramType] => named
)
*/
The final code for PHP >=5.4:
$this->Paginator->params()['count'];
For PHP versions less than 5.4:
$paginatorInformation = $this->Paginator->params();
$totalPageCount = $paginatorInformation['count'];
To get your answer go to he following link
http://book.cakephp.org/2.0/en/controllers/request-response.html
use pr($this->request->params) you will find all the stuff of pagination
For cake 3.x
you can use method getPagingParams
example:
debug($this->Paginator->getPagingParams());
output:
[
'users' => [
'finder' => 'all',
'page' => (int) 1,
'current' => (int) 5,
'count' => (int) 5,
'perPage' => (int) 1,
'prevPage' => false,
'nextPage' => true,
'pageCount' => (int) 5,
'sort' => null,
'direction' => false,
'limit' => null,
'sortDefault' => false,
'directionDefault' => false,
'scope' => null
]
]
Here's how I got the count from my controller*
This is for CakePHP 2.3. It uses a view helper, which is typically a no-no in the controller as it violates MVC, but in this case I think makes sense to keep the code DRY.
// Top of file
App::uses('PaginatorHelper', 'View/Helper');
// Later in controller method
$paginatorHelper = new PaginatorHelper(new View(null));
$records = $this->paginate();
$count = $paginatorHelper->params()['count'];
* I know the OP asked about from the view, but I figure if Arzon Barua's answer is helping people (though I think it only tells you the requested count, not the actual count as the OP wants), then this might help too.
This way is getting a pagination information over controller.
class YourController extends Controller{
$helpers = array('Paginator');
public fn(){
$view = new View(null);
var_dump($view->paginator->params());
}
}

saveall not saving associated data

I'm having a problem trying to save (update) some associated data. I've read about a million google returns, but nothing seems to be the solution. I'm at my wit's end and hope some kind soul here can help.
I'm using 1.3.0-RC4, my database is in InnoDB.
Course has many course_tees
CourseTee belongs to course
My controller function is pretty simple (I've made it as simple as possible):
if(!empty($this->data))
$this->Course->saveAll($this->data);
I've tried a lot of different variations of that $this->data['Course'], save($this->data), etc without luck.
It saves the Course info, but not the CourseTee stuff. I don't get an error message.
Since I don't know how many tees any given course will have, I generate the form inputs dynamically in a loop.
$form->input('CourseTee.'.$i.'.teeName', array(
'error' => false,
'label' => false,
'value'=>$data['course_tees'][$i]['teeName']
))
The course inputs are simpler:
$form->input('Course.hcp'.$j, array(
'error' => false,
'label' => false,
'class' => 'form_small_w',
'value'=>$data['Course']['hcp'.$j]
))
And this is how my data is formatted:
Array
(
[Course] => Array
(
[id] => 1028476
...
)
[CourseTee] => Array
(
[0] => Array
(
[key] => 636
[courseid] => 1028476
...
)
[1] => Array
(
[key] => 637
[courseid] => 1028476
...
)
...
)
)
According to CakePHP conventions you must provide [course_id] => 1028476 and not [courseid] => 1028476. Check you model bindings as well (capitalizations and underscores). There must be "Course has many CourseTee".
Do this way to save:
if ($this->Course->saveAll($this->data, array('validate' => 'first'))) {
$this->_flash(__('Successfully saved.', true), 'success');
} else {
$this->_flash(__('Cannot save. Does not validates.', true), 'error');
}

Resources