与数据库的laravel下拉列表

时间:2014-10-10 04:26:35

标签: php forms laravel laravel-4

我是laravel框架的新手,我发现很难理解laravel形式的可用性......所以这是我面临的一些问题

首先我的下拉列表应该是我的类别名称,并且在下拉列表的最后,它将是我的特定下拉列表添加新类别,当我选择时将触发我的javascript ...而我在这里是我的表格代码

{{ Form::select('kategori',KategoriArtikel::lists('name','id'),Input::old('kategori'),array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}

从我的数据库中显示正确的值也有正确的选择值,但是它缺少我的特定下拉列表,所以我试图像这样添加

 <?php 
     $tambah = array('tambah' => 'Tambah Kategori Baru');
     $list = array_merge(KategoriArtikel::lists('name','id'),$tambah); 
 ?>
{{ Form::select('kategori',array(KategoriArtikel::lists('name','id'),$tambah),Input::old('kategori'),array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}

但它会生成2个不同的布局(丑陋)并且没有显示正确的选择值,所以我尝试了其他方式

 <?php 
     $tambah = array('tambah' => 'Tambah Kategori Baru');
     $list = array_merge(KategoriArtikel::lists('name','id'),$tambah); 
?>
{{ Form::select('kategori',$list,Input::old('kategori'),array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}

并且它没有生成,我的下拉布局是它应该是什么,但现在不再来自我的表id,而只是序号0,1,2,3等 任何解决方案?

第二个问题是,当我提交表单时,它不起作用,我在表中的字段是int,当我提交它时只是没有保存/更新所以我试图dd(输入::全部( ))我的下拉列表返回所选选项值的字符串,它没有保存到我的表中......所以为什么呢?它也不适用于包含tinyint(1)的布尔字段...所以基本上所有值都返回字符串。

它返回

array(8) { ["_method"]=> string(3) "PUT" ["_token"]=> string(40) "IspUKdCETMe4Nn3pDI43GI7aJKQfXpupJvQAy1k6" ["simpan"]=> string(6) "simpan" ["judul"]=> string(18) "test "kegiatan" 21" ["kategori"]=> string(1) "9" ["kategori_baru"]=> string(0) "" ["status"]=> string(1) "0" ["content"]=> string(1012) "
I used--and I don't put my arm round your waist,' the Duchess said to herself. 'Of the mushroom,' said the Dormouse, and repeated her question. 'Why did they live at the sides of it, and then turned to the tarts on the twelfth?' Alice went on, 'that they'd let Dinah stop in the shade: however, the moment he was obliged to have wondered at this, but at the Caterpillar's making such a capital one for catching mice--oh, I beg your pardon!' cried Alice hastily, afraid that she had read about them in books, and she at once without waiting for turns, quarrelling all the children she knew, who might do something better with the time,' she said to herself; 'I should like to drop the jar for fear of killing somebody, so managed to swallow a morsel of the house, quite forgetting her promise. 'Treacle,' said the Gryphon: and it sat for a few minutes to see if she had grown up,' she said this, she looked down at her as she wandered about for it, you know--' (pointing with his head!' she said,.

" }

正如你所看到的那样['kategori']应该让我的表格kategori在我的表中为9,但它并没有改变我的数据库中的任何内容

我很简单,但在使用数据库时却很困惑(无法找到与数据库检索数据相关的任何文档示例等)

编辑:

这是我的控制器

public function update($id)
{
    $artikel = Artikel::findOrFail($id);

    if(Input::get('simpan')){
        //dd(Input::all());

        $validator = Validator::make($data = Input::all(), Artikel::$rules);

        if ($validator->fails())
        {
            return Redirect::back()->withErrors($validator)->withInput();
        }

        $judul = Input::get('judul');
        $artikel->update($data);

        return Redirect::route('admin.artikels.index')->with('message', 'Artikel ' .$judul. ' Telah berhasil di ubah.');
    }elseif(Input::get('batal')){
        return $this->index();
    }
}

这是我的观点

@extends('admin._layouts.admin')

@section('content')
{{ Form::model($artikel, array('route' => array('admin.artikels.update',$artikel->id), 'method' => 'put')) }}
    <div class="panel panel-default">
        <!--button-->
        <div class="panel-heading tooltip-demo">
            {{ Form::submit('Simpan',array('class' => 'btn btn-primary', 'data-toggle' => 'tooltip', 
               'data-placement' => 'top','title' => 'Menyimpan artikel' )) }}
            {{ Form::submit('Batal',array('class' => 'btn btn-default', 'data-toggle' => 'tooltip', 
               'data-placement' => 'top','title' => 'Batal menambah artikel dan kembali ke halaman kelola artikel' )) }}
        </div>
        <!--/button-->
        <div class="panel-body">
            <!--judul-->
            <div class="col-lg-10">
            <div class="form-group">
                {{ Form::label('Judul Artikel') }}
                {{ Form::text('judul',null,array('class' => 'form-control', 'placeholder' => 'Silahkan masukkan judul artikel'))}}
                {{ $errors->first('judul', '<p class="error">:message</p>') }}
            </div>
            </div>
            <!--/judul-->
            <!--kategori-->
            <div class="col-lg-4">
            <div class="form-group">
                {{ Form::label('Kategori') }}
                <?php 
                    $tambah = array('tambah' => 'Tambah Kategori Baru');
                    $list = array_merge(KategoriArtikel::lists('name','id'),$tambah); 
                ?>
                {{ Form::select('kategori',$list,'Pilih Kategori Artikel',array('class' => 'form-control', 'onChange' => 'changeFunc(value)')) }}
            </div>
            </div>
            <!--/kategori-->
            <!--kategori baru-->
            <div class="col-lg-4"  id="pilihan" style="display:none;">
            <div class="form-group">
                {{ Form::label('Kategori Baru') }}
                {{ Form::text('kategori_baru',null,array('class' => 'form-control', 'placeholder' => 'Silahkan masukkan kategori baru', 
                   'maxlength' => '30'))}} 
            </div>
            </div>
            <!--/kategori baru-->
            <!--status-->
            <div class="col-lg-4">
            <div class="form-group">
                {{ Form::label('Status') }}
                {{ Form::select('status',array('0' => 'Tidak diterbikan', '1' => 'Terbitkan'),null, array('class' => 'form-control')) }}
            </div>
            </div>
            <!--/status-->
            <!--artikel pilihan-->
            <div class="col-lg-5">
            <div class="form-group">
                {{ Form::label('Artikel Pilihan') }}
                <div class="input-group">
                <span class="input-group-addon">
                {{ Form::checkbox('pilihan','1',true,array('id' => 'artikelpilihan')) }}
                </span>
                {{ Form::text('null','Tidak',array('class' => 'form-control', 'id' => 'artikeltext' ,'disabled' => 'true'))}}
                </div>
            </div>
            </div>
            <!--/artikel pilihan-->
            <!--content-->
            <div class="col-lg-12">
                {{ Form::label('Isi Artikel') }}
                {{ Form::textarea('content',null,array('style' => 'height:300px')) }}
                {{ $errors->first('content', '<p class="error">:message</p>') }}
            </div>
            <!--/content-->
        </div>
     </div>
{{ Form::close() }}
{{ HTML::script('js/tinymce/tinymce.min.js') }}
<script type="text/javascript">
    tinymce.init({
        selector: "textarea",
        theme: "modern",
        skin: 'light',
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern"
        ],
        toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
        toolbar2: "print preview media | forecolor backcolor emoticons | fontselect fontsizeselect",
        image_advtab: true,
        templates: [
            {title: 'Test template 1', content: 'Test 1'},
            {title: 'Test template 2', content: 'Test 2'}
        ],
        file_browser_callback: RoxyFileBrowser
    });


    function RoxyFileBrowser(field_name, url, type, win) {
      var roxyFileman = '../../../../public/js/tinymce/plugins/fileman/index.html?integration=tinymce4';
      if (roxyFileman.indexOf("?") < 0) {     
        roxyFileman += "?type=" + type;   
      }
      else {
        roxyFileman += "&type=" + type;
      }
      roxyFileman += '&input=' + field_name + '&value=' + document.getElementById(field_name).value;
      tinyMCE.activeEditor.windowManager.open({
         file: roxyFileman,
         title: 'File Manager',
         width: 800, 
         height: 480,
         resizable: "yes",
         plugins: "media",
         inline: "yes",
         close_previous: "no"  
      }, {     window: win,     input: field_name    });
      return false; 
    }
</script>
@stop

2 个答案:

答案 0 :(得分:0)

如果我已正确理解您的问题,您希望根据数据库中的值填充下拉列表,并且还希望在类别下拉列表中显示“选择类别”。目前您的下拉值未保存。

要填充下拉列表,请将以下代码放在控制器的加载视图文件的方法中。

$data['kategori'] = KategoriArtikel::lists('name','id');
$data['kategori'][''] = 'Select a kategori';        
return View::make('YOUR_VIEW_FILE', $data); 

在您的视图文件中,简单使用以下内容(相同规则适用于其他选择下拉列表):

{{ Form::select('kategori', $kategori , Input::old('kategori'), array('id' => 'category', 'class' => 'form-control',  )) }} 

上面的代码基本上生成了这样的内容:

<select id="category" class="form-control">
  <option value="">Select a Kategori</option>
  <option value="1">First Kategori</option>
  <option value="2">Second Kategori</option>
</select>

Form::select()中的第三个参数需要默认选项值,如果您提供的值将与选项值进行比较,并将匹配的值显示为选中。

而且您的表单方法不应该是'method' => 'POST'而不是'method' => 'put'

答案 1 :(得分:0)

我在您描述的情况下使用以下代码。在我的控制器中我有

public function create()
    {
        $category1= Category1::lists('category1','id');
        $category2= Category2::lists('category2','id');
       //you can have many select lists in an form
        return      
     View::make('someobject.create',compact('category1','category2'));
    }

和我的someobject.create视图

{{Form::open(array('route'=>'someobject.store'))}}
   <div>
    {{Form::label('category1', 'category1')}}  
    {{Form::select('category1',array('' => 'Please select') + $category1) }}
    <span class="errors">{{$errors->first('category1')}}</span>
    {{Form::label('category2', 'category2')}}  
    {{Form::select('category2',array('' => 'Please select') + $category2) }}
    <span class="errors">{{$errors->first('category2')}}</span>
   </div>
   <div>
   {{Form::submit('Save',array('class' => 'btn'))}}
   </div>