开发者

Symfony: How to pass Doctrine Collection to Form as default values?

开发者 https://www.devze.com 2023-03-26 11:41 出处:网络
My action: public function executeEdit(sfWebRequest $request) { // Get the object $article = $this->getRoute()->getObject();

My action:

public function executeEdit(sfWebRequest $request)
{
    // Get the object
    $article = $this->getRoute()->getObject();

    // Create the form
    $this->form = new ArticleEditForm( $article );
}

You can see that $article is the Doctrine Collection that gets passed to the Form as default values. The $article object contains a fields like "title", "text", "author", etc.

But this causes an error in the Form creation:

500 | Internal Server Error | Doctrine_Record_UnknownPropertyException
Unknown record property / related component "_csrf_token" on "article"

So basically, the form is trying to use the Doctrine Collection to fill out default values for the form elements. But there obviously isn't a csrf_token in that object... But it's still trying to find one to use as the default value...

And what happens if you have a form where there are always extra empty fields that are empty but others have default values that are passed. I开发者_StackOverflowf those empty fields don't have set values in the Doctrine Collection then you get an error...

Now, obviously I could just make a simple array ahead of time where I specify the default values and pass that:

$defaults = array( 'title' => $article->title, 'text' => $article->text, 'author' => $article->author );
$this->form = new ArticleEditForm( $defaults);

This works. My problem is that the above "article" is an example for simplicity reasons. In reality my form has about 30 fields in it. So the only way that this solution would work is to have to manually specify 30 individual default values in an array. This is a poor solution from a maintenance point-of-view, obviously.

I figure the Symfony developers are smart enough to come up with a good solution but I just can't find it... Any clues?


This problem is all about your form doesn't create _csrf_token. You can add it when creating form in your template page like:

<?php 
  echo $form->renderFormTag(url_for('article/edit'))
  echo $form->render();
?>
  <input type="hidden" name="form[_csrf_token]" value="<?= $form->getCSRFToken(); ?>">
  <input type="submit" value="Submit" />
</form>


I discovered my problem. My custom form was extending BaseForm. Once I changed this to extend BaseArticleForm then I was able to successfully pass article Doctrine Collections in as default values.

0

精彩评论

暂无评论...
验证码 换一张
取 消