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;
    }

?>