Как найти строку таблицы после модального открытия закрыть - PullRequest
0 голосов
/ 19 мая 2019

У меня есть форма, в которой у меня есть таблица, и в таблице есть строки, или я буду добавлять строки динамически.

    <table class="table table-bordered table-hover table-sm table-light sortable" >
        <thead class="thead-light">
            <tr>
                <th scope="col">{{ __('additional_information.title') }}</th>
                <th scope="col">{{ __('additional_information.text') }}</th>
                <th scope="col">{{ __('additional_information.file') }}</th>
                <th scope="col">{{ __('additional_information.is_public') }}</th>
                <th scope="col">{{ __('additional_information.is_showcase') }}</th>
                <th scope="col"></th>
            </tr>
        </thead>

        <tbody>
   @foreach ($additionalInformations as $additionalInformation)
            <tr>
                <td data-value="{{ $additionalInformation->title }}">
                    <input class="form-control" type="text" placeholder="{{ __('additional_information.title') }}" name="existing_additional_information_title[{{ $additionalInformation->id }}]" value='{{ $additionalInformation->title }}'>
                </td>
                <td data-value="{{ $additionalInformation->text }}">
                    <input class="form-control" type="text"  placeholder="{{ __('additional_information.text') }}" name="existing_additional_information_texts[{{ $additionalInformation->id }}]" value='{{ $additionalInformation->text }}'>
                </td>
                <td  id = "photo"  class="d-inline-block text-truncate" data-value="{{ $additionalInformation->original_file_name }}" style="max-width: 300px;">
   @empty($additionalInformation->original_file_name)
   @else
                    <a href="/file/image/{{ $additionalInformation->file }}"    data-placement="bottom" data-toggle="tooltip" data-html="true" title="<img src='/file/image/{{ $additionalInformation->file }}'  width='180'  >">{{ $additionalInformation->original_file_name }} </a>
@endif<br>
                <input type="file"  class= "imgcha" name="existing_additional_information_files[{{ $additionalInformation->id }}]"><br>
                <button type="button" class="btn btn-primary item-img file center-block"  id ="add_id" value="{{ $additionalInformation->id }}" name="file_photo"/>Rajaa näyttökuva </button>

                </td>
                <td nowrap data-value="{{ $additionalInformation->existing_additional_information_is_publics }}">
                    <label class="plain"><input type="checkbox" name="existing_additional_information_is_publics[{{ $additionalInformation->id }}]" value="1" {{ $additionalInformation->is_public == 1 ? 'checked' : '' }}> {{ __('additional_information.is_public') }}</label>
                </td>
                <td nowrap data-value="{{ $additionalInformation->existing_additional_information_is_showcase }}">
                    <label class="plain"><input type="checkbox" name="existing_additional_information_is_showcase[{{ $additionalInformation->id }}]" value="1" {{ $additionalInformation->is_showcase == 1 ? 'checked' : '' }}> {{ __('additional_information.is_showcase') }}</label>
                </td>
                <td>
                    <button class="btn btn-secondary delete" value = {{ $additionalInformation->id }}><i class="fas fa-trash"></i> {{ __('global.delete') }}</button>
                </td>
            </tr>
   @endforeach
        </tbody>
    </table>

or

        var number= 0;
        $(".add-new").click(function(){
            // Math.floor(Math.random() * 100);

            var index = $("table tbody tr:last-child").index();
            var row =
                '<tr>' +
                '<td><input class="form-control" type="text" placeholder="{{ __("additional_information.title") }}" name="new_additional_information_title[]" value=""></td>' +
                '<td><input class="form-control" type="text" placeholder="{{ __("additional_information.text") }}" name="new_additional_information_texts[]" value=""></td>' +

                '<td class="d-inline-block text-truncate"><input  type="file" class= "imgcha" name="new_additional_information_files[]" ><br><button type="button" class="btn btn-primary item-img file center-block" value="{{ $additionalInformation->id ?? null}}" id ="add_id" name="file_photo">Rajaa näyttökuva </button> </td>' +
                ' <input type="hidden"  name="new_additional_information_is_publics[' + number + ']" value="0" /> ' +
                '<td nowrap><label class="plain"><input type="checkbox" name="new_additional_information_is_publics[' + number + ']"value="1" checked> {{ __("additional_information.is_public") }}</label></td>' +
                '<td nowrap><label class="plain"><input type="checkbox" class="chk" name="new_additional_information_is_showcase[]" value="1"> {{ __("additional_information.is_showcase") }}</label></td>' +
                '<td><button class="btn btn-secondary delete" value="0"><i class="fas fa-trash"></i> {{ __("global.delete") }}</button></td>' +
                '</tr>';
            $("table").append(row);
            $("table tbody tr").eq(index + 1).find(".add, .edit").toggle();
            $('[data-toggle="tooltip"]').tooltip();
            number++;
        });

