cakephp echo count - cakephp

Hi I have a like button which updates the likes table field type with like. I want to count the number of likes in the table, in my controller I have this,
// Load Likes Model and retrive number of likes and dislikes
$this->loadModel('Like');
$related_likes = $this->Like->find('count', array(
'conditions' => array('uploadid' => $id)
));
$this->set('likes', $related_likes);
}
How do I go about echoing the number of likes in my view??
Would really appreciate any help

When you use set(), the name you define becomes a variable in the view.
In your view:
echo $likes;

Related

Fetching values of a particular field from an array to a variable in cakephp

In cakephp, I executed this query to find the id field value of the corresponding username
$count = $this->User->find('all',array('conditions'=>array('User.username' => $n)))
How I will get take the value of a field from this array result to a variable?
I am new to cakephp and any help will be very useful.
Well, after calling find, you will notice that $count will be populated if something was brought from the database. I would change something, though, I would use "first" instead of "all" because you are finding only one record.
You can either use this
//in your controller
$count = $this->User->find('first',
array('conditions'=>array('User.username' => $n)));
//and set the variable to be used in the view in this way
$this->set('yourId', $count['User']['id']);
Then in your view
echo $yourId;
Or, you can also do this
$yourId = $this->User->field('id', array('User.username' => $n));
$this->set(compact('yourId'));
and then in your view
echo $yourId

CakePHP hasMany checkbox

I have two tables: Ingredients and Customers. The relationship between them is that Customers hasMany Ingredients. By default when doing the cakebake using the console, the only way to change them is by assigning an ingredient to the customer in the Ingredients page. However, I want to have in Customers page a checkbox list of Ingredients that can be assigned. Is it possible to do this? If yes, how?
edit:
What I have done until now is that I add this code to my add.ctp:
echo $this->Form->input('Ingredient',
array('label'=>'',
'type'=>'select',
'multiple'=>'checkbox',
'options'=>$ingredients));
However, it gives me "Undefined variable: ingredients" error when I tried to open the add view.
You want and need a HABTM relationship. Different customers can access and use the same ingredients. Look at the docs here yours would be very similar to different Posts using same Tags.
If you are getting this error:
"Undefined variable: ingredients"
It sounds like you haven't declared this variable in your controller, and set it so that the view can use it. Without knowing your code, you would probably need do do something like this (please note I am guessing what your application structure looks like and have not tested this code).
CustomersController.php
// The controller action for your view
public function view() {
// Get the ID and name of all your ingredients
$ingredients = $this->Ingredient->find('all', array(
'fields' => array('id', 'name'),
'order' => 'name',
'recursive' => -1
));
// We will use this array to store all the HTML select options
$ingredientOptions = array();
// Loop through all the ingredients and add them to the select
// options in a format that is suitable for CakePHP to use in
// the view to build your HTML select menu.
foreach ($ingredients as $i) {
$ingredient = $i['Ingredient'];
$ingredientOptions[$ingredient['id']] = $ingredient['name'];
}
// Make the variable available to the view
$this->set('ingredients', $ingredientOptions);
}

CakePHP SaveMany not saving

I have a issue with the SaveMany call in my CakePHP function.
The code below is my current attempt. This now sort of works, it does not make any errors at all but only the savefield will save any data, the saveMany, although it does not come back with errors does NOT save the data?
Please Help???
$InvoiceArrayData = array(
array('Invoicedata' => array('workdes' => $WorkHolder)),
array('Invoicedata' => array('price' => $PriceHolder)),
);
foreach($InvoiceArrayData as $InvoiceArrayKey => $InvoiceArrayValue) {
debug($InvoiceArrayValue);
$this->Invoicedata->saveMany($InvoiceArrayValue['Invoicedata']);
$this->Invoicedata->saveField('invoicejoblists_id', $MyJobIDInput);
$this->Invoicedata->saveField('invoicejoblists_id', $MyJobIDInput);
$this->Session->setFlash('Invoice Data Saved', 'default', array(), 'good');
//$this->redirect($this->Auth->redirect('/AdminInvoiceSystem/'));
}
When the code runs it does redirect with the saved meessaged but when the database is checked, only the invoicejoblist_id is saved.
Have not not done something right?
Glenn
UPDATE ::
Ok so what I am trying to do is to build an invoice system, I have a number of tables one of which 'invoicedatas' which has 'id, workdes, price, invoicejoblists_id' contained within it. ID is the key and is sent to auto count.
When the user starts to make a new invoice they fill in a form which saves in the other tables. But also in this form they input a work detail and price for that work.
This is then sent over to the function I am working on now, which returns no errors but does not save. Or I should say the saveMany call does not work, the saveField works and saves the ID number which I call from one of my other tables.
A bit of code I forget to add are the vars, which are just basic holders for the $this->data I am trying to save.
$WorkHolder = $this->data['workdes'];
$PriceHolder = $this->data['price'];
Please Help......
Glenn.
OK Here goes, I try and see if I can explain myself in more detail.
I am going to re-do so of my work to make it just plan easier for the UI apart form anything. To explain, I will now have a form which sets the invoice job, e.g jobnumber per user, user id, and other bits. This information will go into a table call invoicejoblist
The second table invoicedata holds just workdes and price along with invociejoblists_id (this links each row with the invoice job details).
But no matter what I do I can not get it to save into workdes and price. This is how my current test setup looks :
MY .cpt file:
$InvoiceMake = $this->Form->create('Invoice', array('url'=>'/InvoiceSet/', 'id' => 'InvoiceSet', 'inputDefaults' => array('div' => false) ) );
$InvoiceMake .= "<div id=\"InvoiceDataInput\">Please Input Description<br />";
$InvoiceMake .= $this->Form->textarea('Invoicedata.0.workdes');
$InvoiceMake .= $this->Form->textarea('Invoicedata.1.workdes');
$InvoiceMake .= $this->Form->textarea('Invoicedata.2.workdes');
$InvoiceMake .= $this->Form->textarea('Invoicedata.3.workdes');
$InvoiceMake .= $this->Form->textarea('Invoicedata.4.workdes');
$InvoiceMake .= "</div>";
$InvoiceMake .= $this->Form->submit('Make Invoice', array('div' => false, 'class' => 'ButtonInvoice'));
$InvoiceMake .= $this->Form->end();
echo $InvoiceMake;
My test function in controller:
function test() {
debug($this->data);
$HoldeME = $this->data;
$this->loadModel('Invoicedata');
$this->Invoicedata->saveAll($HoldeME);
}
These return not errors but the workdes information submitted will not save. The only thing I put in my model was:
public $belongsTo = array(
'Invoicejoblists' => array(
'className' => 'Invoicejoblists',
'foreignKey' => 'invoicejoblists_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
I did have some checks to make sure the inputs where not empty but remove them to see if that was my problem, not sure it that was right or not.
Hope that is better explained, I have gone down to the right basic level to just test save any data set but it still will not let me, is that because I should have something in my model?
Any help most welcome
Glenn.
I really have no clue what you're asking, but I'm giving it a blind-shot.
You should be able to save an item and as many sub/related items as you want in a single saveAll().
Just make sure your form (or the data) is formatted correctly per the copious instructions found in the CakePHP book.
As an example:
echo $this->Form->create('Invoice');
echo $this->Form->input('name');
echo $this->Form->input('Price.0.amount');
echo $this->Form->input('Price.1.amount');
echo $this->Form->end('Submit');
Then, when you do a saveAll() (or saveMany() - whatever), your Invoice will save as well as the two Prices (assuming Invoice is related to Price).
If you're trying to build the data manually, but don't know how it should be formatted, you can always create a form like above, submit it, and debug() the results to see how CakePHP would format it.
Hope that helps clarify for you.

Settings page and multi edit rows

I would like to make a configuration page like this for my CMS
http://img4.hostingpics.net/pics/72087272ok.png
I want this page (admin/settings/index) gets me the various settings (ID 1 to 21) came to my table and in case of change, I can, in this form, do an update
After 3 days of not especially fruitful research I found something. I put in my SettingsController:
admin_index public function () {
if (!empty($this->data)) {
$this->Setting->saveAll($this->request->data['Setting']);
} else {
$this->request->data['Setting'] = Set::combine($this->Setting->find('all'),
'{n}. Setting.id', '{n}. Setting');
}
}
and my view:
<?php
echo $this->Form->create('Setting', array ('class' => 'form-horizontal'));
foreach($this->request->data['Setting'] as $key => $value) {
echo $this->Form->input('Setting.' . $key . '.pair');
echo $this->Form->input('Setting.' . $key . '.id');
}
echo $this->Form->end(array('class' => 'btn btn-primary', 'label' => 'Save',
'value' => 'Update!', 'div' => array ('class' => 'form-actions')));
?>
he is recovering well all my information, I can even update. The trouble is that I do not really know how I can do to get the same result as my first screenshot. He puts everything in the textarea while in some cases I want the checkbox and / or drop-down.
please help me or explain to me how to make a page that retrieves configuration information from my table and allows me to edit without use an address like admin/settings/edit/ID
My table settings is something like this here
http://img4.hostingpics.net/pics/724403settings.png
If you are asking about how to format the output to produce a "settings" page, you will need to do it manually or add some kind of metadata to your table schema, such as "field_type".
Now Cake will automatically generate a checkbox for a boolean or tiny int, for example, but as you have varchars, ints, texts and so on, this won't work for you (pair is presumably varchar or text to allow for the different possible values.
You cannot really automagically generate the outputs you want without telling Cake.
One option would be to add a field_type to the table, so:
key value field
site_name My Site input
site_online 1 checkbox
meta_desc [some text] textarea
and something like
foreach($settings as $setting) {
echo $this->Form->{$setting['field']}($setting['key'],
array('value' => $setting['value']));
}
might do what you are after.
Or if($key=='site_name') // output a textbox
but this is not exactly ideal.

Cake HABTM Query, Order By Rand()

I'm aware that Cake HABTM associations are tricky at the best of times, but I seem to be making life even harder for myself...
If I want to return a random Item from the db, I can do it as follows in the Item model:
$random = $this->find('first', array(
'order' => 'rand()'
));
and if I want to find all the Items that are in a certain Category (where Item has a HABTM relationship to Categories), I know I can get a result set through $this->Categories->find.
My question is: how can I combine the two, so I can return a random Item that belongs to a specified Category? Is there any easy way? (If not, I'll gladly take any suggestions for a laborious way, as long as it works ;)
ETA: I can get some of the way with Containable, maybe: say I add the line
'contain' => array('Categories'=>array('conditions'=>array('Categories.id'=>1))),
then the Item results that I don't want come back with an empty Categories array, to distinguish them from "good" items. But really I don't want said Item results to be returned at all...
ETA(2): I can get a workaround going by unsetting my results in the afterFind if the Categories array is empty (thanks to http://nuts-and-bolts-of-cakephp.com/2008/08/06/filtering-results-returned-by-containable-behavior/ for the tip), and then having my random find function not give up until it gets a result:
while (!is_array($item)) {
$item = $this->random($cat);
}
but ugh, could this be any clunkier? Anyway, time for me to stop editing my question, and to go away and sleep on it instead!
Try this:
<?php
$this->Item->bindModel(array('hasOne' => array('ItemsCategory')));
$random = $this->Item->find('all', array(
'order' => 'rand()',
'conditions' => array('ItemsCategory.category_id' => '1')
));
?>

Resources