Cakephp HABTM saving -.- - cakephp

I'm googling high and low on this. I'm not sure where i went wrong cause I don't get any errors.
i have 3 tables:
MOVIES - id, title, genre, etc
GENRES - id, genre
GENRES_MOVIES - movie_id, genre_id
Movie model:
public $hasAndBelongsToMany = array(
'Genre' => array(
'className' => 'Genre',
'joinTable' => 'genres_movies',
'foreignKey' => 'movie_id',
'associationForeignKey' => 'genre_id'
)
);
View:
echo $this->Form->create('Movie', array('controller' => 'movies', 'action' => 'add', 'type' => 'file'));
echo $this->Form->input('title');
echo $this->Form->input('description', array('type' => 'textarea');
echo $this->Form->input('imdb_url');
echo $this->Form->year('release_year', 1900, date('Y'));
echo $this->Form->input('length', array('type' => 'number'));
echo $this->Form->input('genre', array('type'=>'select', 'multiple'=>'checkbox', 'options'=> $genres));
echo $this->Form->input('image', array('type' => 'file'));
echo $this->Form->button('Submit');
MoviesController:
public function add()
{
/* for populating checkbox */
$this->set('genres', $this->Movie->Genre->find('list', array('fields' => array('Genre.id', 'Genre.genre'))));
if($this->request->is('post'))
{
$data_movie = array(
'title' => $this->request->data['Movie']['title'],
'description' => $this->request->data['Movie']['description'],
'imdb_url' => $this->request->data['Movie']['imdb_url'],
'release_year' => (int)$this->request->data['Movie']['release_year']['year'],
'length' => (int)$this->request->data['Movie']['length'],
'user_id' => (int)$this->Auth->user('id')
);
$data_genre = array('Genre' => array());
foreach($this->request->data['Movie']['genre'] as $genre)
array_push($data_genre['Genre'], (int)$genre);
$data = array('Movie' => $data_movie, 'Genre' => $data_genre);
$this->Movie->create();
if($this->Movie->save($data)
{
echo 'success';
}
}
}
So, why did I bother setting up data manually for saving in the movieController, it is because the tutorials are telling me data should be organised like it is now (before that it looked a little different.. so i tried and this is what i have now (it looks ok to me)
http://s10.postimg.org/ikewszo95/Untitled_1.jpg
you can see the form here http://marko-stimac.iz.hr/temp/movies/movies/add (although submit wont work, i guess it is because of the Auth component not letting non-registered users)
hm any help would be greeatly appreciated :)
EDIT - updated controller
public function add()
{
$this->set('genres', $this->Movie->Genre->find('list', array('fields' => array('Genre.id', 'Genre.genre'))));
if($this->request->is('post'))
{
($this->Movie->saveAssociated($this->request->data))
{
$this->redirect('/');
$this->Session->setFlash('Success.');
}
}
}

Don't modify the data, that is, get rid of these lines
$data_genre = array('Genre' => array());
foreach($this->request->data['Movie']['genre'] as $genre)
array_push($data_genre['Genre'], (int)$genre);
$data = array('Movie' => $data_movie, 'Genre' => $data_genre);
$this->Movie->create();
And save your data using
if ($this->Movie->saveAssociated($this->request->data) {
...
EDIT
Modify your form, change this
echo $this->Form->input('genre', array('type'=>'select', 'multiple'=>'checkbox', 'options'=> $genres));
to this
echo $this->Form->input('Genre', array('type'=>'select', 'multiple'=>'checkbox', 'options'=> $genres));

Related

cakedc search not working

I've tried every simple cakedc search setup, and followed code samples from previous posts on this but it just won't seem to cooperate for me. I'm not sure, but there doesn't seem to be any search query generated with the search string, judging from a query log I have running on my database.
When I try to search, from /books/search, I get no results on a title I know is in the database and the URL changes to /books/index/title:sweet (I'm not sure if that is relevant).
Any help would be much appreciated.
Model
public $actsAs = array('Search.Searchable');
public $primaryKey = 'isbn13';
public $hasMany = array(
'Contributor' => array (
'className' => 'Contributor',
'foreignKey' => 'isbn13'
),
'Override' => array (
'className' => 'Override',
'foreignKey' => 'isbn13'
)
);
public $filterArgs = array(
'title' => array('type' => 'query', 'method' => 'filterTitle'),
'main_desc' => array('type' => 'value')
);
public function filterTitle($data, $field = null) {
if (empty($data['title'])) {
return array();
}
$titleField = '%' . $data['title'] . '%';
return array(
'OR' => array(
$this->alias . '.title LIKE' => $titleField,
));
}
Controller
class BooksController extends AppController {
public $helpers = array ('Html', 'Form');
public $paginate = array();
public $components = array('Search.Prg');
public $presetVars = true;
public function index() {
//get books
$this->set('books', $this->Book->find('all'));
//search
/* $this->Prg->commonProcess();
$this->paginate['conditions'] = $this->Book->parseCriteria($this->Prg->parsedParams());
$this->set('books');
*/
}
public function search($books = NULL) {
$this->Prg->commonProcess();
$this->paginate['conditions'] = $this->Book->parseCriteria($this->passedArgs);
$this->set('books', $this->paginate());
}
View
<h1>Search Results</h1>
<?php
echo $this->Form->create('Book' , array(
'url' => array_merge(array('action' => 'search'), $this->params['pass'])
));
echo $this->Form->input('title', array('div' => false, 'empty' => true)); // empty creates blank option.
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();
Routes
Router::connect('/', array('controller' => 'books', 'action' => 'index'));
Router::connect('/index/*', array('controller' => 'books', 'action' => 'search'
));
Router::connect('/view/:url', array('controller' => 'books', 'action' => 'view', array('url' => '[\w\W]*')
));
Router::connect('/edit/:url', array('controller' => 'books', 'action' => 'edit', array('url' => '[\w\W]*')
));
Router::connect('/whatsnew/*', array('controller' => 'books', 'action' => 'whatsnew'
));
Router::connect('/search/*', array('controller' => 'books', 'action' => 'search'
));
I've renamed the search-master folder to Search and put it in my plugins directory and In my bootstrap.php I've loaded the plugin
CakePlugin::load('Search');
Fixed! Needed
$this->set('books', $this->paginate($this->Book->parseCriteria($this->passedArgs)));'
instead of
$this->set('books', $this->paginate());'
in the controller. Not sure why though..

Search functionality not working using ID field input

I am using the search plugin on https://github.com/cakedc/search. I am trying to search for records using the ID field only, that is if i type in 1 on my form input it must show a record with user ID 1. The challenge that i am having now is when i specify that the input should be the id field, the input field for the search functionality disappears on my index view, strange thing is when i specify a different field name the input field shows.
Below is my code for my Model
public $actsAs = array('Search.Searchable');
public $filterArgs = array(
'id' => array('type' => 'like', 'field' => 'ItSupportRequest.id'),
);
public function findByTags($data = array()) {
$this->Tagged->Behaviors->attach('Containable', array('autoFields' => false));
$this->Tagged->Behaviors->attach('Search.Searchable');
$query = $this->Tagged->getQuery('all', array(
'conditions' => array('Tag.name' => $data['tags']),
'fields' => array('foreign_key'),
'contain' => array('Tag')
));
return $query;
}
public function orConditions($data = array()) {
$filter = $data['filter'];
$cond = array(
'OR' => array(
$this->alias . '.id LIKE' => '%' . $filter . '%',
));
return $cond;
}
and here is my controller code.
public $components = array('Search.Prg');
public $presetVars = true; // using the model configuration
public function find() {
$this->Prg->commonProcess();
$this->paginate['conditions'] = $this->ItSupportRequest->parseCriteria($this->passedArgs);
$this->set('articles', $this->paginate());
}
and in my index.ctp file i have this code.
<?php
echo $this->Form->create('ItSupportRequest', array(
'url' => array_merge(array('action' => 'find'), $this->params['pass'])
));
echo $this->Form->label('Query ID:') . "<br/>";
echo $this->Form->input('name', array('div' => false, 'label' => false));
echo $this->Form->submit(__('Search'), array('div' => false));
echo $this->Form->end();
?>
Thanks in advance.
You should not call it id as id will be hidden (because cake assumes this is a primary key here).
Either name it something else or manually overwrite this behavior using
$this->Form->input('id', array('type' => 'text'));
But I would go with sth like "search" and
$this->Form->input('search', array('placeholder' => 'ID to look for'));
and
public $filterArgs = array(
'search' => array('type' => 'like', 'field' => 'ItSupportRequest.id'),
);

CakePHP 2.3: Save multiple forms in multiple tables all at once in 1 page

I'm trying to set up a commercial proposal system using CakePHP 2.3.
It has 5 tables which are associated (see details below).
This system will have 1 page on which are 5 forms for each table. (see details below).
Form 1: table proposals
Form 2: table clients FK proposal_id
Form 3: table products FK client_id
Form 4: table specifications FK product_id (of the product)
Form 5: table appendices FK product_id (of the product)
WHERE:
proposals hasOne clients.
----------v----------
clients beongsTo proposals AND hasMany products.
----------v----------
products belongsTo clients AND hasMany specifications & appendices.
----------v----------
specifications belongsTo products.
appendices belongsTo products.
The form 4 can have multiple row so it's inside a foreach loop to generate more input. Same for the form 5. Because 1 product can have multiple specifications and appendices.
I admit, it's pretty tricky :)
This is the solution I finally chose, but maybe there is better. For exemple, I could make a multi-step form but it seems quite difficult to put in place. Anyway, i'm open to suggestion.
Meanwhile, I'm sure we can make this work so here are the details. For each table, I have created a model and made the appropriated connections. In each model I have enable the containable behaviour: public $actsAs = array('Containable');.
Now here is the ProposalsController.php:
function admin_edit($id=null){
$this->loadModel('Proposal','Client','Product', 'Specification', 'Appendice');
$this->Proposal->contain('Proposal','Client','Product', 'Specification', 'Appendice');
if ($this->request->is('put') || $this->request->is('Post')) {
$data = $this->request->data;
if (!empty($data)) {
// Use the following to avoid validation errors:
// unset($this->Proposal->Client->validate['proposal_id']);
// $this->Proposal->saveAssociated($data);
// $this->Session->setFlash("Le contenu a bien été édité");
// $this->redirect(array('action' => 'index', $data['Product']['id']));
debug($data);
}
}
elseif($id){
$this->Proposal->id = $id;
$this->request->data = $this->Proposal->read(null,$id);
}
}
This edit action has many errors because I don't know how to set it up correctly in that case. So forgive me but I give you a raw code :). I would like this admin_function to add or edit, but again, in this case I don't know how to handle it.
And the view admin_edit.ctp :
<hr/>
<h1>Proposition</h1>
<hr/>
<?php echo $this->Form->create('Product'); ?>
<?php echo $this->Form->input('Proposal.name', array('label' => "Nom de la proposition")); ?>
<?php echo $this->Form->input('Proposal.created', array('label' => "Date de création")); ?>
<?php echo $this->Form->input('Proposal.due', array('label' => "Date d'échéance")); ?>
<?php echo $this->Form->input('Proposal.content', array('label' => "Termes & conditions")); ?>
<hr/>
<h1>Client</h1>
<hr/>
<?php echo $this->Form->input('Client.name', array('label' => "Nom du client")); ?>
<?php echo $this->Form->input('Client.project', array('label' => "Nom du projet")); ?>
<?php echo $this->Form->input('Client.address', array('label' => "Adresse")); ?>
<?php echo $this->Form->input('Client.phone', array('label' => "Téléphone")); ?>
<?php echo $this->Form->input('Client.email', array('label' => "Email")); ?>
<?php echo $this->Form->hidden('Client.proposal_id'); ?>
<hr/>
<h1>Produit</h1>
<hr/>
<?php echo $this->Form->input('Product.0.name', array('label' => "Nom du produit")); ?>
<?php echo $this->Form->input('Product.0.reference', array('label' => "Référence")); ?>
<?php echo $this->Form->input('Product.0.image', array('label' => "Image")); ?>
<?php echo $this->Form->input('Product.0.pu', array('label' => "Prix Unitaire")); ?>
<?php echo $this->Form->input('Product.0.quantity', array('label' => "Quantité")); ?>
<?php echo $this->Form->input('Product.0.ce', array('label' => "CE")); ?>
<?php echo $this->Form->input('Product.0.nf', array('label' => "NF")); ?>
<?php echo $this->Form->input('Product.0.rohs', array('label' => "RoHS")); ?>
<?php echo $this->Form->hidden('Product.0.client_id'); ?>
<hr/>
<h1>Spécifications :</h1>
<hr/>
<?php
foreach (range(0,1) as $i):
$a=$i+1;
echo '<p>Spécification '.$a.'</p>';
echo $this->Form->input('Specification.'.$i.'.name', array('label' => "Nom de la spécification"));
echo $this->Form->input('Specification.'.$i.'.value', array('label' => "Valeur de la spécification"));
echo $this->Form->hidden('Specification.'.$i.'.product_id');
endforeach;
?>
<hr/>
<h1>Annexes :</h1>
<hr/>
<?php
foreach (range(0,1) as $j):
$b=$j+1;
echo '<p>Annexe '.$b.'</p>';
echo $this->Form->input('Appendice.'.$j.'.name', array('label' => "Image"));
echo $this->Form->input('Appendice.'.$j.'.content', array('label' => "Description de l'annexe"));
echo $this->Form->hidden('Appendice.'.$j.'.product_id');
endforeach;
?>
<?php echo $this->Form->end('valider'); ?>
And finally, here is the array result of the debug($data):
array(
'Proposal' => array(
'name' => 'Proposition 3',
'created' => array(
'month' => '02',
'day' => '19',
'year' => '2013',
'hour' => '08',
'min' => '27',
'meridian' => 'am'
),
'due' => array(
'month' => '02',
'day' => '19',
'year' => '2013',
'hour' => '08',
'min' => '27',
'meridian' => 'am'
),
'content' => 'Termes & conditions'
),
'Client' => array(
'name' => 'Client 3',
'project' => 'Projet Client 3',
'address' => 'Adresse Client 3',
'phone' => 'Téléphone Client 3',
'email' => 'Email#test.com',
'proposal_id' => ''
),
'Product' => array(
(int) 0 => array(
'name' => 'Produit 3',
'reference' => 'Référence Produit 3',
'image' => 'Image Produit 3',
'pu' => '100.77',
'quantity' => '1000',
'ce' => '1',
'nf' => '0',
'rohs' => '0',
'client_id' => ''
)
),
'Specification' => array(
(int) 0 => array(
'name' => 'Specification 1',
'value' => 'Valeur 1',
'product_id' => ''
),
(int) 1 => array(
'name' => 'Specification 2',
'value' => 'Valeur 2',
'product_id' => ''
)
),
'Appendice' => array(
(int) 0 => array(
'name' => 'Image annexe 1',
'content' => 'Description de l'annexe',
'product_id' => ''
),
(int) 1 => array(
'name' => 'Image annexe 2',
'content' => 'Description de l'annexe',
'product_id' => ''
)
)
)
So in this array, everything is there. I just need to take these data and save them all in the corresponding tables. The first problem is to manage with the table's associations. Then the 2 foreach loops that generate multiple row.
I would like to save it all at once but is it even possible?
After trying many ways to get it work, I've gone completely crazy and I just lost myself. I'm really desperate on that one, i mix up everything between the saving method and the request->data that contains everything but cannot get it saved. Anyway, i'm desperately in need for help!
Thank you very much in advance for all the help you can give me, I really appreciate!
[EDIT]
I add my model to the present post for more detail.
Proposal.php:
<?php
class Proposal extends AppModel {
public $actsAs = array('Containable');
public $validate = array(
'name' => array(
'rule' => 'notEmpty',
'message' => "Veuillez préciser un titre"
)
) ;
public $hasOne = array(
'Client' => array(
'className' => 'Client',
'foreignKey' => 'proposal_id',
'dependent' => true
)
);
}
Client.php:
<?php
class Client extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array(
'Proposal' => array(
'className' => 'Proposal',
'foreignKey' => 'proposal_id'
)
);
public $hasMany = array(
'Product' => array(
'className' => 'Product',
'foreignKey' => 'client_id',
'conditions' => '',
'order' => '',
'limit' => '',
'dependent' => true
)
);
}
Product.php:
<?php
class Product extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array(
'Client' => array(
'className' => 'Client',
'foreignKey' => 'client_id'
)
);
public $hasMany = array(
'Specification' => array(
'className' => 'Specification',
'foreignKey' => 'product_id',
'conditions' => '',
'order' => '',
'limit' => '',
'dependent' => true
),
'Appendice' => array(
'className' => 'Appendice',
'foreignKey' => 'product_id',
'conditions' => '',
'order' => '',
'limit' => '',
'dependent' => true
)
);
}
Specification.php:
<?php
class Specification extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array(
'Product' => array(
'className' => 'Product',
'foreignKey' => 'product_id'
)
);
}
Appendice.php:
<?php
class Appendice extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array(
'ProductAppend' => array(
'className' => 'Product',
'foreignKey' => 'product_id'
)
);
}
What's the output when you save the data?
if (!empty($this->data)) {
$this->Proposal->save($this->data);
}
You should also check the sql-output
echo $this->element('sql_dump');
edit:
Well after your edit, on the first look it seems that your relations are wrong.
Check out the examples in the book: http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
For example hasOne: the other model contains the foreign key.
As I said earlier, you should try to start with just one relation, getting it to work. Afterwords, it'll be much easier to get the other working. So try to comment-out everything except your Proposal and Client model. Then try saving just those two.

CakePHP Uploader Plugin only works on one Model

I've installed Miles Johnson's Uploader plugin and set it up with one of my models and got it working perfectly. Very nice.
Then I went and set it up on another model with almost identical code [the only difference is the upload path] and it won't work on the second model. When I submit the form the plugin doesn't seem to notice; I get an SQL error from an attempt to insert the POST file array straight into the DB.
Here is the code. [Other than this the plugin is imported in the bootstrap]
public $actsAs = array(
'Uploader.Attachment' => array(
'photo' => array(
'name' => 'formatFileName',
'uploadDir' => '/uploads/uses/img/',
'dbColumn' => 'photo',
'maxNameLength' => 30,
'overwrite' => true,
'stopSave' => true,
'allowEmpty' => false,
'transforms' => array(
array('method' => 'resize', 'width' => 240, 'dbColumn' => 'photo_thumb'))
)
),
'Uploader.FileValidation' => array(
'fileName' => array(
'extension' => array('gif', 'jpg', 'png', 'jpeg'),
'required' => true
)
)
);
This is on the model that is not uploading and the only difference is the uploadDir.
Does the plugin only work on one model? Any clues? thnx :}
Edit for extra clarity
Here is my view code:
echo $this->Form->create('Use', array('type' => 'file'));
echo $this->Form->input('Use.photo', array('type' => 'file'));
echo $this->Form->input('Use.desc', array('rows' => '3', 'label' => 'Description'));
echo $this->Form->end('Add to Gallery');
And here is my controller code:
public function add() {
if ($this->request->is('post')) {
$this->Use->set('user_id', $this->Auth->user('id'));
if ($this->Use->save($this->request->data)) {
$this->Session->setFlash('Your Use has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your Use.');
}
}
}
The plugin doesn't work in only one model. You can add more uploader into your site.
The model seems to be good, I suggest you to see into your form to see if you have create the form in the right way into your view (is imporant to put into your form: 'type' => 'file'
example:
echo $this->Form->create('Product', array ('class' => 'form', 'type' => 'file'));
echo $this->Form->input('ModelImage.filename', array('type' => 'file'));
echo $this->Form->submit('Add Image', array('id'=>'add_image'));
echo $this->Form->end();
Or the problem is the name Use try to change the name with another
After checking thru the code with Alessandro [thank you :)] I found the problem.
If you look in the View and Controller code you can see that the model is named 'Use'. This was the problem, as Use is a loaded word in PHP and I shouldn't have used it for a model name.
I renamed the model to Outcome and now the Uploader works perfectly.

Cakephp isPut() Save Logic

help me to fix isPut or isPost for save logic, in the following code i can view the data in the from, but when i am trying to save it its not working, i have tried ispost and isput logic both are not working. i think problem is with controller sections not with view
here is view of my form,
<?php
echo $this->Form->create('Role',array('url'=>array('controller'=>'Organisations','action' => 'edit_profile'),'id' => 'role'));
echo $this->Form->input('RoleLanguage.rolename',array('label'=>'Profile Name:','id'=>'rolename'));
$options = array('A' => 'Approve', 'P' => 'Pending', 'D' => 'Delete');
echo $this->Form->input('Role.status', array(
'options'=>$options,
'empty' => false,
'label'=>'Status',
'style'=>'width:100px',
'id'=>'status'
));
$id= array('value' => $id);
//print_r($id);die();
echo $this->Form->hidden('rle_id', $id);
echo "<br>";
$options = array('R' => 'Role', 'P' => 'Position', 'T' => 'Team','C'=>'Core Strategic Profile');
echo $this->Form->input('Role.type', array(
'options'=>$options,
'empty' => false,
'label'=>'Type of Job Profile:',
'style'=>'width:100px',
'id'=>'type'
));
echo "<br>";
echo $this->Form->input('RoleLanguage.external_document_URL',array('label'=>'External Document URL:','id'=>'external_document_URL','type'=>'text'));
echo "<br>";
echo $this->Form->input('RoleLanguage.description', array('style'=>'width:420px','rows' => '5', 'cols' => '5','label'=>'Description','id'=>'description'));
?>
here is controller logic
function edit_profile($id=NULL)
{
$this->layout='Ajax';
//print_r($id);die();
$this->set('id',$id);
$this->Role->recursive = 0;
$this->Role->id = $id;
$language = $this->getLanguage('content');
$this->Role->unBindModel(array("hasMany" => array('RoleLanguage')));
$this->Role->bindModel(array("hasOne" => array('RoleLanguage'=> array('foreignKey' => 'rle_id', 'className' => 'RoleLanguage', 'type' => 'INNER', 'conditions' => array('RoleLanguage.language' => $language)))));
$this->data = $this->Role->read();
//print_r($this->data);die();
if ($this->RequestHandler->isPut())
{
$this->data=array(null);
$this->autoRender = false;
$acc_id = $this->activeUser['User']['acc_id'];
$this->data['Role']['acc_id'] = $acc_id;
unset($this->Role->RoleLanguage->validate['rle_id']);
print_r($this->data);die();
$this->Role->saveAll($this->data);
}
}
i am serializing data in another view from where i am calling the qbove view code for that is
$.ajax({
type: 'Put',
url: $('#role').attr('action'),
data: $('#role').serialize()
It could be that the data is failing the model validation test that occurs when you call saveAll.
Have you tried printing $this->Role->invalidFields() to see if there is anything there?

Resources