таблица

После добавления строки я нажимаю кнопку, открывающую модальное окно.В модальном я обрезаю изображение и отправляю / сохраняю обрезанное изображение через ajax.Взамен я получаю путь к картине.Я хочу добавить скрытый ввод в строку, по которой щелкнули, например


            resize.croppie('result', {

                type: 'canvas',

                size: 'viewport'

            }).then(function (img) {
                    console.log( 'toka');
                $.ajax({

                    url: "{{route('upload.image')}}",

                    type: "POST",

                    data: {"image":img, "add_id":add_id},

                    success: function (data) {

                        var el = '<input type="hidden" name="crop_img" value=' 
                        + data.path + '></input>';
                        $('#additionalInformationForm 
           input:hidden:last').replaceWith(el);

                        var test = $('#additionalInformationForm 
        tr:last').val();
                            console.log(data.id + data.path +test);


                    }

                });

            });

        });
modal
<div class="modal fade " id="cropImagePop" tabindex="-1" role="dialog" aria- 
    labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered " role="document"  >
        <div class="modal-content" style="width:750px;">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalCenterTitle">Croppaa 
       näyttökuva</h5>
                <button type="button" class="close" data-dismiss="modal" aria- 
       label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body align-items-center text-center" >
                <div id="upload-demo"></div>
                <button type = "button" class="btn btn-primary btn-block 
            `enter code here`upload-image" style="margin-top:2%">Rajaa 
             kuva</button>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data- 
                dismiss="modal">Close</button>

            </div>

        </div>
    </div>
</div>


И вопрос в том, как найти нужную строку, куда добавить вход?И как обновлять определенные строки каждый раз, когда я обрезаю фотографию.Надеюсь, вы понимаете вопрос.Спасибо!

модальный


  public function uploadImage(Request $request)

    {

        if($request->add_id === null){
            $image = $request->image;

            list($type, $image) = explode(';', $image);

            list(, $image)      = explode(',', $image);

            $image = base64_decode($image);

            $image_name= time().'.png';


            $path = storage_path() . '/app/additional_information_files/' . $image_name;


            $statement = DB::select("show table status like 'additional_informations'");



            file_put_contents($path, $image);
            $path_img = '/app/additional_information_files/' . $image_name;
           // $filename = explode("/", $path);
            //$path_img = 'file/image/' . $filename[8];
            return response()->json(['status'=>true, 'path' => $path, 'id'=>  $statement[0]->Auto_increment]);
        }

        $addinfo = \App\AdditionalInformation::find($request->add_id);
        $image = $request->image;


        if($addinfo->showcase_picture)
        {
            Storage::delete($addinfo->showcase_picture);
        }
        list($type, $image) = explode(';', $image);

        list(, $image)      = explode(',', $image);

        $image = base64_decode($image);

        $image_name= time().'.png';


        $path = storage_path() . '/app/additional_information_files/' . $image_name;


        $addinfo->showcase_picture = $path;
        $addinfo->save();

        file_put_contents($path, $image);

        return response()->json(['status'=>true, 'path' => $path]);

    }

    public function createFromRequest(Request $request, AdditionalInformationContainer $container)
    {
        // Get texts, files and isPublics from the request
        $titles = $request->get('new_additional_information_title') ?? [];
        $texts = $request->get('new_additional_information_texts') ?? [];
        $files = $request->file('new_additional_information_files') ?? [];
        $isPublics = $request->get('new_additional_information_is_publics') ?? [];
        $isShowcases = $request->get('new_additional_information_is_showcase') ?? [];
        $isCropImages = $request->get('crop_img') ?? [];
        // Validate files
        $this->validateFiles($request);


        // Loop through all texts and get the matching files and isPublics
        // based on the array index
        foreach ($texts as $index => $text) {
            $title = array_key_exists($index, $titles) ? $titles[$index] : null;
            $text = array_key_exists($index, $texts) ? $texts[$index] : null;
            $file = array_key_exists($index, $files) ? $files[$index] : null;
            $isPublic = array_key_exists($index, $isPublics) ? $isPublics[$index] : false;
            $isShowcase = array_key_exists($index, $isShowcases) ? $isShowcases[$index] : false;
            $isCropImage = array_key_exists($index, $isCropImages) ? $isCropImages[$index] : false;

            // If the fields are empty, skip
            if ($text === null && $file === null) {
                continue;
            }

            // Create the additional information and attach it to the container
            $additionalInformation = $this->create($file, $title, $text, $isPublic, $isShowcase, $isCropImage);

            if ($additionalInformation) {
                $container->additionalInformations()->attach($additionalInformation);
            }
        }

        return $container;
    }

    public function create(UploadedFile $file = null, string $title = null, string $text = null, bool $isPublic, bool $isShowcase, string $isCropImage = null)
    {
        // Skip if file and text are empty
        if (!$file && strlen(trim($text)) === 0) {
            return null;
        }

        // Create the additional information with basic info
        $additionalInformation = new AdditionalInformation();
        $additionalInformation->title = $title;
        $additionalInformation->text = $text;
        $additionalInformation->is_public = $isPublic;
        $additionalInformation->is_showcase = $isShowcase;
        $additionalInformation->showcase_picture = $isCropImage;
        // Attach the file if specified
        if ($file) {
            $path = $file->store('additional_information_files');
            $additionalInformation->file = $path;
            $additionalInformation->filesize = $file->getClientSize();
            $additionalInformation->original_file_name = $file->getClientOriginalName();
        }
        // Save
        $additionalInformation->save();
        return $additionalInformation;
    }
