从INLINE-EDITING表中具有相同名称的多个输入中获取此值 [英] Get THIS value from multiple input with same name IN INLINE-EDITING table

查看:61
本文介绍了从INLINE-EDITING表中具有相同名称的多个输入中获取此值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况. 我已经使用内联编辑(使用jQ)创建了一个表,并且每一行都有其编辑按钮.因此,例如,如果要编辑第一行,请单击编辑"按钮,这将打开他的输入字段.每个打开的要编辑的行都有其保存按钮,该ID与该行中该属性的ID相关联. 现在,如何使用php达到该输入值?我不得不提到每个输入都具有相同的属性名称->它们都是动态创建的.

I have this situation. I've created a table with inline-editing (using jQ), and every row have its edit button. So if I want for instance, to edit first row, I click on edit button and it opens me his input field. Every opened row for editing has its save button which id is connected with id of that property in row. Now, how can I get to that input value using php? I have to mention every input is with same attribute-name -> they are all creating dynamically.

php

$new_tname = $_POST['edit_team']; ?????????????????????????????????

if (isset($_GET['save_tid'])) {
$tid = $_GET['save_tid'];
$team = Team::getById($tid);

if ($tid == $team->team_id) {


  $team->name = $new_tname;
  $team->save();
}

}

html/php

<?php 
                  $teams = Team::getAll();
                  foreach ($teams as $team) {
                    $tname = $team->name;
                    $tid = $team->team_id;


                    echo "<tr>
                    <td>
                    <a href='#' class='editable' style='margin-left: 2px;'>".$tname."</a><form method='POST' action=''><input type='text' class='editshow form-control col-sm-3' aria-label='Sizing example input' aria-describedby='inputGroup-sizing-sm' name='edit_teams' value='".$tname."'></form><a href='teams.php?save_tid={$tid}' style='margin-left: 2px; margin-top:3px;' class='btn btn-success btn-sm editshow'>Save</a>
                    </td>";

                    echo "<td>
                    <button  class='btn btn-primary btn-sm btnEdit'".$tid."'>Edit</button> | <a href='teams.php?delete_tid={$tid}' class='btn btn-danger btn-sm'>Delete</a>
                    </td>
                    </tr>";
                  }

var_dump($new_tname) throws me a NOTICE: Undefined variable: edit_team

我假设php无法找到哪个edit_team(因为它们是多个),isset($ _ POST ['edit_team'])对此不适用,因为它使我为NULL,

I'm assuming php can't find which edit_team(because they are multiple), isset($_POST['edit_team']) is not solution on this because it throws me NULL,

这是用于内联编辑的jQ

and here is jQ for inline-editing

jQ

<script type="text/javascript">
$(".editshow").hide();
  $(".btnEdit").click(function(){
    let btnEdit = $(this),
    containerEl = btnEdit.closest("tr");
    containerEl.find(".editshow").toggle();
  });
</script>

php是否有解决方案?我希望有一个人可以帮助我.谢谢.

Is there any solution with php or? I hope someone can help me. Thank you.

推荐答案

所以问题是这样的:当您单击这些链接(保存或删除)时,实际上并没有告诉服务器您要更新的内容.链接本身无法知道发送的字段,字段是否已更新或任何内容.您正在页面上执行动态的操作,在这种情况下,这将意味着编写脚本.

So the issue is this: when you click on those links (the save or delete), you don't actually tell the server what it is you are updating. The link has no means of knowing, in and of itself, what fields it is sending, or whether they have been updated, or anything. You are doing something dynamic on the page, and in this case, that will mean scripting.

这比您对切换操作所做的操作要复杂一个数量级,因此请注意-您刚刚跳入了最深层次.我已经开始构建一些东西,向您展示如何可以完成,但这绝不是完整的或准确的.通过提供给我们的快照,我们不知道您的php到底在做什么.

It is an order of magnitude more complex than what you have done with the toggle thing, so be warned -- you have just jumped in at the deep end. I have started building something that will show you how it could be done, but this is by no means complete, or accurate. We don't know what your php is really doing by the snapshot you have given us.

