【问题标题】:Add a form of another module添加另一个模块的表单
【发布时间】:2012-09-26 09:54:56
【问题描述】:

我有一个名为 main 的模块,这是我的默认模块,还有一个名为 song 的模块。

我想将我的song 模块的“添加表单”放入我的main 模块。

不知道是不是一定要使用组件,如何以及在哪里处理表单。

你能帮帮我吗?

【问题讨论】:

  • 你确定你的问题是针对 Symfony2 的吗?
  • 不,没有看到标签。我使用 Symfony 1.4。对不起。

标签: symfony1 symfony-1.4 symfony-forms


【解决方案1】:

您检查过文档吗?特别是this part of the doc?

它通过使用基本的联系表单来涵盖表单系统:

  • 你有一个控制器(actions.class.php 在你的main 模块中),它创建一个表单实例并处理提交(验证、保存等)
  • 然后是显示表单的模板 (contactSuccess.php)

主要区别在于您可能有一个名为 Song 的模型,因此您必须使用 SongForm 而不是创建一个新模型(使用new sfForm())。对于这部分,您可以在同一文档页面上看到 Forms Based on a Model 部分,它涵盖了文章模型的情况。

编辑:

一步一步:

在你的main/actions/actions.class.php:

public function executeIndex($request)
{
  $this->form = new SongForm();
  if ($request->isMethod('post'))
  {
    $this->form->bind($request->getParameter('song'));
    if ($this->form->isValid())
    {
      $song = $this->form->save();

      $this->getUser()->setFlash('notice', 'Thank you, the song has been added');

      $this->redirect('main/index');
    }
  }
}

在您的模板中,main/templates/indexSuccess.php:

<?php if ($sf_user->hasFlash('notice')): ?>
  <div class="flash_notice"><?php echo $sf_user->getFlash('notice') ?></div>
<?php endif ?>

<?php echo $form->renderFormTag('main/index') ?>
  <table>
    <?php echo $form ?>
    <tr>
      <td colspan="2">
        <input type="submit" />
      </td>
    </tr>
  </table>
</form>

你已经完成了。

真的鼓励您阅读整个Jobeet tutorial。你会学到很多东西。基本上我在这里描述的所有内容都在本教程中。

对于sf_guard_user字段,您应该将其重新定义为隐藏,然后为当前连接的用户设置一个默认值。

创建一个新表单:/lib/form/CustomSongForm.class.php

<?php

class CustomSongForm extends SongForm
{
  public function configure()
  {
    parent::configure();

    $this->widgetSchema['sf_guard_user_ud'] = new sfWidgetFormInputHidden();
  }
}

然后你可以定义默认值,就像你说的:

}$this->form->setDefault('sf_guard_user_id', $this->getUser()->getId());

【讨论】:

  • 首先,我真的很感谢你。如果我很好理解:在我的 MAIN 模块的 action.class.php 中,我创建了我的表单: $this->song_form = new SongForm();在我的 MAIN 模块的 indexSuccess.php 中,我显示了表单。渲染等。但是,当 tue 用户提交表单时,如何处理我的表单?因为我在同一页面发送表单(action="")此外,我想要一个显示“谢谢,歌曲已添加”的“tankyou”动作
  • 非常感谢!我很快就会测试它。我有一个问题,您调用操作 executeAddSong 但表单将显示在我的主模块的 indexSuccess.php 中。这就是为什么我坚持我可以在 executeIndex 中做到这一点并将我的表单的操作设置为这样的原因:action=""。我错了吗?
  • 几乎,我已经更新了我的答案。您还应该更改模板名称。
  • 非常感谢。 Main 不是一个好的主页名称?
  • 什么意思?我通常使用main 作为默认值,即事实上的主页。顺便说一句,如果对您有帮助,请不要忘记接受答案;)
猜你喜欢
  • 1970-01-01
  • 2011-06-03
  • 2021-02-04
  • 2017-05-24
  • 2014-07-24
  • 2017-07-26
  • 2011-04-15
  • 1970-01-01
  • 2013-09-12
相关资源
最近更新 更多