Laravel 4在bootstrap模式中验证 [英] Laravel 4 validation in bootstrap modal

查看:100
本文介绍了Laravel 4在bootstrap模式中验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Laravel 4的新手,我正在尝试在bootstrap模式中进行表单验证。
我的模态有一个带有文本输入和提交按钮的表单,我希望当验证失败时,模态会显示错误。
但是在验证和页面刷新之后,模式将被关闭。
以下是控制器和视图中的代码:

控制器代码:

I'm a newbie to Laravel 4, and I'm trying to get a form validation in 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);                
    }

查看代码:

    <!-- 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()));
        }

查看代码:

<!-- 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>


推荐答案

最好的办法是通过AJAX验证表格避免页面重新加载完全。然后,您将检查您的AJAX请求对错误是否存在的响应,并将其显示在模态中(如果存在)。

Your best bet would be to validate the form via AJAX to avoid the page reloading entirely. You would then check the response of your AJAX request for the presence of errors and show them inside the modal if they exist.

您还可以添加客户端验证以防止在满足规则之前提出的请求。我不建议使用这个服务器端验证的INSTEAD,但通常非常需要使用ASWELL。

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.

要实现这一点,你需要做一些事情。专栏:

To accomplish this, you'd need to do something along these lines:

Javascript:

抓住您表单的提交事件并制作一个AJAX请求。

Catch submit event of your form and make an AJAX request.

$(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?
        }
    });
});

后端:

修改您的控制器方法以检测当前请求是否是AJAX请求,如果是,则以JSON而不是重定向返回响应。例如:

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. 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!

这篇关于Laravel 4在bootstrap模式中验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