Generate Required field value from Form Handler

ayhamhsn - 2 months ago

Is there a way to generate a required field value from handler. the scenario is that we have a slug field that must be generated from form handler once the form is submitted. if we skipped that field in form settings, putting its value from handler will not affect and an sql error will thrown because skipping a field will not add it to the form fields array.

Answer

- 2 months ago

To reslove the problem : - skip your field in the form builder :

    protected $skips = [ 'slug'];
  • add your field in your form handler like this :
 public function handle(
        UserRepositoryInterface $users,
        RoleRepositoryInterface $roles,
        FieldFactory $factory,
        UserActivator $activator,
        MessageBag $messages,
        CompanyFormBuilder $builder
    )
    {
        if ($builder->hasFormErrors()) {
            return;
        }

        $builder->addFormField($factory->make(
            [
                'field'    => 'slug',
                'type' => 'anomaly.field_type.slug',
                'required' => true,
                'config'   => [
                    'type' => '-',
                    'slugify' => 'name'
                ],
                'value'    => $this->slugify($builder->getFormValue('name')),
            ]));
        $builder->setFormValue('slug',$this->slugify($builder->getFormValue('name')) );
        $builder->saveForm();
   }

ayhamhsn - 2 months ago

To reslove the problem : - skip your field in the form builder :

    protected $skips = [ 'slug'];
  • add your field in your form handler like this :
 public function handle(
        UserRepositoryInterface $users,
        RoleRepositoryInterface $roles,
        FieldFactory $factory,
        UserActivator $activator,
        MessageBag $messages,
        CompanyFormBuilder $builder
    )
    {
        if ($builder->hasFormErrors()) {
            return;
        }

        $builder->addFormField($factory->make(
            [
                'field'    => 'slug',
                'type' => 'anomaly.field_type.slug',
                'required' => true,
                'config'   => [
                    'type' => '-',
                    'slugify' => 'name'
                ],
                'value'    => $this->slugify($builder->getFormValue('name')),
            ]));
        $builder->setFormValue('slug',$this->slugify($builder->getFormValue('name')) );
        $builder->saveForm();
   }