CakePHP 3.8根据用户选择更改表单数据

问题描述 投票:0回答:2

我处于CakePHP 3环境中,在该环境中,我处于Articles Controller中的Edit Action上。

控制器上的第一个功能是标准编辑功能。这将以表格的形式加载文章的现有数据,因此您可以轻松地对其进行编辑。

public function edit($id){

    $article_categories = $this->Articles->Articlecats->find('list');
    $this->set('article_categories', $article_categories);

    $article = $this->Articles->get($id);

    // if you are not just landing on page but making the save 
    if ($this->request->is(['post', 'put'])) {

        // disable entity creation, not entirely sure what this does.. 
        $this->Articles->patchEntity($article, $this->request->getData());

        // Set the user_id from the session.
        $article->user_id = $this->Auth->user('id');

        if ($this->Articles->save($article)) {

            $this->Flash->success(__('Your article has been updated.'));
            return $this->redirect(['action' => 'index']);

        }

        // check if there are errors in editing and print them
        if ($article->getErrors()){

            // Entity failed validation 
            // print_r($article->getErrors());
            $this->Flash->error(__('Please correct values and try again.'));                

        }

    $this->Flash->error(__('Unable to update your article.'));

    }

    $this->set('article_pass', $article);    

}

ArticlesController的edit方法中的视图显示输入字段,您可以在其中输入Article信息,然后将其保存到基础数据库。在视图的底部,有一个“编辑类别”按钮,可通过Ajax调用访问ArticlesController上的方法。 ArticlesController上的函数editcategory()检索有关所选类别的信息,然后将其返回到视图。

单击此按钮后,我想将类别信息加载到表单中并显示该表单。我被困在如何将检索到的类别信息加载到表单中。

<?php echo $this->Html->script('http://code.jquery.com/jquery.min.js'); ?> 

<!-- File: templates/Articles/edit.php -->

<h1>Edit Article</h1>
<?php
    echo $this->Form->create($article_pass);
    echo $this->Form->control('user_id', ['type' => 'hidden']);
    echo $this->Form->control('title');
    echo $this->Form->control('body', ['rows' => '3']);
    echo $this->Form->select('articlecat_id', $article_categories, ['id' => 'article_cat']);     
    echo $this->Form->button(__('Save Article'));
    echo $this->Form->end();

    $csrfToken = $this->request->getParam('_csrfToken');

    echo $this->articlecatCreate->create();


    // use this form to edit the article category 
    // question is how I can use retrieved data from ajax call to populate this form again.. 

    echo $this->Form->create("", ['id' => 'article_cat_create']);
    echo $this->Form->control('title');   
    echo $this->Form->button(__('Save ArticleCat'));
    echo $this->Form->end();    

?>

<button id="edit_category">edit Category</button>

<script>

    var csrf_token = <?php echo json_encode($csrfToken) ?>;  

    $(window).load(function() {   


        // get article category data from controller method through ajax call 
        // populate the form with them      
        $('#edit_category').click(function(){

            var targeturl = "http://wampprojects/composer_cakephptut/articles/editcategory"; 

            var category_selected = $('#article_cat').children("option:selected").val();
            console.log(category_selected);

            // need to check if this statement works?? 
            if ($('#article_cat').children("option:selected").val()){

                $.ajax({
                    type: 'post',
                    url: targeturl,
                    headers: {'X-CSRF-Token': csrf_token},
                    data: {category: category_selected},
                    success: function(result){

                        console.log(result);

                        // POPULATE AN EXISTING FORM WITH NEW DATA AND TOGGLE DISPLAY VALUE! 
                        var article = JSON.parse(result); 
                        // can you, with this result, populate existing form?? 
                        // id = "article_cat_create"

                        // which value do you need to set in formhelper?? 
                        $('#article_cat_create').css("display", "block");                        


                    }
                });

            }else{

                console.log("no cat selected");

            }


        });

    });

</script>


<style>

    #article_cat_create{

        display: none;

    }

</style>

Articles Controller中的“ editcategory()”方法。

    public function editcategory(){

        $this->loadModel('Articlecats');     

        $category_id = $this->request->getData('category'); 
        $articlecat_data = $this->Articlecats->find('all', ['conditions' => ['id' => $category_id]]);

        $this->response->body(json_encode($articlecat_data));
        return $this->response;      

    }

情况是我通过JSON.parse方法以Javascript格式将“文章类别”信息检索到视图。现在的问题是,如何使用这个新检索到的Javascript数组填充ID为“ article_cat_create”的CakePHP表单元素,以便可以轻松地将更改保存到数据库中?

我可以使用CAKEPHP FORMHELPER这样做还是需要在FORMHELPER之外构建PHP表单?

[{“ id”:3,“ title”:“电子”,“ user_id”:3}]]

javascript php cakephp wamp
2个回答
0
投票
但是我认为一个更简单的解决方案是将ArticleController :: editcategory()数据($ articlecat_data)发送到将呈现所需表单元素的元素。

将此HTML返回给您的Ajax成功函数,并让该函数将其插入到表单中。

将以这种方式遵守所有常规的蛋糕形式约定,以后的发布数据将正是您所需要的。

只需稍微注意一下原始页面和ajax返回的代码段中的id和class属性,就可以轻松地换出整个表单(仅换为内部HTML或向现有表单添加更多的输入。) >

因此,我对“我可以使用CAKEPHP FORMHELPER这样做吗”的具体答案是。


0
投票
由于无法在JQuery中创建窗口小部件,只能创建文本和链接,选项之一是使用屏幕上已经存在的表单,并用我新获取的类别数据加载它,以便我可以进一步使用它。我通过将以下代码添加到我的AJAX调用中来尝试这种方法。
© www.soinside.com 2019 - 2024. All rights reserved.