~~~

Ответы [ 2 ]

1 голос
/ 19 мая 2019

Я использую подобную тактику.Что вы можете сделать, это просто пометить <tr> атрибутом данных, содержащим идентификатор модели, которую вы перечисляете (или что-то уникальное для каждой записи).Затем в серверной части после внесения изменений просто сгенерируйте <tr> заново (вы можете экспортировать его в отдельный файл для этой цели) и верните его как данные с ответом.Тогда в вашем jquery просто найдите tr, помеченный уникальным атрибутом данных, и .replaceWith() новый tr вернул ... или измените его так, как вам нравится!

Надеюсь, вы его получили, я не могу привести примерпоскольку нам не хватает вашей логики на стороне сервера ... но в этом-то и все дело.

0 голосов
/ 20 мая 2019

Устранена проблема с указанным кодом.

Добавлен скрытый ввод после добавления строки.И когда я обрезал фотографию, я добавил значение «in_edit», и после сохранения обрезанного изображения я нашел это значение и заменил его на путь к изображению.И сохранил это с формой соответственно.Нужно немного подумать!Спасибо Петрову за указание на правильный путь:)

jquery



  $(document).on('click', '.item-img', function (e) {

            if(ch_image  ===  undefined) {
                ch_image = $(this).closest('tr').find('a').attr('href');

            }

                add_id= $(this).val();
             $(this).closest('tr').find("[name='crop_img[]']").attr('value', 'in_edit');
             $(this).closest('tr').find("[name='new_Crop_Img[]']").attr('value', 'new_in_edit');


            $('#cropImagePop').modal('show');

        });

      $('.crop_img').each(function(){
                            if($(this).attr('value') == 'in_edit'){

                                $(this).attr('value', data.path)
                                console.log('if');
                            }

                        });

                        $('.new_crop_img').each(function(){
                            if($(this).attr('value') == 'new_in_edit'){

                                $(this).attr('value', data.path)
                                console.log('if');
                            }

                        });



        var number= 0;
        $(".add-new").click(function(){
            // Math.floor(Math.random() * 100);

            var index = $("table tbody tr:last-child").index();
            var row =
                '<tr>' +
                '<td><input class="form-control" type="text" placeholder="{{ __("additional_information.title") }}" name="new_additional_information_title[]" value=""></td>' +
                '<td><input class="form-control" type="text" placeholder="{{ __("additional_information.text") }}" name="new_additional_information_texts[]" value=""></td>' +

                '<td class="d-inline-block text-truncate"><input  type="file" class= "imgcha" name="new_additional_information_files[]" ></td>' +
                ' <input type="hidden"  name="new_additional_information_is_publics[' + number + ']" value="0" /> ' +
                '<td nowrap><label class="plain"><input type="checkbox" name="new_additional_information_is_publics[' + number + ']"value="1" checked> {{ __("additional_information.is_public") }}</label></td>' +
                '<td nowrap><label class="plain"><input type="checkbox" class="chk" name="new_additional_information_is_showcase[]" value="1"> {{ __("additional_information.is_showcase") }}<br><button type="button" class="btn btn-primary item-img file center-block" value="{{ $additionalInformation->id ?? null}}" id ="add_id" name="file_photo">Rajaa näyttökuva </button> </label></td>' +
                '<td><button class="btn btn-secondary delete" value="0"><i class="fas fa-trash"></i> {{ __("global.delete") }}</button></td>' +
                ' <input type="hidden" class="new_crop_img"  name="new_Crop_Img[]"></input></tr>';
            $("table").append(row);
            $("table tbody tr").eq(index + 1).find(".add, .edit").toggle();
            $('[data-toggle="tooltip"]').tooltip();
            number++;
        });


        $(document).on('change','.chk' ,function() {
            console.log('vaihda');
            if ($(this).is(":checked")) {
                $('.chk').not(this).each(function() {
                    $(this).prop('checked', false);
                    console.log('if');
                });
            }




        });
    });

~~~~

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...