Best way to dynamically embed symfony forms?

I have been using the symfony form structure for a while. But I would like to know if anyone has a better approach to implementing forms dynamically.

The problem arises when I insert the form (see below), I need to specify the index of the array, as Fabian explains how the sfForm object looks like a multidimensional array in this article Advanced forms .

If I want to give the user the opportunity to click the button and paste another form, how can I achieve the following if they click the button several times:

<input type="parent[child][]" />
<input type="parent[child][]" />
<input type="parent[child][]" />

... repeated how many times the user clicks the button. I can use fast javascript to copy and paste form elements in the DOM.

Instead of this:

<input type="parent[child][1]" />
<input type="parent[child][2]" />
<input type="parent[child][3]" />

... , . javascript, , , . , Ajax PHP, . , .

:

$parentForm = new ParentForm($parent)        

$child = new child();
$child->setParent($parent);

$sfForm = new sfForm();
$sfForm ->embedForm($someIndex, new ChildForm($child));

$parentForm->embedForm('child', $sfForm);
+3
3
, ! sfWidgetFormSchema:: generateName.
class myWidgetFormSchema extends sfWidgetFormSchema
{

  /**
   * Generates a name.
   *
   */
  public function generateName($name)
  {
    $name = parent::generateName($name);
    //match any [number] and replace it with []
    $name = preg_replace('/\[\d+\]/','[]', $name);
    return $name;
  }
}

"". " ":

  public function configure()
  {
    $this->getWidgetSchema()->setFormFormatterName('list');
    $this->widgetSchema->setNameFormat('master[%s]');

    $slavesForm = new sfForm();
    $slavesForm->setWidgetSchema(new myWidgetFormSchema);
    $slavesCount = $this->getOption('slaves_count', 2);
    for ($i = 0; $i < $slavesCount; $i++)
    {
      $slave = new Slave();
      $slave->Master = $this->getObject();
      $form = new SlaveForm($slave);
      $slavesForm->embedForm($i, $form);
    }
    $this->embedForm('new_slaves', $slavesForm);
  }

"slaves_count", executeCreate :

  public function executeCreate(sfWebRequest $request)
  {
    $schema = $this->getRequest()->getParameter('master');

    $this->form = new MasterNewForm(null, array('slaves_count'=> count($schema['new_slaves'])));

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

jQuery ! .

0
+1

Source: https://habr.com/ru/post/1796422/


All Articles