0

在我的表中创建或编辑对象时,我有一个 jquery 对话框,该对话框打开了视图,用于在其中编辑或添加对象。当他们提交时,一切正常。我还向它添加了验证检查,但如果有任何验证错误,会发生什么,对话框关闭并且用户被重定向到带有验证错误消息的实际页面。

我想要做的是在对话框中显示验证错误,而不是转到页面。我环顾四周,发现我可能必须为此使用 ajax,但我不知道如何开始。

这是我的模型的代码。我删除了一些额外的东西以保持简短。

class LocalClock extends AppModel
{
    public $useDbConfig = 'default';
    public $useTable = 'local_clocks';

    public $validate = array(
        'utc_offset_sec' => array(
            'rule' => 'notEmpty',
            'rule' => 'numeric',
            'message' => 'Please Enter a Valid Number'
        ),
        'in_month' => array(
            'rule' => 'notEmpty',
            'rule' => 'numeric',
            'message' => 'Please Enter a Valid Number'
        ),
        'in_week' => array(
            'rule' => 'notEmpty',
            'rule' => 'numeric',
            'message' => 'Please Enter a Valid Number'
        ),
        'in_day' => array(
            'rule' => 'notEmpty',
            'rule' => 'numeric',
            'message' => 'Please Enter a Valid Number'
        ),
        'in_hour' => array(
            'rule' => 'notEmpty',
            'rule' => 'numeric',
            'message' => 'Please Enter a Valid Number'
        )
    );

    public function setStatType( $type )
    {
        $this->table = 'local_clocks';
        $this->_schema = array(
            'col1' => array('type' => 'int'),
            'col2' => array('type' => 'string'),
            'col3' => array('type' => 'string'),
            'col4' => array('type' => 'string'),
            'col5' => array('type' => 'string'),
    }
}
?>

这是我的控制器的代码:

class LocalClocksController extends AppController
{
    public $components = array('RequestHandler', 'Session');   // enable checking for incoming request attributes

    public $helpers = array('Html', 'Form', 'Session', 'Javascript', 'Paginator');

    public $paginate = array(
        'limit' => 10,
        'order' => array(
            'LocalClock.id' => 'asc'
        )
    );

    public function index()
    {
        $this->LocalClock->table = 'local_clocks';
        $this->LocalClock->getDataSource()->tableFields['local_clocks'] = array( "id", "name", "auto_offset", "utc_offset_sec", "in_month", "in_week", "in_day", "in_hour", "out_month", "out_week", "out_day", "out_hour", "offset_sec");

        if ($this->RequestHandler->accepts('xml'))
        {
            // xml handler
            $this->set('localClocks', $this->LocalClock->find('all'));
            $this->set('_serialize', array('local_clocks'));
            $data = $this->paginate('LocalClock');
            $this->set('localClocks', $data);
        }
        elseif ($this->RequestHandler->accepts('json'))
        {
            //json handler
            $this->set('localClocks', $this->LocalClock->find('all'));
            $this->set('_serialize', array('local_clocks'));
            $data = $this->paginate('LocalClock');
            $this->set('localClocks', $data);
        }
        elseif( $this->RequestHandler->accepts('html'))
        {
            //html handler
            //$this->LocalClock->getDataSource()->tableFields['local_clocks'] = array( "id", "name", "auto_offset", "utc_offset_sec", "in_month", "in_week", "in_day", "in_hour", "out_month", "out_week", "out_day", "out_hour", "offset_sec");
            $this->set('localClocks', $this->LocalClock->find('all'));

            $data = $this->paginate('LocalClock');
            $this->set('localClocks', $data);
        }
    }

    public function add()
    {
        if ($this->request->is('post'))
        {
            if ($this->LocalClock->save($this->request->data))
            {
                $this->set('localClocks', $this->request->data);
                $this->LocalClock->save($localClocks);
                $this->Session->setFlash('Local Clock: '. $this->request->data['LocalClock']['name'] . ' has been created.');
                $this->redirect(array('action' => 'index'));
            }
            else
            {
                $this->Session->setFlash('Unable to add new Local Clock.');
            }
        }
    }

