Monday, December 6, 2021

React.js, download pdf



Handle pdf download in React.js

                   <div className="formRow float-right-no-margin">
                        {this.props && this.props.file && this.props.file.length > 0 && (
                            <Button variant="primary" onClick={handlePdfDownload}>
                                Download
                            </Button>
                        )}
                        &nbsp;&nbsp;
                        <Button variant="secondary" onClick={this.props.handlePreviewClose}>
                            Close
                        </Button>
                    </div>
 

        const handlePdfDownload = () => {
            // Insert a link that allows the user to download the PDF file
            var link = document.createElement('a');
            link.innerHTML = 'Download PDF file';
            link.download = this.props.fileName;
            link.href = this.props.file;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        };

//hide Modal

   handlePreviewClose = () => {
        this.setState({ showPreview: false, pageNumber: 1 })
    };

 

Friday, December 3, 2021

axios handle blob type data




Reference:

https://stackoverflow.com/questions/60454048/how-does-axios-handle-blob-vs-arraybuffer-as-responsetype 

axios:

https://www.npmjs.com/package/axios 

 

'blob' is a "browser only" option for image, pdf etc

Example:

function fetchAs( type ) {
  return axios( {
    method: 'get',
    url: 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png',
    responseType: type
  } );
}
function loadImage( data, type ) {
  // we can all pass them to the Blob constructor directly
  const new_blob = new Blob( [ data ], { type: 'image/jpg' } );
  // with blob: URI, the browser will try to load 'data' as-is
  const url = URL.createObjectURL( new_blob );
  
  img = document.getElementById( type + '_img' );
  img.src = url;
  return new Promise( (res, rej) => { 
    img.onload = e => res(img);
    img.onerror = rej;
  } );
} 
[
  'json', // will fail
  'text', // will fail
  'arraybuffer',
  'blob'
].forEach( type =>
  fetchAs( type )
   .then( resp => loadImage( resp.data, type ) )
   .then( img => console.log( type, 'loaded' ) )
   .catch( err => console.error( type, 'failed' ) )
);
 
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<figure>
  <figcaption>json</figcaption>
  <img id="json_img">
</figure>
<figure>
  <figcaption>text</figcaption>
  <img id="text_img">
</figure>
<figure>
  <figcaption>arraybuffer</figcaption>
  <img id="arraybuffer_img">
</figure>
<figure>
  <figcaption>blob</figcaption>
  <img id="blob_img">
</figure>   

 

react-pdf, display pdf in react.js



Reference: 

https://www.npmjs.com/package/react-pdf

Example 1

import React, { useState } from 'react';
import { Document, Page } from 'react-pdf';

function MyApp() {
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

  function onDocumentLoadSuccess({ numPages }) {
    setNumPages(numPages);
  }

  return (
    <div>
      <Document
        file="somefile.pdf"
        onLoadSuccess={onDocumentLoadSuccess}
      >
        <Page pageNumber={pageNumber} />
      </Document>
      <p>Page {pageNumber} of {numPages}</p>
    </div>
  );

 Example 2

                            <div>
                                <Document
                                    file={this.props.file}
                                    onLoadSuccess={this.props.onDocumentLoadSuccess}
                                >
                                    <Page pageNumber={this.props.pageNumber} />
                                </Document>
                                <p>
                                    {this.props.pageNumber > 1 && (
                                        <a onClick={() => this.props.setPageNumber(this.props.pageNumber - 1)} >
                                            &lt;
                                        </a>
                                    )}
                                    &nbsp;&nbsp;Page {this.props.pageNumber} of {this.props.numPages}&nbsp;&nbsp;
                                    {this.props.pageNumber < this.props.numPages && (
                                        <a onClick={() => this.props.setPageNumber(this.props.pageNumber + 1)}
                                            disabled={this.props.pageNumber < this.props.numPages ? '' : 'disabled'}>
                                            &gt;
                                        </a>
                                    )}
                                </p>
 

                            </div>

File can be from:

          this.setState({

            file: 'data:application/pdf;base64,' + encodeURI(response.data),
        })

Wednesday, December 1, 2021

async in react.js




All react JS is asynchronous.

it provides a declarative API to perform any REST API calls using a single React component 

Example

     componentDidMount() {
        this.getData();
    }
    async getData() {
      this.setState({loading: true});
        axios
            .get("/access_control/access/getAll")
            .then(response => {
                this.setState({
                    data: response.data,
                    loading: false
                })
            })
            .catch(error => {
                console.error(
                    'There has been a probelm with an axios operation:',
                    error
                );
                this.setState({ifSuccess: false, msg: 'There has been a probelm with retriving module list.', loading: false});
            });
    }

Use componentDidMount in React.js




Reference:

https://reactjs.org/tutorial/tutorial.html

componentDidMount is called exactly once and when The component has been initialized. The component has bind with the container element and rendered successfully. All the properties and initial states has been initialized. You can now call setState and other component function on this component, manipulate it and so on. Simply it is the starting point for you to interact with it.

componentDidMount is useful  for AJAX requests. 

componentDidMount() executes after the render() at first execution. After that it executes before the render() according to React Lifecycle.

React.js: pass variables in different components



In React.js

    setSearchYear = (data) => {
        this.setState({searchYear: data})
    }

              <ApplicationList
                 setSearchYear={this.setSearchYear}
                />

setSearchYear is passed to component ApplicationList, ApplicationList.js

                                   <div className="col-2 text-left form-group">
                                        <Select
                                            id="searchYear"
                                            name="searchYear"
                                            closeMenuOnSelect={true}
                                            components={this.props.animatedComponents}
                                            onChange={value => this.props.setSearchYear( value.value )}
                                            options={this.props.yearList}
                                            defaultValue={[{ label: 'All Fiscal Years', value: 0 }]}
                                        />
                                    </div>
 

Tuesday, November 30, 2021

json_encode and json_decode in PHP




1) JSON stands for JavaScript Object Notation

Example of JSON string

s1 = '{"FirstName":"David", "LastName":"Lee"}'

It defines an object with 2 properties:  FirstName and LastName

JavaScript has a built in function for converting JSON strings into JavaScript objects:

obj = JSON.parse(s1)

After we  parse the JSON string with a JavaScript program, we can access the data as an object: 

let FirstName = obj.FirstName;
let LastName = obj.LastName

JavaScript also has a built in function for converting an object into a JSON string:

JSON.stringify()

2) PHP json_encode function

convert PHP array to JSON string

Example:

<?php
$arr 
= array('a' => 1'b' => 2'c' => 3'd' => 4'e' => 5);

echo 
json_encode($arr);
?>

The above example will output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

3) PHP json_decode function 

json_decodeDecodes a JSON string to an object


<?php

$json 
'{"foo-bar": 12345}';

$obj json_decode($json);
print 
$obj->{'foo-bar'}; // 12345

?>

 3) Example in PHP Larvel

in controller

  $dataItems['FirstName'] = "David";

       $data['dataItems'] = json_encode($dataItems);

        return view('templates.view_layout', $data);

in view: view_layout.blade.php

       @isset($dataItems)
            <script type="text/javascript">
                var dataItems = {!! $dataItems !!};
            </script>
        @endisset
Parse to JavaScript object, which can be used it React.js

   constructor(props) {
        super(props);

        this.state = {
            data: dataItems ? dataItems : null,
       }

}

 //Access to FirstName

 this.state.data.FirstName;

 

 

 

 

Monday, November 29, 2021

React.js, handle attachment




import React, { Component } from 'react';

class Attachment extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        const handleDownload = (e, id, type, name) => {
            e.preventDefault();
            if(type == 'preview'){
                this.props.context.componentParent.handleShowPdf(id);
            }else if(type == 'download'){
                this.props.context.componentParent.handleDownload(id, name);
            }
        };
        if(this.props && this.props.data && this.props.data.attachment && this.props.data.attachment.length > 0){
            return (
                <div>
                    {this.props.data.attachment.map((item, i) => {return (
                        <div key={i}><a className="mr-1" onClick={(e) => handleDownload(e, item.file_id, item.type, item.name)}>{item.name}</a>&nbsp;&nbsp;</div>
                    )})}
                </div>
            );
        }else{
            return null
        }
    }

};
 


export default Attachment;

This can be used in AG-grid

  const gridOptions = {
            columnDefs: [
                { field: 'name', headerName: 'Name', hide: false },
                { field: 'apply_end_date', headerName: 'Deadline', },
                {
                    field: 'files', headerName: 'Application Form', minWidth: 400,
                    cellRendererFramework: Attachment,
                },
                {
                    field: 'funding_id',
                    headerName: 'Action',
                    cellRendererFramework: CustomBtn
                },
            ],

 

Wednesday, November 24, 2021

Select example in React.js



Reference:

https://react-select.com/home

https://www.npmjs.com/package/react-select 

https://pretagteam.com/question/how-to-pass-props-to-custom-components-in-reactselect

example 

                                    <div className="col-2 text-left form-group">
                                        <Select
                                            id="searchYear"
                                            name="searchYear"
                                            closeMenuOnSelect={true}
                                            components={this.props.animatedComponents}
                                            onChange={value => this.props.setSearchYear( value.value )}
                                            options={this.props.yearList}
                                            defaultValue={[{ label: 'All Fiscal Years', value: 0 }]}
                                        />
                                    </div>
"options" is for dropdown menu.

About components props

import makeAnimated from 'react-select/lib/animated';

const colourOptions = [] class App extends React.Component { render(){ return ( <Select className="mt-4 col-md-6 col-offset-4" components={makeAnimated()} isMulti options={colourOptions} /> ); } } export default App;

 


AgGrid in react.js



1. AgGrid in react.js Example: GridRenderer.js

import React, { Component } from 'react';
import {AgGridReact} from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-balham.css';
import "ag-grid-enterprise";
import { LicenseManager } from "ag-grid-enterprise";

//Input LicenseKey here
LicenseManager.setLicenseKey(
);

class GridRenderer extends Component {

    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div className={this.props.gridOptions.pagination == true ? "ag-theme-balham pagi" : "ag-theme-balham"}>
                <AgGridReact
                    gridOptions={this.props.gridOptions}
                    rowData={this.props.rowData}
                    onGridReady={this.props.onGridReady}
                >
                </AgGridReact>
            </div>
        );
    }

};

export default GridRenderer;

2) To call this component from another component

import React, { Component, useState } from 'react';
import GridRenderer from '../../components/GridRenderer';
import Select from 'react-select';
import { Spinner } from 'react-bootstrap';

class ApplicationList extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (

                                        <div className="grid-wrapper mb-3">
                                            <GridRenderer
                                                gridOptions={this.props.type === 3 ? this.props.gridOptions3 : this.props.gridOptions2}
                                                rowData={this.props.searchResult}
                                                onGridReady={this.props.onGridReady2}
                                            />
                                        </div>
        )
    }
};

export default ApplicationList;


 


vi, Unable to open swap file for "file",



The reason is  disk space  full

I: error log file

/var/log/httpd/error_log

/var/www/html/tracs/new6sp/application/logs

/var/www/html/tracs/tracs/application/logs

 

 rm  /var/www/html/tracs/tracs/application/logs/log*.php

 rm /var/www/html/tracs/new6sp/application/logs/log*.php

sudo rm  /var/log/httpd/access_log-20211121

Some Examples in Laravel Model



1. get List of years:


    public function getYearList(){
        $years = Application::select('year')->distinct()->orderBy('year')->get();
        $yearList = [];
        if(!empty($years)){
            foreach($years as $y){
                $yearList[] = ['label'=>$y->year, 'value'=>$y->year];
            }
        }
        return $yearList;
    }

2. Select and return an array:

public function getEmailTemplates(){
        return NotificationTemplate::where('status', 'active')->where('trigger_status', '<>', 'Submitted')->get()->toArray();
    }


3.Delete a row:

    public function delLogByAppId($appId){
        FundingLog::where('application_id', $appId)->delete();
    }

4. Use when and with

 Application::with(['funding:type'])

In Application model, there is funding function. In Funding model,  there is a column type

Application::with(['funding:type']) to get all the columns in Application model and type from Funding model

class Application extends Model
{
    use HasFactory;

    protected $table = 'funding_application';
    protected $primaryKey = 'application_id';

    function funding(){
        return $this->belongsTo(Funding::class, 'funding_id', 'funding_id');
    }
}

//when $computingId is true

when($computingId, function($query) use ($computingId) {

Full example:

       $applications = Application::with(['funding:type'])
                                    ->when($computingId, function($query) use ($computingId) {
                                            return $query->where('created_by', '=', $computingId);
                                        })
                                    ->when($fundingArr, function($query) use ($fundingArr) {
                                        return $query->whereIn('funding_id', $fundingArr);
                                    })
                                   ->orderBy('created_at', 'desc')
                                    ->get();


Tuesday, November 23, 2021

What does x <> y mean?



x <> y

means "not equal", either less than or greater than

in SQl <> is the same as != (not equal) excepts for NULLS of course, in that case you need to use IS NULL or IS NOT NULL

Laravel PHP: add Log



Model for table MyLog:

<?php

namespace App\Models\Log;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MyLog extends Model
{
    use HasFactory;

    protected $table = 'MyLog';
    protected $primaryKey = 'id';
}

?>

In another Log_model

<?php

namespace App\Models\Log;

use Illuminate\Foundation\Auth\User as Authenticatable;

use App\Models\Eloquent\Log\MyLog;
 

class Log_model  extends Authenticatable
{
    public function addLog($appId, $desc){
        $log = new MyLog;
        $log->application_id = $appId;
        $log->modified_by = cas()->user();
        $log->modified_at = date("Y-m-d H:i:s");
        $log->description = $desc;
        $log->timestamps = false;
        $log->save();
        return $log->id;
    }

?>