Laravel 4在bootstrap模式中验证

时间:2014-08-03 10:24:45

标签: javascript php twitter-bootstrap laravel laravel-4

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

    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>

我该如何解决? 感谢。

解决:
控制器代码:

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>

2 个答案:

答案 0 :(得分:2)

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

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

要做到这一点,你需要按照这些方针做点什么:

<强>使用Javascript:

抓取表单的提交事件并发出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?
        }
    });
});

<强>后端

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

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

我没有对任何代码进行测试,因此可能包含一些拼写错误/错误,但希望这对您有帮助!

答案 1 :(得分:0)

我遇到了同样的问题。经过互联网研究,我发现Laravel不支持withSuccess('success_msg')方法。

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

以下是关于此主题的完整讨论: https://github.com/laravel/framework/issues/906

但是你可以用这种方法处理这个问题: -

- 对于错误讯息: -

[必须在控制器中添加代码]

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

[必须在视图中添加代码]

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

- 有关成功消息: -

[必须在控制器中添加代码]

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

[必须在视图中添加代码]

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

这种方法对我来说很好。 为了更好地显示错误,您可以使用bootstrap css。