简体   繁体   English

引导模态中的Laravel 4验证

[英]Laravel 4 validation in bootstrap modal

I'm a newbie to Laravel 4, and I'm trying to get a form validation in bootstrap modal. 我是Laravel 4的新手,并且我正尝试在bootstrap modal中进行表单验证。 My modal have a form with a text input and a submit button, and I want that when the validation fails, the modal show me the error. 我的模态有一个带有文本输入和提交按钮的表单,我希望当验证失败时,模态向我显示错误。 But the modal, after the validation and the page refresh, is closed. 但是,在验证和页面刷新之后,该模式已关闭。 Here is the code from the controller and the view: 这是控制器和视图中的代码:
Controller code: 控制器代码:

    public function postAvatar()
{
        $avatar_rules = array(
            'avatar_src' => 'url',

        );
        $validator = Validator::make(Input::all(), $avatar_rules);
        $validator->setAttributeNames(User::$names_attr); 

        if ($validator->passes()) 
        {                
        $avatar_src = (Input::get('avatar_src'))? Input::get('avatar_src') : URL::asset('assets/images/user/default-user-avatar.png');
        $user = User::find(Auth::id());
        $user->avatar_src = $avatar_src;

        if ($user){
         return Redirect::to('dashboard')->withSuccess("Success: avatar updated.");  
        }
        return Redirect::to('dashboard')->withError("Error: an error has occurred.");
        }
        return Redirect::back()->withErrors($validator);                
    }

View code: 查看代码:

    <!-- Modal -->
<div class="modal fade" id="avatarModal" tabindex="-1" role="dialog" aria-labelledby="avatarModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="avatarModalLabel">Update avatar</h4>
      </div>
      <div class="modal-body">
          <h4><span class="label label-info">Current avatar</span></h4>
          <img class="img-circle img-responsive dashboard-avatar" src="{{ $user->avatar_src }}" alt="{{ $user->username }} avatar">     
          <div class="divider"></div>
          <h4><span class="label label-info">New avatar</span></h4>
          {{ Form::open(array('url' => 'dashboard/avatar', 'method'=>'post', 'role'=>'form')) }}
            <ul>
                @foreach($errors->all() as $error)
                <div class="alert alert-danger" role="alert">{{ $error }}</div>
                @endforeach
            </ul>          
          <div class="form-group">
            <label for="avatar_src" class="control-label">Link avatar</label>
            <input type="text" name="avatar_src" class="form-control" id="avatar_src" placeholder="Link of avatar image url">
          </div>     
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Update</button>
      </div>
         {{ Form::close() }}       
    </div>
  </div>
</div>

How can I resolve ? 我该如何解决? Thanks. 谢谢。

SOLVED: 解决了:
Controller code: 控制器代码:

public function postAvatar()
{
        $avatar_rules = array(
            'avatar_src' => 'url',

        );
        $validator = Validator::make(Input::all(), $avatar_rules);
        $validator->setAttributeNames(User::$names_attr); 

        if ($validator->passes()) 
        {                
        $avatar_src = (Input::has('avatar_src'))? Input::get('avatar_src') : URL::asset('assets/images/user/default-user-avatar.png');
        $user = User::find(Auth::id());
        $user->avatar_src = $avatar_src;

        if ($user->save()){
         if(Request::ajax()){
           return Response::json(array('success' => true));
        }
        }
        return Redirect::to('dashboard')->withError("Error: an error has occurred.");
        }
            return Response::json(array('errors' => $validator->errors()->toArray()));
        }

View code: 查看代码:

<!-- Modal -->
<div class="modal fade" id="avatarModal" tabindex="-1" role="dialog" aria-labelledby="avatarModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="avatarModalLabel">Update avatar</h4>
      </div>
      <div class="modal-body">
          <h4><span class="label label-info">Current avatar</span></h4>
          <img class="img-circle img-responsive dashboard-avatar" src="{{ $user->avatar_src }}" alt="{{ $user->username }} avatar">     
          <div class="divider"></div>
          <h4><span class="label label-info">New avatar</span></h4>
          {{ Form::open(array('url' => 'dashboard/avatar', 'id'=>'avatar_form', 'method'=>'post', 'role'=>'form')) }}
          <div class="alert alert-danger avatar_alert" role="alert" style="display: none">
              <ul></ul>
          </div>
            <ul>
            </ul>          
          <div class="form-group">
            <label for="avatar_src" class="control-label">Link avatar</label>
            <input type="text" name="avatar_src" class="form-control s_tooltip" id="avatar_src" placeholder="Avatar image links">
          </div>     
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Update</button>
      </div>
         {{ Form::close() }}       
    </div>
  </div>