这里是我构建的代码块,只是作为原型.我将在下面更详细地描述它:

Here is a code block I've built, simply as a prototype. I'll describe it in deeper detail below:

$(function(){
  let updateTeamUrl = "SET_THIS_TO_THE_UPDATE_URL";

  // We'll also save these as references to all the action buttons.
  let actionItems = {
    editBtn: $(".btnEdit"),
    saveBtn: $(".save-btn"),
    deleteBtn: $(".btnDelete")
  }
  $(".editshow").hide();
  // Here we assign the actions to the various buttons/anchors
  actionItems.editBtn.on("click", toggleEdit);
  actionItems.saveBtn.on("click", saveTeam);
  actionItems.deleteBtn.on("click", confirmDelete)

  // Below are the actions we assign above, or support functions for them

  /**
   * toggleEdit() is triggered when the "Edit" button is clicked. This
   *   hides the team name text element, and displays the editable field.
   **/
  function toggleEdit(event){
    let teamContainer = $(this).closest("tr");
    teamContainer.find(".editshow").toggle();
    teamContainer.find(".editable").toggle();
  }

  /**
   * saveTeam() crawls up the DOM tree to the closest "tr" node, and gets
   *  the custom "data-teamid" attribute there. Using that, we can create
   *  a JSON object that we will send to the backend.
   **/
  function saveTeam(event){
    event.preventDefault();

    let clickedEl = $(this),
        teamContainer = clickedEl.closest("tr"),
        teamNameEl = teamContainer.find(".editshow");
    let payloadToSend = {
      // We need a mechanism to identify what team we're updating
      teamId: teamContainer.data("teamid"),
      // This will eventually hold any and all updates.
      updates: {
        /* We'll create this empty, and fill it as we need.*/
      }
    };

    // I created a data attribute on the input, "data-original", and
    //  set it to the same value as the input. By comparing these, we
    //  can see if an input has, in fact, been updated.
    if(teamNameEl.data("original") !== teamNameEl.val() ){
      /**
       * The only thing we are updating in this pass is the team name.
       *  So we can update our "payload", then simply send the post request.
       **/
      payloadToSend.updates.name = teamNameEl.val();

      /**
       * When we POST, we need a URL and a string we'll send. 
       *  What we'll do is take the payload, and run it through
       *  JSON.stringify() to convert it to a string.
       *  Then, when we call $.post(), we can also add a .done() and
       *  .fail() handler. These will run when the save is complete,
       *  or when it fails.
       * 
       **/
      let postRequest = $.post(UpdateTeamUrl, JSON.stringify(payloadToSend) )
              .done(function(returnedData){
                console.log("Update succeeded: "+returnedData)
              })
              .fail(function(error){
                console.error("Update had an error: "+error)
              })
              .always(function(){
                teamContainer.find(".editshow").toggle();
                teamContainer.find("editable").toggle();
              });
    }
  } // end saveTeam();

  function confirmDelete(event){
    event.preventDefault();
    let clickedEl = $(this),
        teamContainer = clickedEl.closest("tr"),
        teamId = teamContainer.data("teamid"),
        teamName = teamContainer.find("[name='edit_teams']").val();


    if(confirm("are you sure you want to delete the team "+teamId+": "+teamName+"?") ){
      console.log("Deleting!")
    } else {
      console.log("false alarm.")
    }
  }
})

此外,支持此操作的HTML需要做一些改动:<tr>获取数据属性data-teamid<input>获取数据属性data-original,并且包装输入的form元素已经被删除.这是HTML(无需PHP即可构建):