    public function edit($id = null)
    {
        $this->LocalClock->id = $id;
        if ($this->request->is('get'))
        {
            $this->request->data = $this->LocalClock->read();
            $this->set('localClocks', $this->LocalClock->read());
        }
        else
        {
            if ($this->LocalClock->save($this->request->data))
            {
                $this->Session->setFlash('Local Clock: '. $this->request->data['LocalClock']['name'] . ' has been updated.');
                $this->redirect(array('action' => 'index'));
            }
            else
            {
                $this->Session->setFlash('Unable to update Local Clock: '. $this->request->data['LocalClock']['name']);
                $this->set('localClocks', $this->request->data);
            }
        }
    }
?>

这是我的 index.ctp 的代码:

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/start/jquery-ui.css" type="text/css" media="all" />

<p> <?php echo $this->Paginator->prev('« Previous', null, null, array('class' => 'disabled')); ?>;
<?php echo $this->Paginator->numbers(); ?>
<?php echo $this->Paginator->next('Next »', null, null, array('class' => 'disabled')); ?>; </p>

<script>
$(function() 
{
    var $dialog = $("#edit_dialog").dialog(
        {
            autoOpen: false,
            title: 'Edit Local Clock',
            height: 500,
            width: 500,
            resizable: true,
            modal: true
        });
    $(".edit_dialog").click(function()
    {
        $dialog.load($(this).attr('href'), function ()
                {
                    $dialog.dialog('open');
                });
        return false;
    });
});
</script>

<script>
$(function()
{
    var $dialog = $("#add_dialog").dialog(
        {
            autoOpen: false,
            title: 'Create Local Clock',
            height: 500,
            width: 500,
            resizable: true,
            modal: true
        });
    $(".add_dialog").click(function()
    {
        $dialog.load($(this).attr('href'), function ()
                {
                    $dialog.dialog('open');
                });
        return false;
    });
});
</script>

<p><marquee><u>Local Clocks</u></marquee></p>

<div>

<table>
    <thead><tr>
<th> <?php echo $this->Paginator->sort('id', 'ID'); ?> </th>  <th>Name      </th>  <th>Auto Offset  </th>  <th>UTC Offset Sec  </th>  <th>In Month  </th>
<th>In Week  </th>  <th>In Day    </th>  <th>In Hour      </th>  <th>Out Month       </th>  <th>Out Week  </th>
<th>Out Day  </th>  <th>Out Hour  </th>  <th>Offset Sec   </th>  <th>Actions         </th>
    </tr></thead>

    <tbody>

<?php  foreach($localClocks as $LocalClock) { ?>

        <tr>
    <td>  <?php echo $LocalClock['LocalClock']['id']; ?>              </td>
    <td>  <?php echo $LocalClock['LocalClock']['name']; ?>            </td>
    <td>  <?php echo $LocalClock['LocalClock']['auto_offset']; ?>     </td>
    <td>  <?php echo $LocalClock['LocalClock']['utc_offset_sec']; ?>  </td>
    <td>  <?php echo $LocalClock['LocalClock']['in_month']; ?>        </td>
    <td>  <?php echo $LocalClock['LocalClock']['in_week']; ?>         </td>
    <td>  <?php echo $LocalClock['LocalClock']['in_day']; ?>          </td>
    <td>  <?php echo $LocalClock['LocalClock']['in_hour']; ?>         </td>

    <td>
        <?php echo $this->Html->link('View', array('action' => 'view', $LocalClock['LocalClock']['id']), array('class' => 'view_dialog')); ?>
    <?php echo $this->Html->link('Edit', array('action' => 'edit', $LocalClock['LocalClock']['id']), array('class' => 'edit_dialog'));?>
    <?php echo $this->Form->postLink('Delete', array('action' => 'delete', $LocalClock['LocalClock']['id']), array('confirm' => 'Are you sure?')); ?>
            </td>
        </tr>
<?php } ?>

