简体   繁体   English

如何从Symfony和PHP中的表单传递参数?

[英]How to pass a parameter from a form in Symfony and PHP?

I am trying to implement a very simple search function with PHP in symfony. 我试图用symfony中的PHP实现一个非常简单的搜索功能。

Basically I have a form that posts a query and I want to retrieve the items in the database that match the query. 基本上,我有一个发布查询的表单,我想在数据库中检索与查询匹配的项目。

If I have a User table with columns first_name and last_name, I want to be able to retrieve all items that contain a query. 如果我有一个用户表的列first_name和last_name,我希望能够检索包含查询的所有项目。 For example, if I submit 'a', I will get all names that have an 'a' in them: 例如,如果我提交“ a”,我将得到其中包含“ a”的所有名称:

  • Bat Man 蝙蝠侠
  • Black Beard 黑胡子
  • Adam West 亚当·韦斯特
  • Mister A A先生

So I know I can get all objects in the table whose first names contain 'a' by specifying criteria: 所以我知道我可以通过指定条件来获取表中所有名字都包含“ a”的对象:

$c = new Criteria();  
$c->add(UserPeer::FIRST_NAME, '%a%', Criteria::LIKE);  
$users = UserPeer::doSelect($c);  

Is there a way I can pass a variable like $query in the add() function? 有没有办法在add()函数中传递$ query这样的变量? Can I acquire $query via a form and then pass it as a variable in the add function and get all the objects that contain it? 我可以通过表单获取$ query,然后将其作为变量传递给add函数并获取包含它的所有对象吗? Am I even going about this the right way? 我什至会以正确的方式这样做吗?

On your form create an input with the id 'query' 在您的表单上创建一个ID为'query'的输入

<label for="query">Query:</label>
<?php echo input_tag('query') ?>

In the action get the parameter IF the form has been submitted then pass it into your criteria 在操作中,如果已提交表单,则获取参数,然后将其传递到您的条件中

if($this->getRequest()->getMethod() == sfRequest::POST)
{
    $query = $this->getRequestParameter('query');

    $c = new Criteria();
    $c->add(UserPeer::FIRST_NAME, '%'.$query.'%', Criteria::LIKE);
    $users = UserPeer::doSelect($c); 

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM