跳到正文

被拒绝的表单保留已输入的内容 ​

机器翻译

本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。

任务: 当服务器拒绝一个表单时,把它连同用户输入的内容一起返回,而不是空的。

yaml
# Recipe: a refused form comes back with what was typed, not empty.
paths:
  components: ./components
  migrations: ./migrations

datasources:
  db:
    driver: sqlite
    database: ./data/messages.db
sql
CREATE TABLE messages (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    email TEXT NOT NULL,
    body TEXT NOT NULL
);

这不需要写任何东西。被拒绝之后,ui:form 的下一次渲染会用提交的值填充每个字段, 只填一次,就像提示消息(flash)一样。密码字段和文件字段永远不会被带回。 rows="6" 让消息成为一个多行字段。

xml
<q:component name="Contact">
  <q:action name="send" method="POST">
    <q:param name="email" type="email" required="true" />
    <q:param name="body" required="true" minlength="20" maxlength="2000" />
    <q:query name="saved" datasource="db">
      INSERT INTO messages (email, body) VALUES (:email, :body)
      <q:param name="email" value="{email}" type="string" />
      <q:param name="body" value="{body}" type="string" />
    </q:query>
    <q:redirect url="/" flash="Thanks, we got your message." />
  </q:action>

  <ui:window title="Contact us">
    <q:if condition="flash">
      <ui:alert variant="{flashType == 'error' and 'danger' or 'success'}">{flash}</ui:alert>
    </q:if>
    <!-- Nothing to write for the values: after a refusal, the next render of
         this form fills each field with what was sent (UI-9), once. -->
    <ui:form on-submit="send">
      <ui:formitem label="Your e-mail"><ui:input bind="email" /></ui:formitem>
      <ui:formitem label="Message"><ui:input bind="body" rows="6" /></ui:formitem>
      <ui:button variant="primary">Send</ui:button>
    </ui:form>
  </ui:window>
</q:component>

第一个测试提交一个错误的地址和一条正确的消息:地址被拒绝,消息仍然留在它的字段里。 第二个测试再次打开页面:值已经不在了。

xml
<q:test name="a refused message comes back as it was typed" page="/">
  <test:submit action="send" email="ana@example" body="Your shop is closed on Sundays?" />
  <test:expect redirect="/" />
  <test:expect error="email" message="Must be a valid email" />
  <test:expect text="Your shop is closed on Sundays?" />
  <test:expect table="messages" count="0" />
</q:test>

<q:test name="the values come back once: the next visit is empty" page="/">
  <test:submit action="send" email="ana@example" body="Your shop is closed on Sundays?" />
  <test:visit />
  <test:expect no-text="Your shop is closed on Sundays?" />
</q:test>

<q:test name="a valid message is saved" page="/">
  <test:submit action="send" email="ana@example.com" body="Your shop is closed on Sundays?" />
  <test:expect redirect="/" flash="Thanks, we got your message." />
  <test:expect table="messages" count="1" where="email = 'ana@example.com'" />
</q:test>
text
tests/contact.test.q
  PASS  a refused message comes back as it was typed
  PASS  the values come back once: the next visit is empty
  PASS  a valid message is saved
3 passed, 0 failed

参见 UI-9,多行字段见 UI-14。

MIT 许可证 · 使用 VitePress 构建