[form-builder] In form builder can we send error response and exit form?

lckamal - 4 months ago

I am trying like this for exit form and send response

class UserLanguageFormBuilder extends FormBuilder
{
...
public function onPost()
    {
        $language = \Request::get('language');
        $userlang = UserLanguageModel::where(['user_id' => auth()->id(), 'language_id' => $language])->count();
        if($userlang > 0){
            return response()->json(['success' => false, 'message' => 'This language is already added.']);
        }
    }
}

Is there some other options instead?

piterden - 4 months ago

$this->setFormResponse($redirect->to('admin/users/roles'));

return;
class UserLanguageFormBuilder extends FormBuilder
{
...
public function onPost()
    {
        $language = \Request::get('language');

        // The right way is to use UserLaguageRepositoryInterface here
        //$userlang = UserLanguageModel::where(['user_id' => auth()->id(), 'language_id' => $language])->count();

        if($userlang > 0){
            $this->setFormResponse(
                response()->json(['success' => false, 'message' => 'This language is already added.'])
            );
            return;
        }
    }
}

lckamal - 4 months ago

Hi piterden, It is not working

dali - 4 months ago

instead of using onPost create a handler class UserLanguageFormHandler and :

    public function handle(UserLanguageFormBuilder $builder, MessageBag $messages, Redirector $redirect)
    {
        $messages->error('Cant save now..');
        $builder->setSave(false);
        $builder->setFormResponse($redirect->back());
    }