我想在用户输入标题时自动生成slug。
<div class="form-group">
<label for="name">Title of News</label>
<input type="text" class="form-control" id="name" name="name"
placeholder="Enter your title of news"
value="@if(isset($news->name)){{ old('name', $news->name) }}@else{{old('name')}}@endif">
</div>
<div class="form-group">
<label for="slug">Slug</label>
<input type="text" class="form-control" id="slug" name="slug"
placeholder="slug"
{{!! isFieldSlugAutoGenerator($dataType, $dataTypeContent, "slug") !!}}
value="@if(isset($news->name)){{ str_slug($news->name, '-') }}@endif">
</div>
<script>
$('document').ready(function () {
$('#slug').slugify();
});
</script>
问题是:
在Title of news
输入文字时,它不会实时更改。
因为它不会实时更改,所以它无法正确保存slu。
示例:
当我在新闻的Title
字段中输入时:Apple iPhone 7
- &gt;单击按钮保存。字段slug
不包含任何值。
接下来,我将Title
新闻更改为Apple have plan release IOS 11
- &gt;单击按钮保存。数据库中的字段slug
更改为Apple iPhone 7
。
你可以在gif看到:
答案 0 :(得分:1)
您的控制器:
function store(Request $request) {
$this->validate($request, [
'title' => 'required'
]);
$news = News::create($request->all());
$news->slug = str_slug($request->title, '-');
$news->save();
return redirect()->back();
}
您的观点:
<div class="form-group">
<label for="name">Title of News</label>
<input type="text" class="form-control" id="name" name="name"
placeholder="Enter your title of news"
value="@if(isset($news->name)){{ old('name', $news->name) }}@else{{old('name')}}@endif">
</div>
<p>The slug will be <span id="slug"></span></p>
<script>
$('document').ready(function () {
$(document).on('change', 'input#name', function() {
var slug = slugify($(this).val());
$('span#slug').text(slug);
});
});
function slugify(text)
{
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
}
</script>
我没有尝试过,但应该有效。您可能需要适应您的系统,但这个想法就在这里。