草庐IT

设置表格以重定向到提交时的当前页面(SilverStripe/PHP)

程序员大本营 2024-07-10 原文

我为SilverStripe站点有一个注册表单,该网站处理服务器端上的所有内容。最初,它只会在主页上,所以我工作的设置很好。但是随后的需求发生了变化,也需要出现在子页面上的表格。除了我为什么设置的内容,表格总是提交到主页外,一切仍然有效 action 范围。

最初, action 参数为“/家庭/提交”。我将其更改为接受一个变量,该变量返回当前页面URL并通过制作称为称为的函数来附加“/提交” Link (请参阅下面的代码)。这似乎有效,并将正确的URL放入 action 范围。

但是,当您点击“提交”按钮时,该表格仍将用户发送回主页,这不是我想要的。我希望他们留在表单上的当前页面上(无论是主页还是任何子页面)。

我尝试获取当前的URL并将其用于提交功能的最后一行,这样:

$current = $this->get_current_page()->Link();return $this->redirect("$current/?redirected=1#signupform");;

但这使用户陷入不正确的URL: http://my-site.org/sub-page-title /submit (这是无效的)

这是存储在page.php中的表单代码:

  public function Link($action='') {    $req = Controller::curr()->getRequest();     $req->setURL(parent::Link($action));     $url = $req->getURL(TRUE); // get the url back but with querystr intact.    return $url ; }public function getFirstName() {    return Session::get('first_name');}public function getLastName() {    return Session::get('last_name');}public function getCompanyName() {    return Session::get('company_name');}public function getEmail() {    return Session::get('email');}public function submit(SS_HTTPRequest $request) {    $firstName = $request->postVar('first_name');    $lastName  = $request->postVar('last_name');    $c  = $request->postVar('company_name');    $email     = $request->postVar('email');    Session::clear('FORM_ERRORS');    $errors = [];    if (empty($email)) {        array_push($errors, "Email is required");    }    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {        array_push($errors, "Email must be in a valid format. Example: [email protected]");    }    if(empty($firstName)){        array_push($errors, "Please enter a first name");    }    if(empty($lastName)){        array_push($errors, "Please enter a last name");    }    if (empty($errors)) {        Session::clear('first_name');        Session::clear('last_name');        Session::clear('email');        Session::clear('company_name');        $comment = new EmailSignUpSubmission();        $comment->FirstName = $firstName;        $comment->LastName  = $lastName;        $comment->CompanyName   = $c;        $comment->Email     = $email;        $comment->write();    } else {        Session::set($this->formErrorsKey, $errors);        Session::set('first_name', $firstName);        Session::set('last_name', $lastName);        Session::set('company_name', $c);        Session::set('email', $email);    }    return $this->redirect("/?redirected=1#signupform");}public function getFormErrors() {    $errors = Session::get($this->formErrorsKey);    if ($errors == null || $errors == "") {        return null;    } else {        $errorList = new ArrayList();        foreach ($errors as $error) {            $e = new ArrayData(['Text' => $error]);            $errorList->add($e);        }        return $errorList;    }}public function isRedirect() {    $request = $this->getRequest();    return $request->getVar('redirected') == "1";}

这是HTML形式本身:

 <div class="sign-up" id="signupform">    <div class="form-container">        <% if $isRedirect && not $getFormErrors %>            <div class="row">                <p class="success">                    Thank you for your submission. You will hear back from us shortly.                </p>            </div>        <% else %>        <form method="post" action="/$Link/submit">            <h2 class="text-center white subscribe-hdr">Sign up</h2>            <% if $getFormErrors %>                <% loop $getFormErrors %>                    <p class="error">$Text</p>                <% end_loop %>            <% end_if %>            <p class="white subscribe-body" style="text-align:center;">Sign up for the latest newsletter.</p>            <div class="form-group">                <input class="form-control" type="text" name="first_name" value="$getFirstName" placeholder="First Name">            </div>            <div class="form-group">                <input class="form-control" type="text" name="last_name" value="$getLastName" placeholder="Last Name">            </div>            <div class="form-group">                <input class="form-control" type="text" name="company_name" value="$getCompanyName" placeholder="Company">            </div>            <div class="form-group">                <input class="form-control" type="email" name="email" value="$getEmail" placeholder="Email">            </div>            <div class="form-group">                <button class="btn btn-primary btn-block" type="submit"                        style="width:140px;margin-left:auto;margin-right:auto; float: none; text-align: center">Submit                </button>            </div>        </form>    <% end_if %>    </div></div>

看答案

您可以随时使用隐藏的字段:

<input type="hidden" value="{$AbsoluteLink}" name="redirectURL" />

然后在您的提交方法中使用它以重定向。

通过扩展表单类,这将变得更加容易,因为您将当前控制器对象传递给表单。 https://docs.silverstripe.org/en/3/developer_guides/forms/introduction/

有关设置表格以重定向到提交时的当前页面(SilverStripe/PHP)的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  3. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

  4. ruby-on-rails - date_field_tag,如何设置默认日期? [ rails 上的 ruby ] - 2

    我想设置一个默认日期,例如实际日期,我该如何设置?还有如何在组合框中设置默认值顺便问一下,date_field_tag和date_field之间有什么区别? 最佳答案 试试这个:将默认日期作为第二个参数传递。youcorrectlysetthedefaultvalueofcomboboxasshowninyourquestion. 关于ruby-on-rails-date_field_tag,如何设置默认日期?[rails上的ruby],我们在StackOverflow上找到一个类似的问

  5. ruby-on-rails - 在 Rails 开发环境中为 .ogv 文件设置 Mime 类型 - 2

    我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain

  6. ruby-on-rails - 有没有办法为 CarrierWave/Fog 设置上传进度指示器? - 2

    我在Rails应用程序中使用CarrierWave/Fog将视频上传到AmazonS3。有没有办法判断上传的进度,让我可以显示上传进度如何? 最佳答案 CarrierWave和Fog本身没有这种功能;你需要一个前端uploader来显示进度。当我不得不解决这个问题时,我使用了jQueryfileupload因为我的堆栈中已经有jQuery。甚至还有apostonCarrierWaveintegration因此您只需按照那里的说明操作即可获得适用于您的应用的进度条。 关于ruby-on-r

  7. ruby - 将 spawn() 的标准输出/标准错误重定向到 Ruby 中的字符串 - 2

    我想使用spawn(针对多个并发子进程)在Ruby中执行一个外部进程,并将标准输出或标准错误收集到一个字符串中,其方式类似于使用Python的子进程Popen.communicate()可以完成的操作。我尝试将:out/:err重定向到一个新的StringIO对象,但这会生成一个ArgumentError,并且临时重新定义$stdxxx会混淆子进程的输出。 最佳答案 如果你不喜欢popen,这是我的方法:r,w=IO.pipepid=Process.spawn(command,:out=>w,:err=>[:child,:out])

  8. ruby-on-rails - Prawn - 表格单元格内的链接 - 2

    我正在尝试用Prawn生成PDF。在我的PDF模板中,我有带单元格的表格。在其中一个单元格中,我有一个电子邮件地址:cell_email=pdf.make_cell(:content=>booking.user_email,:border_width=>0)我想让电子邮件链接到“mailto”链接。我知道我可以这样链接:pdf.formatted_text([{:text=>booking.user_email,:link=>"mailto:#{booking.user_email}"}])但是将这两行组合起来(将格式化文本作为内容)不起作用:cell_email=pdf.make_c

  9. git使用常见问题(提交代码,合并冲突) - 2

    文章目录git常用命令(简介,详细参数往下看)Git提交代码步骤gitpullgitstatusgitaddgitcommitgitpushgit代码冲突合并问题方法一:放弃本地代码方法二:合并代码常用命令以及详细参数gitadd将文件添加到仓库:gitdiff比较文件异同gitlog查看历史记录gitreset代码回滚版本库相关操作远程仓库相关操作分支相关操作创建分支查看分支:gitbranch合并分支:gitmerge删除分支:gitbranch-ddev查看分支合并图:gitlog–graph–pretty=oneline–abbrev-commit撤消某次提交git用户名密码相关配置g

  10. ruby - 如何使用 Ruby 将 CSV 文件读入 HTML 表格? - 2

    我正在尝试将一个简单的CSV文件读入HTML表格以在浏览器中显示,但我遇到了麻烦。这就是我正在尝试的:Controller:defshow@csv=CSV.open("file.csv",:headers=>true)end查看:输出:NameStartDateEndDateQuantityPostalCode基本上我只获取标题,而不会读取和呈现CSV正文。 最佳答案 这最终成为最终解决方案:Controller:defshow#OpenaCSVfile,andthenreaditintoaCSV::Tableobjectforda

随机推荐