</div>

Ajax: 阿贾克斯:

<script>
$(document).on('submit', '#avatar_form', function(event){
    var info = $('.avatar_alert');
    event.preventDefault();
    var data = { avatar_src: $("#avatar_src").val() }

    $.ajax({
        url: "/dashboard/avatar",
        type: "POST",
        data: data,
    }).done(function(response) {
            info.hide().find('ul').empty();
        if(response.errors)
        {
            $.each(response.errors, function(index, error){
                info.find('ul').append(error);
            });
            info.slideDown();
        }
        else if(response.success){
          window.location.href = "/dashboard";
        }
    });
});
</script>

Your best bet would be to validate the form via AJAX to avoid the page reloading entirely. 最好的选择是通过AJAX验证表单,以避免完全重新加载页面。 You would then check the response of your AJAX request for the presence of errors and show them inside the modal if they exist. 然后,您将检查AJAX请求的响应是否存在错误,并在错误模态中显示错误(如果存在)。

You could also add in client side validation to prevent the request being made until the rules are satisfied. 您还可以添加客户端验证,以防止在满足规则之前发出请求。 I wouldn't recommend using this INSTEAD of server side validation but using it ASWELL as is normally quite desirable. 我不建议使用此INSTEAD的服务器端验证,但通常希望将它用作ASWELL。

To accomplish this, you'd need to do something along these lines: 为此,您需要按照以下步骤进行操作:

Javascript: 使用Javascript:

Catch submit event of your form and make an AJAX request. 赶上您的表单提交事件并提出AJAX请求。

$(document).on('submit', 'form', function(event){
    event.preventDefault();

    var data = { avatar_src: $("#avatar_src").val(); };

    $.ajax({
        url: "/dashboard/avatar",
        data: data
        type: "POST",
    }).done(function(response) {
        if(response.errors)
        {
            // Add error to Modal Body
        }
        else
        {
            // Show success message, close modal?
        }
    });
});

Backend: 后端:

Modify your controller method to detect if the current request is an AJAX request and if so, return the response in JSON instead of Redirecting. 修改控制器方法,以检测当前请求是否为AJAX请求,如果是,则以JSON而不是重定向返回响应。 For example: 例如:

if(Request::ajax())
{
    return Response::json(array('errors' => $validator->messages()));
}
else
{
    return Redirect::back()->withErrors($validator);
}

I've not tested any of that code so might contain some typos/errors but hopefully this helps you! 我没有测试任何代码,因此可能包含一些错字/错误,但希望对您有所帮助!

I was facing same issue. 我面临着同样的问题。 After research on internet,I found that Laravel don't support withSuccess('success_msg') method. 经过互联网研究后,我发现Laravel不支持withSuccess('success_msg')方法。

     return Redirect::to('dashboard')->withSuccess("Success: avatar updated."); 

Here is complete discussion on this topic: https://github.com/laravel/framework/issues/906 . 这是关于此主题的完整讨论: https : //github.com/laravel/framework/issues/906

But you can handle this issue with this approach:- 但是您可以使用以下方法处理此问题:-

- For Error message:- -对于错误消息:-

[code has to be added in controller] [必须在控制器中添加代码]

return Redirect::to('view')->withErrors('your error message.');

[code has to be added in view] [必须在视图中添加代码]

@if(isset($errors) && count($errors->all())>0)
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif

- for succcess message:- -成功消息:-

[code has to be added in controller] [必须在控制器中添加代码]

$success_msg='your success message.';
Session::flash('successMsg', $success_msg);
return Redirect::to('view');

[code has to be added in view] [必须在视图中添加代码]

@if (Session::has('successMsg'))
{{ Session::get('successMsg') }}
@endif

This approach is working fine for me. 这种方法对我来说很好。 For better display of your errors you can use bootstrap css. 为了更好地显示错误,您可以使用Bootstrap CSS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM