Thursday, March 21, 2019

Laravel Row reorder implementation

I was able to get this working in Laravel using Yajra Datatables as a Service.Here is the example below, hopefully you get the idea.

In my DataTable Builder:
return $this->builder()
    ->columns([
        'id' => [ 'visible' => false ], // record id
        'sortsequence' => [ ... ],  // db column containing order sequence
        ...,
    ])
    ->parameters([
        ...
        'rowReorder' => [
            'selector' => 'tr>td:not(:last-child)', // I allow all columns for dragdrop except the last
            'dataSrc' => 'sortsequence',
            'update' => false // this is key to prevent DT auto update
        ]
    ]); 

Blade:
/ includes DataTables JS/CSS plus the folliowing:
...
<meta name="csrf-token" content="{{ csrf_token() }}”>
...
<link rel="stylesheet" href="https://cdn.datatables.net/rowreorder/1.2.0/css/rowReorder.dataTables.min.css”>
...
<script src="https://cdn.datatables.net/rowreorder/1.2.0/js/dataTables.rowReorder.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){  
 $.ajaxSetup({
     headers: {
         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
     }
 });
 var table = $('#dataTableBuilder').DataTable();
 table.on( 'row-reorder', function ( e, diff, edit ) {
     var myArray = [];
     for ( var i=0, ien=diff.length ; i<ien ; i++ ) {
         var rowData = table.row( diff[i].node ).data();
  myArray.push({
      id: rowData.id,   // record id from datatable
      position: diff[i].newData  // new position
  });
     }
    var jsonString = JSON.stringify(myArray);
    $.ajax({
                url     : '{{ URL::to('myurl/reorder') }}',
                type    : 'POST',
                data    : jsonString,
                dataType: 'json',
                success : function ( json ) 
                {
          $('#dataTableBuilder').DataTable().ajax.reload(); // now refresh datatable
                    $.each(json, function (key, msg) {
                 // handle json response
                    });
                }
            });
 });

});
</script>
Route:
Route::post('myurl/reorder', 'MyController@reorder')->name('myname.reorder');
MyController :
/**
 * Reorder a listing of the resource.
 *
 * @return Response
 */
public function reorder(Request $request)
{
    $count = 0;

    if (count($request->json()->all())) {
        $ids = $request->json()->all();
        foreach($ids as $i => $key)
        {
            $id = $key['id'];
            $position = $key['position'];
            $mymodel = MyModel::find($id);
            $mymodel->sortsequence = $position;
            if($mymodel->save())
            {
                $count++;
            }
        }
        $response = 'send response records updated goes here';
        return response()->json( $response );
    } else {
        $response = 'send nothing to sort response goes here';
        return response()->json( $response );
    }
}

 Thanks for partially share by the exninja

Tuesday, September 25, 2018

PHPWord - Convert html to docx with header and footer layouts

Here is the simple and additional reasons to set the header with logo and address contents, and footer with positions on easy way.


       /* Convert HTML to word */
        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $phpWord->setDefaultFontSize($fontSize);
        $phpWord->setDefaultFontName($fontFamily);
        $phpWord->setDefaultParagraphStyle(
           [
                'spaceAfter' => \PhpOffice\PhpWord\Shared\Converter::pointToTwip(0),
                'spacing' => 120,
                'lineHeight' => 1,
           ]
        );

        if ($addresstxt && ($headerlogoposition != $headercompanyposition)) {
            $imageStyle = [
                'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(4.50),
                'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(1.50),
                'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE,
                'posHorizontal' => $headerlogoposition,
                'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN,
                'posVerticalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_MARGIN
            ];
        } else {
            $imageStyle = [
                'width' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(4.50),
                'height' => \PhpOffice\PhpWord\Shared\Converter::cmToPixel(1.50),
                'alignment' => $headerlogoposition
            ];
        }
        $section = $phpWord->addSection();
        if($headerLogo || $addresstxt) {
            $header = $section->addHeader();

            if ($headerLogo) {
                $header->addImage($headerLogo, $imageStyle);
            }

            if ($addresstxt) {
                $textlines = explode("\n", $addresstxt);
                for ($i = 0; $i < sizeof($textlines); $i++) {
                    $header->addText($textlines[$i], ['size' => $headerfontsize], ['alignment' => $headercompanyposition]);
                }
            }
        }

        if ($footerTxt) {
            $footer = $section->addFooter();
            $footer->addText($footerTxt, ['size' => $footerfontsize], ['alignment' => $footerposition]);
        }

        $html = mb_convert_encoding($templateHtml, 'HTML-ENTITIES', 'UTF-8');
        \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false);

        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $objWriter->save($fileUrl);