i have 2 table:
tickets :
`CREATE TABLE IF NOT EXISTS `tickets` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nom_model` varchar(32) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`date_modif` date NOT NULL,
PRIMARY KEY (`id`));`
details:
`CREATE TABLE IF NOT EXISTS `details` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ticket_id` int(11) NOT NULL,
`nom` varchar(32) NOT NULL,
`text` varchar(32) NOT NULL,
`taille` enum('8','9','10','11','12','13','14','15','16','17','18','19','20') NOT NULL,
`police` enum('Impact','courier new','times new roman','comic sans ms') NOT NULL,
`bold` int(2) NOT NULL,
`italic` int(2) NOT NULL,
PRIMARY KEY (`id`),
KEY `ticket_id` (`ticket_id`));`
the tickets have 11 zone (msg_acc, nom_buro,heure, date ....)
which are the attributes of fields nom in table details
and in one zone have (text, police, bold, italic)
therefore must save 11 rows in table (details)
i want to creat form (contains nom model in table ticket and save 11 rows in table details with foreign key ticket_id in table details is the new ticket create (nom_model) ):
I create form save 11 rows market is well but th foreing key not worked
nom_model not save in table (tickets) and the 11 rows save with ticket_id equal 0
the code in model Ticket.php
<?php
class Ticket extends AppModel
{
var $name = 'Ticket';
public $displayField='id';
public $hasMany = array(
'Detail'
);
}
?>
the code in model Detail.php
<?php
class Detail extends AppModel{
var $name = 'Detail';
public $belongsTo = array(
'Ticket'
);
}
?>
the code in controller detailsController.php
$this->set('title_for_layout', __('Add Details'));
$tickets= $this->Detail->Ticket->find('list');
if (!empty($this->request->data)) {
if($this->Detail->saveAll($this->request->data['Detail'])){
$this->Session->setFlash(__('The Model has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The Model could not be saved. Please, try again.'));
}
$this->redirect(array('action' => 'index'));
}
$this->set('tickets', $tickets);
th code in view add.ctp
<?php echo $this->form->create('Detail');?>
<fieldset>
<legend>Add New Detail</legend>
<?php
echo $this->form->input('Ticket.$i.nom_model');//not working
for($i=0;$i<$count;$i++){
echo $this->form->input("Detail.$i.name");
echo $this->form->input("Detail.$i.text");
echo $this->form->input("Detail.$i.taille");
echo $this->form->input("Detail.$i.police");
echo $this->form->input("Detail.$i.bold");
echo $this->form->input("Detail.$i.italic");
$this->form->hidden('ticket_id');} ?> </fieldset>
<?php echo $this->form->end('Submit');?>
You are saving your request data by saveAll without your associated Ticket.
The associated data of Ticked is located in $this->request->data['Ticket'] and will be ignored:
//(Line 4 of your posted controller)
$this->Detail->saveAll($this->request->data['Detail'])
Update:
Your $this->request->data should have the following structure:
Array
(
[Ticket] => Array
(
[id] => 1
...
)
[Detail] => Array
(
[0] => Array
(
[ticket_id] => 1
...
)
[1] => Array
(
[ticket_id] => 1
...
)
..........
)
)
Adapt your View, generating that datafield and you can try to save your posted data via $this->Detail->saveAll($this->request->data)
Update
Your View in basic should look like the following:
<fieldset>
<legend>Add New Detail</legend>
<?php
echo $this->form->input("Ticket.nom_model");
echo $this->form->hidden("Ticket.id", array('value' => '1'));
for($i=0;$i < $count;$i++){
echo $this->form->input("Detail.$i.name");
echo $this->form->input("Detail.$i.text");
echo $this->form->input("Detail.$i.taille");
echo $this->form->input("Detail.$i.police");
echo $this->form->input("Detail.$i.bold");
echo $this->form->input("Detail.$i.italic");
echo $this->form->hidden("Detail.$i.ticket_id", array('value' => '1'));} ?>
<?php echo $this->form->end('Submit');?>
</fieldset>
This is an example view, that references Detail to Ticket via Ticked.id = 1
Update:
You should define the foreign key from Detail to Ticket in your Models/Detail.php:
public $belongsTo = array(
'Ticket' => array(
'className' => 'Ticket',
'foreignKey' => 'ticket_id'
)
);
Related
In Cakephp3, I have the following tables:
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`created` datetime NOT NULL,
`modified` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `roles` (
`id` int(11) NOT NULL,
`title` varchar(45) DEFAULT NULL,
`created` datetime NOT NULL,
`modified` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `roles_users` (
`id` int(11) NOT NULL,
`note` text,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
`role_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
My intention is, to edit the available fields in table 'roles_users' within the Users add & edit view (and the related controller actions). I considereded https://book.cakephp.org/3.0/en/views/helpers/form.html#associated-form-inputs, my user view (edit) look like:
<div class="users form large-9 medium-8 columns content">
<?= $this->Form->create($user) ?>
<fieldset>
<legend><?= __('Edit User') ?></legend>
<?php
echo $this->Form->control('name');
echo $this->Form->control('roles.0._joinData.role_id', ['type'=>'select', 'options' => $roles]);
echo $this->Form->control('roles.1._joinData.role_id', ['type'=>'select', 'options' => $roles]);
echo $this->Form->control('roles.2._joinData.role_id', ['type'=>'select', 'options' => $roles]);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
the underlying controller action is:
public function edit($id = null)
{
$user = $this->Users->get($id, [
'contain' => ['Roles']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user,$this->request->getData());
pr($this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$roles = $this->Users->Roles->find('list', ['limit' => 200]);
$this->set(compact('user', 'roles'));
}
The correct data are displayed, while accessing the edit action. But when submitting the data (even unchanged) new records are saved to table 'roles'. How do I have to update the controller actions and the related views, to write data to the table 'roles_users'?
You need to add associated model in your patchEntity like below
$user = $this->Users->patchEntity($user,$this->request->getData(), [
'associated' => ['RolesUsers']
]);
https://book.cakephp.org/3.0/en/orm/saving-data.html#
echo $this->Form->control('roles.0._joinData.role_id', ['type'=>'select', 'options' => $roles])
to:
echo $this->Form->control('roles.0.id', ['type'=>'select', 'options' => $roles])
echo $this->Form->control('roles.1.id', ['type'=>'select', 'options' => $roles])
I'm a beginner. I am using CakeDC ratings to make a star rating in my site. I managed to make it work but it is displaying radio choices.
And it show me error:
Undefined variable: item
and After pressing "Rate", the url changes to avis/post/view/redirect:1
I download the plugin and I unzip in C:\wamp\www\avis\app\Plugin
after I write CakePlugin::load('Ratings') in app/Config/bootstrap.php my database is
CREATE TABLE IF NOT EXISTS `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
CREATE TABLE IF NOT EXISTS `ratings` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` char(36) NOT NULL DEFAULT '',
`foreign_key` char(36) NOT NULL DEFAULT '',
`model` varchar(100) NOT NULL DEFAULT '',
`value` float NOT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `rating` (`user_id`,`model`,`foreign_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
in Post Model
public $hasMany = array(
'Rating' => array(
'className' => 'Rating',
'foreignKey' => 'foreign_key',
'dependent' => false,
)
);
in PostController
public $components = array('Paginator', 'Flash', 'Session','Ratings.Ratings');
public $actsAs = array('Ratings.Ratable');
public function index() {
$this->Post->recursive = 0;
$this->set('posts', $this->Paginator->paginate());
}
public function view($id = null) {
if (!$this->Post->exists($id)) {
throw new NotFoundException(__('Invalid post'));
}
$options = array('conditions' => array('Post.' . $this->Post->primaryKey => $id));
$this->set('post', $this->Post->find('first', $options));
}
in view
<h2><?php echo __('Post'); ?></h2>
<dl>
<dt><?php echo __('Id'); ?></dt>
<dd>
<?php echo h($post['Post']['id']); ?>
</dd>
<dt><?php echo __('Title'); ?></dt>
<dd>
<?php echo h($post['Post']['title']); ?>
</dd>
<?php
echo $this->Rating->display(array(
'item' => $post['Post']['id'],
'type' => 'radio',
'stars' => 5,
'value' => $item['rating'],
'createForm' => array(
'url' => array(
$this->passedArgs, 'rate' => $item['id'],
'redirect' => true
)
)
));
?>
</dl>
</div>
<script>
$('#ratingform').stars({
split:2,
cancelShow:false,
callback: function(ui, type, value) {
ui.$form.submit();
}
});
</script>
First Download Jquery Raty Js plugin From : https://github.com/wbotelhos/raty
Include js,css into your view
<div class="jrating" data-score="5"></div>
<script>
$('.jrating').raty({ score: function() {return $(this).attr('data-score');} });
</script>
This will create a hidden text field when you post the form
On controller :
$rating = $this->data['score'];
Now you can save rating in your table
I simply want to have in my function (add) the file upload process in my cake application. i have tried various tutorial across the web bur I could reach the solution to my problem. I am new to cake and I dont want to reinvent the wheel I just want to learn based on what I have implemented so far. I am truly grateful for your help.
add.ctp
<?php echo $this->Form->create('Movie'); ?>
<?php echo __('Add Movie'); ?>
<?php
echo $this->Form->hidden('movie_id');
echo $this->Form->input('title');
echo $this->Form->input('date', array(
'type' => 'date',
'label' => 'Date',
'empty' => false,
'dateFormat' => 'DMY',
'minYear'=>'1990',
'maxYear'=>date('Y'),
));
echo $this->Form->input('description');
echo $this->Form->input('file', array('type' => 'file'));?>
<?php echo $this->Form->end(__('Submit')); ?>
THE CONTROLLER
public function add() {
if ($this->request->is('post')) {
$this->Movie->create();
}
if ($this->Movie->save($this->request->data))
{
$this->Session->setFlash(__('The movie has been created'));
$this->redirect (array('action'=>'index'));
}
}
Table structure for table movies
CREATE TABLE IF NOT EXISTS `movies` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`movie_id` int(11) NOT NULL,
`title` varchar(100) NOT NULL,
`file` varchar(200) NOT NULL,
`date` date NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `movie_id` (`movie_id`),
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
Create Model located at /app/Model/Movies.php
<?php
class Movie extends AppModel {
}
?>
Create Controller in app/Controller/Movies.php
<?php
class MoviesController extends AppController {
public function add() {
if ($this->request->is('post')) {
$maxId = $this->Movie->find('first', array(
'order' => 'movie_id DESC',
'fields' => array('Movie.movie_id')
));
$maxId = (isset($maxId['Movie']['movie_id'])? $maxId['Movie']['movie_id'] : 0);
$this->request->data['Movie']['movie_id'] = $maxId+1;
$folderToSaveFiles = WWW_ROOT . 'img/uploads/' ;
if(!empty($this->request->data['Movie']['file']))
{
$file = $this->request->data['Movie']['file'];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
$arr_ext = array('jpg', 'jpeg', 'gif','png');
if(in_array($ext, $arr_ext))
{
$newFilename = $this->request->data['Movie']['title'].'.'.$ext;
$result = move_uploaded_file( $file['tmp_name'], $folderToSaveFiles . $newFilename );
$this->request->data['Movie']['file'] = $newFilename;
$this->Movie->save($this->request->data);
//debug($this->request->data);
}
}
}
}
Note : Create a directory in app/webroot/img/uploads/ & upload directory must be write permission.
I am building a CakePHP 2.3 application, and can't for the life of me figure out why saveAll keeps failing.
I have the following models:
Artist hasMany ArtistPreview
ArtistPreview belongsTo Artist
I have no problem saving my Artist model with the save() function, however as soon as I try to use the saveAll method, Cake seems to fail validation - which is crazy because I have even totally removed all my validation rules from my models.
Here's my view, nothing crazy:
<?php
echo $this->Form->create('Artist', array('inputDefaults' => array('class' => 'input-block-level')));
echo $this->Form->input('Artist.name', array('label' => __('Name')));
echo $this->Form->input('Artist.artist_section_id', array('label' => __('Section'), 'empty' => true));
?>
<label>Tags</label>
<div class="checkboxes">
<?php echo $this->Form->input('Tag', array('label' => false, 'multiple' => 'checkbox', 'class' => false));; ?>
</div>
<?php
echo $this->Form->input('Artist.website', array('label' => __('Website')));
echo $this->Form->input('ArtistPreview.0.url', array('label' => __('Artist Preview')));
echo $this->Form->input('Artist.description', array('label' => __('Description')));
?>
<?php
echo $this->Form->submit(__('Add'), array('class' => 'btn btn-primary btn-large', 'div' => false)) . ' ';
echo $this->Form->button(__('Cancel'), array('type' => 'button', 'class' => 'btn btn-large', 'div' => false, 'onclick' => 'closeDialog()'));
echo $this->Form->end();
?>
And here's my add controller method:
public function add() {
$this->layout = 'form';
if (!$this->request->is('ajax')) {
throw new ForbiddenException();
}
if ($this->request->is('post')) {
$this->setData($this->request->data['Artist'], array(
'user_id' => AuthComponent::user('id'),
'date' => $this->Date->gmt()
));
if ($this->Artist->saveAll($this->request->data)) {
$this->redirectAjax('/artists/view/' . $this->Artist->id);
}
}
$this->set(array(
'title_for_layout' => 'Add Artist',
'artistSections' => $this->Artist->ArtistSection->find('list', array('order' => 'name')),
'tags' => $this->Artist->Tag->find('list', array('order' => 'name'))
));
}
As I mentioned above, the saveAll method fails everytime. I have inspected what is getting output and Cake is outputting a bunch of blank <div>s with the error-message class, but there is no message. Every field on the form gets one of these divs.
Now, when I change my code to use the save function instead of saveAll, everything gets saved properly except the ArtistPreview data, which is to be expected. Even my HABTM Tags are being saved properly, and nothing fails validation.
I have been using Cake since the 1.3 days so I'm quite familiar with it, and have even done exactly what I'm asking in previous projects. I'm leaning towards this being a bug, unless I'm missing something here. Any ideas?
EDIT
I have also tried the saveAssociated method, along with setting the deep key to true when trying to save. This will let me save the artist, but it will not save the related data (ArtistPreview).
EDIT 2
As requested, here are the two tables:
-- -----------------------------------------------------
-- Table `artists`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `artists` ;
CREATE TABLE IF NOT EXISTS `artists` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`user_id` INT UNSIGNED NULL ,
`artist_section_id` INT UNSIGNED NULL ,
`artist_status_id` INT UNSIGNED NULL ,
`name` VARCHAR(200) NULL ,
`website` VARCHAR(500) NULL ,
`description` TEXT NULL ,
`date` DATETIME NULL ,
`comment_count` INT UNSIGNED NOT NULL DEFAULT 0 ,
PRIMARY KEY (`id`) ,
INDEX `FK_artists_users_idx` (`user_id` ASC) ,
INDEX `FK_artists__artist_sections_idx` (`artist_section_id` ASC) ,
INDEX `FK_artists__artist_statuses_idx` (`artist_status_id` ASC) ,
CONSTRAINT `FK_artists__users`
FOREIGN KEY (`user_id` )
REFERENCES `users` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `FK_artists__artist_sections`
FOREIGN KEY (`artist_section_id` )
REFERENCES `artist_sections` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `FK_artists__artist_statuses`
FOREIGN KEY (`artist_status_id` )
REFERENCES `artist_statuses` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `artist_previews`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `artist_previews` ;
CREATE TABLE IF NOT EXISTS `artist_previews` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`artist_id` INT UNSIGNED NULL ,
`url` VARCHAR(500) NULL ,
`date` DATETIME NULL ,
PRIMARY KEY (`id`) ,
INDEX `FK_artist_previews__artists_idx` (`artist_id` ASC) ,
CONSTRAINT `FK_artist_previews__artists`
FOREIGN KEY (`artist_id` )
REFERENCES `artists` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
Here is my setData function, which just merges two arrays. Instead of using hidden fields, I set fields in the controller which aren't populated by user input:
public function setData(&$original, $new) {
$original = array_merge($original, $new);
}
So I finally figured this out, and wow was it a rookie mistake. I think I must've been half asleep yesterday when I was coding. The problem was in my model:
class Artist extends AppModel {
public $belongsTo = array(
'User',
'ArtistSection',
'ArtistStatus'
);
public $hasMany = array(
'ArtistPicture',
'Artist' // <--- problem was here, had 'Artist' instead of 'ArtistPreview'
);
public $hasAndBelongsToMany = array(
'Tag'
);
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->validate = array(
'name' => array(
'rule' => 'notEmpty',
'message' => __('Artist name cannot be blank.')
),
'website' => array(
'rule' => 'url',
'message' => __('Must be a valid URL.'),
'allowEmpty' => true
),
'artist_section_id' => array(
'rule' => 'notEmpty',
'message' => __('Section is required.')
)
);
}
}
Thank you to those of you who took the time to look at this question, even though I posted the wrong information.
New to Cake, and trying to set up model associations. I'm creating an execution planner, to be used by multiple teams, aka 'groups' where the base unit of a plan is an 'event'. Each event is owned by one team, but it can have many supporting teams.
When I use $scaffold in the controllers, the model associations work as expected and when adding a new event I get a select box with all the groups to select who owns an event. However, when I bake the controller using console, the select box for group_id is blank. I've included the baked add() code from the controller, and from the baked add view. I also tried debug($this) in add.ctp, and found that the list of groups is indeed being passed to the view. I'm thus mostly confused about why it works with $scaffold, but not otherwise.
Any advice or pointers in the right direction would be greatly appreciated.
Tables:
CREATE TABLE IF NOT EXISTS `events` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`group_id` int(5) NOT NULL COMMENT 'Group that owns event',
`version` int(5) NOT NULL,
`type` varchar(5) NOT NULL,
`stime` time NOT NULL,
`etime` time NOT NULL,
`description` text NOT NULL,
`comment` text NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `events_groups` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`event_id` int(5) NOT NULL,
`group_id` int(5) NOT NULL,
PRIMARY KEY (`id`)
) ;
CREATE TABLE IF NOT EXISTS `groups` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`code` varchar(4) NOT NULL,
`name` varchar(25) NOT NULL,
`liveversion` int(4) NOT NULL,
`lastupdated` date NOT NULL,
PRIMARY KEY (`id`)
);
Models:
Event:
public $belongsTo = array(
'Prigroup' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
)
);
public $hasAndBelongsToMany = array(
'Secgroup' => array(
'className' => 'Group',
'joinTable' => 'events_groups',
'foreignKey' => 'event_id',
'associationForeignKey' => 'group_id',
)
);
Group:
public $hasMany = array(
'Prievent' => array(
'className' => 'Event',
'foreignKey' => 'group_id',
)
);
public $hasAndBelongsToMany = array(
'Secevent' => array(
'className' => 'Event',
'joinTable' => 'events_groups',
'foreignKey' => 'group_id',
'associationForeignKey' => 'event_id',
)
);
EventsController Snippet:
public function add() {
if ($this->request->is('post')) {
$this->Event->create();
if ($this->Event->save($this->request->data)) {
$this->Session->setFlash(__('The event has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The event could not be saved. Please, try again.'));
}
}
$prigroups = $this->Event->Prigroup->find('list');
$secgroups = $this->Event->Secgroup->find('list');
$this->set(compact('prigroups', 'secgroups'));
}
Add view:
<?php echo $this->Form->create('Event'); ?>
<fieldset>
<legend><?php echo __('Add Event'); ?></legend>
<?php
echo $this->Form->input('group_id');
echo $this->Form->input('version');
echo $this->Form->input('type');
echo $this->Form->input('stime');
echo $this->Form->input('etime');
echo $this->Form->input('description');
echo $this->Form->input('comment');
echo $this->Form->input('Secgroup');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
Add HTML Output
<div class="input select"><label for="EventGroupId">Group</label><select name="data[Event][group_id]" id="EventGroupId">
</select></div>
Can u try something for me please? Rename the $prigroups variable to "groups" and pass it to the view. See if this is working. Otherwise use this one with your old code:
echo $this->Form->input(
'group_id',
array(
'options' => $prigroups
)
);
I also recommend you to use camel case for all those PriGroups and SecGroups. Those are two words in english so camel case advisable.
Greetings
func0der