Also, the HTML to support this needs to change a little: the <tr> gets a data attribute data-teamid, the <input> gets a data attribute data-original, and the form element that wrapped the input has been removed. Here's the HTML (without the PHP to construct it):

    <tr data-teamid="1">
      <td>
        <a href='#' class='editable' style='margin-left: 2px;'>Team Name</a>: <input type='text' class='editshow form-control col-sm-3' aria-label='Sizing example input' aria-describedby='inputGroup-sizing-sm' name='edit_teams' data-original='Team Name' value='Team Name'> <a href='teams.php?save_tid={$tid}' style='margin-left: 2px; margin-top:3px;' class='btn btn-success btn-sm editshow save-btn'>Save</a>
      </td>
      <td>
        <button  class='btn btn-primary btn-sm btnEdit team-1'>Edit</button> | <a href='#' class='btn btn-danger btn-sm btnDelete'>Delete</a>
      </td>
    </tr>

正如我所说的,这变得非常复杂.

As I've said, this is getting pretty complex.

首先,我将您所有的动作"都移到了javascript对象中.如果添加其他操作,则只需在那里进行更新.然后,我对要处理的每个操作使用.on(...)附加侦听器:编辑,保存和删除.对于每一个,我写了一个函数来处理动作本身:toggleEdit(...)用于编辑,saveTeam(...)用于保存,confirmDelete用于删除.每个动作都是独立的,使编辑更容易.

First, I moved all your "actions" into a javascript object. If I add other actions, I simply update them there. Then I attach listeners using .on(...) for each action I want to handle: edit, save and delete. For each of these, I wrote a function that will handle the action itself: toggleEdit(...) for the edit, saveTeam(...) for the save, and confirmDelete for the delete. Each action is self-contained, making editing a little easier.

toggleEdit(...)几乎与您以前使用的完全一样.我认为我在那件事上并没有太大改变,所以看起来应该很熟悉.

The toggleEdit(...) is almost exactly what you had before. I don't think I changed much in that one, so it should look pretty familiar.

saveTeam(...)是您现在要问的那个,它很复杂.首先,我们将DOM树爬回到<tr>,并使用.data("teamid")获取我们正在编辑的团队的ID.然后,我们开始创建一个JavaScript对象,我称之为payloadToSend.在此,我们有一个属性teamId和一个嵌套对象updates.接下来,我们检查文本输入是否已更新(通过将其值与我添加的data-original属性进行比较).如果没有更改,我们不需要更新.如果它,那么我们通过在payloadToSend.updates对象中添加name来更新payloadToSend,然后使用$.post(...)实际发送POST请求. $ .post()需要一个URL和一些数据.我们将发送payloadToSend对象作为该数据,该数据应在PHP中显示为$_REQUEST$_POST.此外,$.post(...)包括两个条件回调.done(...).fail(...),以及一个绝对"回调.always(...)

The saveTeam(...) is the one you're asking about now, and it is the complex bit. First, we climb back up the DOM tree to the <tr>, and use .data("teamid") to get the id of the team we're editing. Then we start creating a javascript Object, which I've called payloadToSend. In this, we have an attribute teamId, and a nested object updates. Next, we check to see if the text input has been updated (by comparing its value with that data-original attribute I added). If it hasn't changed, we don't need to update. If it has, then we update the payloadToSend by adding name to the payloadToSend.updates object, and we use $.post(...) to actually send the POST request. $.post() takes a URL and some data. We'll send the payloadToSend object as that data, which should show up in php as either $_REQUEST or $_POST. In addition, the $.post(...) includes two conditional callbacks, .done(...) and .fail(...), and one "absolute" callback, .always(...)

.done(...)在服务器端请求成功完成返回时运行,并且.fail(...)使用错误消息处理后端失败.不过,无论哪种情况,我们.always(...)都想隐藏可编辑内容并再次显示团队名称.

.done(...) runs when the server-side request has returned with a successful complete, and .fail(...) handles a back-end failure with an error message. In either case, though, we .always(...) want to hide the editable and show the team name again.

在这一点上,confirmDelete操作除了获得相同的teamId之外没有做任何其他事情,并弹出一个基本的确认对话框.删除操作远不止于此,还超出了您原始问题的范围.

At this point, the confirmDelete action doesn't do anything more than get that same teamId, and pop up a basic confirmation dialog. The delete action is quite a bit more than that, and beyond the scope of your original question.

这篇关于从INLINE-EDITING表中具有相同名称的多个输入中获取此值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