How can i save multiple checkbox value those are checked in cakephp hasMany relation? - cakephp-2.0

Suppose I have 3 tables property_details, property_feature_details, property_feature_relations.
PropertyDetail Model has the hasMany relation with PropertyFeatureRelation.
AT the time saveing my data array looks like that:
$this->data = array('PropertyDetail' => array('name'=>'xyz'),'PropertyFeatureRelation' => array('0' => array('feature_id'=>1),'1' => array('feature_id'=>5),'2' => array('feature_id'=>0),'3' => array('feature_id'=>0)));
Those feature_ids values are coming out from the checkboxes. Those are checked they are contains ids value and non checked are having 0 value. But in the child table saves all the data zero and non zeros.
Actually I want to save those checkboxes values which are only checked. Please do not provide any manual controller logic. Help me.

I am explaining you with my example which is having question ,answer and its survey
you can use multiple checkbox syntax as below:
$answers=array();
$tmp_ans=$question['Answer'];
for($j=0;$j < count($tmp_ans);$j++)
$answers[$tmp_ans[$j]['id']]=$tmp_ans[$j]['answer'];
echo '<li>';
echo $this->Form->input('Answer', array(
'type' => 'select',
'name'=>'Answer['.$question['Question']['id'].']',
'class'=>'test',
'label'=>false,
'multiple' => 'checkbox',
'options' =>$answers ,
));
echo '</li>';
after that you will have only those answers which you have checked others will not come in array of post so to save data you can use below syntax
if(!empty($this->data['Answer'])){
foreach ($this->data['Answer'] as $key=>$val):
if(!empty($val)):
if(is_array($val)):
foreach ($val as $ans):
$post_data['UserAnswer']['id']='';
$post_data['UserAnswer']['survey_id']=$id;
$post_data['UserAnswer']['user_id']=$this->Auth->user('id');
$post_data['UserAnswer']['question_id']=$key;
$post_data['UserAnswer']['answer_id']=$ans;
$this->UserAnswer->save($post_data['UserAnswer']);
endforeach;
else:
$post_data['UserAnswer']['id']='';
$post_data['UserAnswer']['survey_id']=$id;
$post_data['UserAnswer']['user_id']=$this->Auth->user('id');
$post_data['UserAnswer']['question_id']=$key;
$post_data['UserAnswer']['answer_id']=$val;
$this->UserAnswer->save($post_data['UserAnswer']);
endif;
endif;
endforeach;
}

Related

How to get only one row from a table using cakephp

I'm trying to retrieve data from one of the rows of a table using cakephp, and I want to get the values from the extracted row.
P.s. I've tried to follow cakephp's find(), but did not get anything, got an error instead.
Error`$login_id = $this->AppAuth->user('id');
$userSettings= $this->loadModel("UserSettings");
$userSetting= $this->$userSettings->find('first', array(
'conditions' => array('UserSettings.user_id' => $login_id)));`
From cakephp siteGot it.
$query = $internSettings->find('all', [
'conditions' => ['InternSettings.intern_id' => $login_id]
]);
$row = $query->first();
Now that I can retrieve a row, how am I suppose to access the values of the row?
$record = $internSettings->find('all', [ 'conditions' => ['InternSettings.intern_id' => $login_id]])->first();
This will returns Entity object in $record, you can access field by
echo $record->field_name;
or you can convert it in array and then you can access
$recordArr=$record->toArray();
echo $recordArr['field_name'];

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.

Why I can't see the result of HABTM?

I am using cakephp since few months, and I have a problem today that I don't know why it is not working as always.
I've got three table:
posts
comments
posts_comments
In the models, I set :
Comment Model:
var $hasAndBelongsToMany = array('Post');
Post Model
var $hasAndBelongsToMany = array('Comment');
Then in my controller, for example the PostController:
$this->set('comments', $this->Post->Comment->find('list', array('order' => 'Comment.id')));
And then in my Post View I have :
<?php
echo $this->Form->create('Post');
echo $this->Form->input('name', array('label' => 'Name', 'maxlength' => '100'));
echo $this->Form->input('Comment.Comment', array('label' => 'New Comment', 'type' => 'select', 'multiple' => true));
echo $this->Form->submit('Add', array('class' => 'button'));
?>
In my others projects it always worked !
I always had my "Comment" displayed on the list, but here, I don't know why it is not working, nothing is displayed, did I forgot something ?
Regards,
4m0ni4c.
I don't know if you solved it yet, but according to Cake convention, the HABTM tables should be named alphabeticaly for them to work magically.
This new join table’s name needs to include the names of both models involved, in alphabetical order, and separated with an underscore ( _ ). The contents of the table should be two fields, each foreign keys (which should be integers) pointing to both of the primary keys of the involved models
So your posts_comments table should be comments_posts, unless you change the association directly on Post and Comment model.

cakephp view printing out the same values from database

created a view function and any time i click the link to view a template, the url at the top of the page is correct but it spits out the same list of fields in the database.
the fields are
accounts - id, company name, abn
template - id, name, description, account_id
field - id, name, field type, template_id
function view(){
$accounts=$this->User->AccountsUser->find('list',
array('fields'=>array('id', 'account_id'),
'conditions' =>array('user_id' =>
$this->Auth->user('id'))));
$templates=$this->Template->find('first',
array('conditions' => array(
'Template.account_id' => $accounts)));
$fields=$this->Field->find('all',
array('conditions' => array(
'Field.template_id' => Set::extract('/Template/id', $templates))));
$this->set('template', $templates);
$this->set('account', $accounts);
$this->set('field', $fields);
}
here is the view
<div class = "conlinks">
</br></br></br></br></br><h2>Here is your template fields</h2></br>
<?php foreach($field as $fields): ?>
<tr>
<td align='center'><?php echo $fields['Field']['name']; ?>
</tr></br>
<?php endforeach; ?>
</div>
so the problem is its grabbing the exact same list of fields, not the correct template_id when it prints out the fields
You should be able to debug this for yourself. Just narrow the bug down step by step.
For starters, in your view function, do a print_r on the following variables, and make sure each one contains a logical result:
$accounts
$templates
$fields
If you find unexpected results there, I'd be looking at the parameters you pass into each of your finds, and making sure they're OK. You're passing in $accounts as an array to your find condition - make sure it matches the format that cake expects. Do the same for Set::extract('/Template/id', $templates).
Also look at the SQL that Cake is producing.
If you're not already using it, I'd highly recommend installing Cake's Debug Kit Toolbar - https://github.com/cakephp/debug_kit/ because it makes debugging variables and SQL much easier.
If you do the above steps and can't solve your problem, you should at least be able to narrow it down to a line or two of code. Update your answer to show what line or two is causing the problem, and include print_r's of some of the variables you're working with. That should help others on StackOverflow to give you a specific answer.
Hope that helps!
the issue was I wasn't getting the parameters when click the link
function view($name){
$fields = $this->Template->Field->find('list',array(
'fields'=> array('name'),
'conditions' => array(
'template_id'=> $name)));
$this->set('field', $fields);
}
and the view
<div class = "conlinks">
</br><h2>Here is your template fields</h2>
<?php foreach($field as $name): ?>
<tr>
<td align='center'>
<?php echo $name; ?>
</tr></br>
<?php endforeach; ?>
</br>
<?php
echo $this->Html->link('Back', '/templates/view', array('class' => 'button'));?>
</div>

Checking boxes with associated with HABTM in CakePHP

So, I have models associated via HABTM. In one view, I'm using checkboxes to save associations. I can save data no problem. But what I can't determine is how cleanly check boxes of pre-existing associations, say, when I go onto an Edit page and want to edit associations.
In this case, I have a User model and a Survey model.
Here's the code for my view:
foreach ($users as $user) {
echo $this->Form->input('User.User.', array('type' => 'checkbox', 'value' => $user['User']['id'], 'hiddenField' => false, 'label' => false )) . ' ' . $user['User']['username'];
}
There must be a way to simply mark boxes as selected where appropriate.

Resources