0

I have a prize form with the followings fields:

artist -> Choice (Related model artist)
prize_type
year

When creating a new Prize object I don't have any problems. Now I want to have a button on my Artist view called Create Prize and when it is clicked it needs to go to a form but I want the artist field to be selected by default.

How can I set a default value for this field depending from which URL is coming from?

I tried to retrieve my Artist ID in the URL so I got something like this:

"prize/new?id_artist=23"

But I can't figure out how to insert that ID on the $form['id_artist'] field.

I have tried to use setDefault option but it is only for placeholders:

$this->form->setDefault('id_artist', $request->getParameter("id_artist"));

Also I hide the related field in my template since I don't want it when coming from that URL

<?php if(!$id_artist): ?>
            <div class="control-group <?php echo $form['id_artist']->hasError()?'error':''; ?>">
                <?php echo $form['id_artist']->renderLabel('Artist ',array('class' => 'control-label')) ?>
                <div class="controls">
                    <?php echo $form['id_artist']?>
                    <small class="help-inline">Artist</small>
                    <?php if($form['id_artist']->hasError()): ?>
                        <small class="help-inline">(<?php echo $form['id_artist']->getError() ?>)</small>   
                    <?php endif; ?> 
                </div>
            </div>
        <?php endif; ?>

I tried to automatically set id_artist directly to that parameter but instead, I got an error since artist in my form is required.

Sephy
  • 159
  • 1
  • 2
  • 15
  • Firstly, what is the error? Secondly, you have said `$form[id_artist]` in your explanation but you are using `$form['id_artist']` in your html.twig file? Which one are you trying to use? If you're trying to use the variable within your description then change the html twig file to `$form[id_artist]` – Tom Jul 02 '19 at 11:14
  • Hello, sorry for being so unclear with my explanation...1. The error is that "field artist is required" so it clearly doesn't detect any value from my NewAction nor CreateAction method. 2) Yes, sorry, Its $form['id_artist']. I will edit my question. – Sephy Jul 02 '19 at 11:27
  • So you're clicking a button? If you want the form to have a default value why don't you just `onclick` post the `$form['id_artist']='val'` to the form? Which is acting as a default value? – Tom Jul 02 '19 at 11:49
  • Yeah...It doesnt work like that...It throws an error "Cannot update form fields." so it clearly doesn't accept it. It has to be through the symfony forms...but I can't find any method to set a value to the form field. – Sephy Jul 03 '19 at 10:29

0 Answers0