Как настроить редактирование и добавить представления с отношением hasOne в cakePHP? - PullRequest
0 голосов
/ 15 апреля 2011

Мне было интересно, может ли кто-нибудь мне помочь.

Я использую cakePHP 1.3, и у меня возникают проблемы с отображением редактирования для обновления основной модели и связанной с hasOne модели.Я довольно уверен, что это связано с моей настройкой представления edit.ctp.Я использую медиа-плагин, который я работал над другой моделью, поэтому я не верю, что это как-то связано с этим.В частности, я работаю над тем, чтобы получить плагин Media, модель монолитного вложения с работающими отношениями hasOne.

Я проверил документы на торт
http://book.cakephp.org/#!/view/1032/Saving-Related-Model-Data-hasOne-hasMany-belongsToПрочитайте большинство документов в Media Plugin. Это как наиболее актуальное
https://github.com/davidpersson/media/blob/next/docs/RECIPESи провел много времени в поисках Google.

Любая помощь приветствуется.

Спасибо,

Джеймс

Модель - client.php

<?php
class Client extends AppModel {
var $name = 'Client';
var $displayField = 'name';
var $actsAs = array(
    'Media.Transfer',
    'Media.Coupler',
    'Media.Generator'
);

[...]
var $hasOne = array(
  'Logo' => array(
      'className' => 'Attachment',
      'foreignKey' => 'foreign_key',
      'conditions' => array('Logo.model' => 'Client'),
      'dependent' => true,
));
[...]
?>

Контроллер - clients_controller.php

<?php
class ClientsController extends AppController {

var $name = 'Clients';
    [...]
function edit($id = null) {
    if (!$id && empty($this->data)) {
        $this->Session->setFlash(__('Invalid client', true));
        $this->redirect(array('action' => 'index'));
    }
    if (!empty($this->data)) {
        if ($this->Client->saveAll($this->data, array('validate'=>'first') )) {
            $this->Session->setFlash(__('The client has been saved', true));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The client could not be saved. Please, try again.', true));
        }
    }
    if (empty($this->data)) {
        $this->Client->recursive = 0;
        $this->data = $this->Client->read(null, $id);
    }
    $statuses = $this->Client->Status->find('list');
    $this->set(compact('statuses'));
}
    [...]
    ?>

Просмотр - edit.ctp

<h1><?php __('Edit Clients');?></h1>
<div class="clients form">
<?php echo $this->Form->create('Client', array('type' => 'file'))."\n";?>
<fieldset>
<?php
   echo $this->Form->input('Client.id')."\n";
   echo $this->Form->input('Client.name')."\n";
   echo $this->Form->input('Client.address1')."\n";
   echo $this->Form->input('Client.address2')."\n";
   [...]
   echo $form->input('Logo.id')."\n";
   echo $form->input('Logo.file', array('type' => 'file'))."\n";
   echo $form->hidden('Logo.foreign_key')."\n";
   echo $form->hidden('Logo.model', array('value' => 'Client'))."\n";
    ?>
</fieldset>

<?php echo $this->Form->end(__('Submit', true));?>
</div>

клиенты sql

CREATE TABLE `clients` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `address1` varchar(255) NOT NULL,
  `address2` varchar(255) NOT NULL,
  `created` datetime default NULL,
  `modified` datetime default NULL,
  PRIMARY KEY  (`id`)
)

вложения sql

CREATE TABLE `attachments` (
  `id` int(10) NOT NULL auto_increment,
  `model` varchar(255) NOT NULL,
  `foreign_key` int(10) NOT NULL,
  `dirname` varchar(255) default NULL,
  `basename` varchar(255) NOT NULL,
  `checksum` varchar(255) NOT NULL,
  `group` varchar(255) default NULL,
  `alternative` varchar(50) default NULL,
  `created` datetime default NULL,
  `modified` datetime default NULL,
  PRIMARY KEY  (`id`)
) 

Ответы [ 2 ]

0 голосов
/ 17 апреля 2011

Спасибо за все ответы. Я наконец получил это работает. Похоже, что почему-то спасение все вызывало у меня горе. Когда я сохранил клиент, то сохранил логотип, все работало

Я разместил код ниже.

Код контроллера

function edit($id = null) {
    if (!$id && empty($this->data)) {
        $this->Session->setFlash(__('Invalid client', true));
        $this->redirect(array('action' => 'index'));
    }
    if (!empty($this->data)) {
        $client = $this->Client->save($this->data);
        if (!empty($client)) {            
            $this->data['Logo']['foreign_key'] = $this->Client->id;
            $this->data['Logo']['model'] = 'Client';
            $this->Session->setFlash(__('The client has been saved', true));
            $this->Client->Logo->save($this->data);
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The client could not be saved. Please, try again.', true));
        }
    }
    if (empty($this->data)) {
        $this->Client->recursive = 0;
        $this->data = $this->Client->read(null, $id);
    }
    $statuses = $this->Client->Status->find('list');
    $this->set(compact('statuses'));
}
0 голосов
/ 16 апреля 2011
    var $hasOne = array(
  'Logo' => array(
      'className' => 'Attachment',
      'foreignKey' => 'foreign_key', // 'foreign_key' ? is that a name for your fk?
      'conditions' => array('Logo.model' => 'Client'),
      'dependent' => true,
));

здесь вы не определили foreign_key, который привязывает ваш логотип к вашему клиенту.найдите в своей базе данных внешний ключ и введите его имя здесь.

...