CakePHP:无法将表单内容写入数据库

时间:2013-04-20 20:38:20

标签: database cakephp

我获取表单的内容以写入数据库。我的代码如下:

查看(index.ctp):

<div class="modal fade" id="test_modal">
      <div class="modal-header">
        <a class="close" data-dismiss="modal">&times;</a>   
        <h1>Create Customer</h1>
      </div>
      <div class="modal-body"> 
        <?php
        echo $this->Form->create('Contact');
        echo $this->Form->input('type');
        echo $this->Form->input('name');
        echo $this->Form->input('company');
        echo $this->Form->input('phone');
        echo $this->Form->input('mobile');
        echo $this->Form->input('email');
        echo $this->Form->input('vatNumber');

        echo $this->Form->input('mainAddressLine1');
        echo $this->Form->input('mainAddressLine2');
        echo $this->Form->input('mainAddressTown');
        echo $this->Form->input('mainAddressCounty');
        echo $this->Form->input('mainAddressPostCode');
        echo $this->Form->input('mainAddressCountry');

        echo $this->Form->input('notes', array('rows' => '5'));
        echo $this->Form->end('Save Customer');
        ?>
      </div>
    </div>

Controller(ContactController.php)

class ContactsController extends AppController {
    public $helpers = array('Html', 'Form', 'Session');
    public $components = array('Session');

    public function index() {
        $this->set('contacts', $this->Contact->find('all'));
    }

    public function view($id) {
        if (!$id) {
            throw new NotFoundException(__('Invalid contact'));
        }

        $contact = $this->Contact->findById($id);
        if (!$contact) {
            throw new NotFoundException(__('Invalid contact'));
        }
        $this->set('contact', $contact);
    }

    public function add() {                 
        if ($this->request->is('post')) {
            $this->Contact->create();
            if ($this->Contact->save($this->request->data)) {
                $this->Session->setFlash('Your contact has been saved.');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to add your contact.');
            }
        }
    }
}

模型(Contact.php)

class Contact extends AppModel {    
}

任何帮助表示感谢。

此致 斯蒂芬

1 个答案:

答案 0 :(得分:0)

如果您的视图文件是index.ctp,则意味着默认情况下处理逻辑thta是在Controller的index()方法中。该方法仅设置变量。我假设你正在混淆视图/动作。请尝试在add.ctp视图中添加您的表单,然后调用contacts/add URI。

或者,您可以通过向$this->render方法添加add()来覆盖要呈现的视图:

public function add() {
    $this->autoRender = false;
    // Rest of your logic
    $this->render('index');
}

这样,contacts/add URI将提供index.ctp视图,而不是add.ctp

相关问题