    </tbody>
</table>

</div>

<div>
    <?php echo $this->Html->link('Create Local Clock', array('action' => 'add'), array('class' => 'add_dialog')); ?>
</div>

<div id="view_dialog">
</div>

<div id="edit_dialog">
</div>

<div id="add_dialog">
</div>

最后是我的edit.ctp:

<p>Edit Settings for Local Clock: <?php echo $localClocks['LocalClock']['name']; ?> </p>

<div>

<?php echo $this->Form->create('LocalClock', array('action' => 'edit', 'inputDefaults' => array('label' => false))); ?>
<?php echo $this->Form->input('id', array('type' => 'hidden')); ?>

<table>
    <thead><tr>
        <th>Field</th>  <th>Current Value</th>  <th>New Value</th>
    </tr></thead>

    <tbody>
    <tr> <td>Name</td> <td> <?php echo $localClocks['LocalClock']['name']; ?> </td> <td> <?php echo $this->Form->input('LocalClock.name');?> </td> </tr>
    <tr> <td>Auto Offset </td> <td> <?php echo $localClocks['LocalClock']['auto_offset']; ?> </td> <td> <?php echo $this->Form->input('LocalClock.auto_offset');?> </td> </tr>
    <tr> <td>UTC Offset Sec</td> <td> <?php echo $localClocks['LocalClock']['utc_offset_sec']; ?> </td> <td> <?php echo $this->Form->input('LocalClock.utc_offset_sec');?> </td> </tr>
    <tr> <td>In Month</td> <td> <?php echo $localClocks['LocalClock']['in_month']; ?> </td> <td> <?php echo $this->Form->input('LocalClock.in_month');?> </td> </tr>
    </tbody>
</table>

<?php echo $this->Form->end('Save Changes'); ?>
</div>

如果我可以在编辑对话框中获得帮助并在不关闭和重定向到页面的情况下进行验证,那么我应该能够对 add 函数执行相同的操作。

感谢您的帮助,如果有任何不清楚或是否有人需要更多信息,请告诉我。

4

1 回答 1

1

为了解决这个问题,首先在编辑文件的末尾添加一个 ajax 提交按钮,就在 $this->Form->end() 之前。(把括号里的'Save changes'删掉,因为ajax提交可以改这么说)。

<?php
    // The Ajax Helper submit is used to submit the changes made to the edit form
    // because it allows the modal window to be loaded with the updated edit view
    // without leaving the modal window. 
    echo $this->Ajax->submit('Save Changes', array(
        'url' => array('controller' => 'localClocks', 'action' => 'edit'),
        'update' => 'editTable'));

    // Call the close Dialog() function if data was validated sucessfully; valid == true. 
    // Else it stays open displaying validation error message.
    if (false != $valid)
    {
        echo "<script>closeDialog()</script>";
    }

echo $this->Form->end(); ?>

接下来在控制器文件中,将编辑功能更改为:

public function edit($id = null)
    {
        $this->LocalClock->id = $id;
        $this->set('valid', false);
        if ($this->request->is('get'))
        {
            $this->request->data = $this->LocalClock->read();
            $this->set('localClocks', $this->LocalClock->read());
        }
        else
        {
            if ($this->LocalClock->save($this->request->data))
            {
                $this->Session->setFlash('Local Clock: '. $this->request->data['LocalClock']['name'] . ' has been updated.');
                $this->set('valid', true);
                //$this->redirect(array('action' => 'index'));
            }
            else
            {
                $this->Session->setFlash('Unable to update Local Clock: '. $this->request->data['LocalClock']['name']);
                $this->set('localClocks', $this->request->data);
                $this->set('valid', false);
            }
        }
    }

这里唯一的新内容是代码将布尔值分配给变量,以根据是否存在验证错误来确定是否关闭对话框。

就是这样。它可以直接插入其他所有内容。我希望这对其他人有帮助。

于 2012-06-13T13:03:10.127 回答