Fastadmin step in the pit diary-2. Magic change form

Fastadmin step in the pit diary-2. Magic change form

After days and nights of searching, we can finally slowly start this, step on a few pits, and record it

Pit 1 - the foreground cannot display emoji characters

The first few emoji are two bytes, which can be displayed normally in the default double byte encoding of utf8, such as the red exclamation mark. Later, emoji gradually became four characters. The original utf8  Gerneral  CI character set could not be displayed, so it must be set manually

Several conditions are required to display emoji

  1. The character set of the database is utf8mb4, and the character set of mysql is utf8mb4

  2. The character set of the field is ut8mb4, and the character set of mysql is utf8mb4

  3. When connecting to the database in the background, you also need to select ut8mb4, which is similar to this file in db.php

    for example

It has not been successful before. It turns out that condition 3 is not met, which leads to what the front desk always sees? Instead of emoji, I changed 3 and finally succeeded

Pit 2-Bootstrap-table display image or custom rendering display

For example, there is a gender field in the database to store the gender of the user. 0 is male and 1 is female

When rendering to the BT table (bootstrap table, the same below), you want to directly display men or women,

Or if you want to customize the css of the table content, you need to use BT's formatter renderer

First of all, you need to complete the operation of generating table from curd of step log 1, and then go to the corresponding js of the foreground page

The location is public/assets/js/[backend|frontend] which is determined in the foreground and background according to your bt table / < plug-in name > / < Table >. JS

Find the corresponding fields, such as

Just add a formatter. If it's from this page, it can be placed in the api below the page. Then the fields can be rendered correspondingly. Then notice that the pit is coming

The Controller of this page is Controller, not Table, so to access this renderer, it must be Controller.api.formatter.xxxx, not Table.api.formatter.xxxx

Common formatter s are

Table.api.formatter.icon //Render as icon button
Table.api.formatter.image //Render as a single picture
Table.api.formatter.images //Render to multiple pictures
Table.api.formatter.content //Automatic content capture
Table.api.formatter.status //Render to state
Table.api.formatter.normal //Render to label
Table.api.formatter.toggle //Render as switch
Table.api.formatter.url //Render as text box link
Table.api.formatter.search //Render as search link
Table.api.formatter.addtabs //Render to open new tab link
Table.api.formatter.dialog //Render as a pop-up link
Table.api.formatter.flag //Render as flag
Table.api.formatter.label //Render as flag
Table.api.formatter.datetime //Render to date time
Table.api.formatter.operate //Render to action bar button
Table.api.formatter.buttons //Render as button group

The final effect is as follows

Pit 3 - click button cannot be set as pop-up window

The location is public/assets/js/[backend|frontend], which is determined by your bt table in the foreground and background / < plug-in name > / < Table >. JS the classname here is written as BTN dialog, which can be set as pop-up window. The url is the controller corresponding to pop-up window

You can output the corresponding page in the controller by referring to the figure below. The figure below outputs the rendered view/index.html

Pit 4 - the update event in the pop-up window will not close itself after completion

I'm a non mainstream method, because I've tried all the callback methods and have no response. I can't make the pop-up data interact with the parent window, and I'll find out a set of methods by myself

Point 1. The form must be ajax

Only when the Ajax form is submitted will the small window in the upper right corner prompt that the update succeeds or fails. If it is submit in the form, the global page will be refreshed and displayed successfully

Point 2. Learn to use parent to control the parent window

In the pop-up window, parent represents the parent window, so that you can access and perform related operations

In the pop-up window, you can execute the following js code to realize data interaction

parent.Toastr.success(data)			//Parent success Popup
parent.Toastr.error(data)			//Parent failure Popup
parent.Layer.closeAll()			//The parent closes all pop ups, that is, pop ups can close themselves


This is the ajax method of updating and wechat subscription push. The case of data interaction with the parent after updating push

//js file executed in pop-up window
<script>
    function submit() {
      var url = 'mypchelper/orders/update'
      var formData = $('#myForm').serialize()
      //Serialization to a = 1 & B = 2
      Fast.api.ajax({
        url: url,
        type: 'POST',
        data: formData,
        success: function(data) {
          parent.Toastr.success(data.msg)
          switch (data.data.errcode) {
            case 0:
              parent.Toastr.success('The message has been pushed to the user's mobile phone')
              break
            case 40003:
              parent.Toastr.error('Push error: touser field openid Empty or incorrect')
              parent.Toastr.error('Error message:' + data.data.errmsg)
              break
            case 40037:
              parent.Toastr.error('Push error: Subscription template id Empty incorrect')
              parent.Toastr.error('Error message:' + data.data.errmsg)
              break
            case 43101:
              parent.Toastr.error(
                'Push error: the user refuses to accept the message. If the user has previously subscribed, it means the user has cancelled the subscription relationship'
              )
              parent.Toastr.error('Error message:' + data.data.errmsg)
              break
            case 47003:
              parent.Toastr.error(
                'Push error: template parameters are inaccurate, may be empty or do not meet the rules, errmsg It will prompt which field is wrong'
              )
              parent.Toastr.error('Error message:' + data.data.errmsg)
              break
            case 41030:
              parent.Toastr.error(
                'Push error: page The path is not correct. It needs to be ensured that it exists in the current network version applet app.json Bring into correspondence with'
              )
              parent.Toastr.error('Error message:' + data.data.errmsg)
              break
          }
          parent.Layer.closeAll()
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          Toastr.error('Network error, please try again later!')
          console.log('Error message to submit request:' + errorThrown + XMLHttpRequest)
        }
      })
    }
  </script>

Point 3. The isAjax() function in the controller handles the data request of ajax

if ($this->request->isAjax()) { //form submit ajax request
		$result = false;
		$params = $this->request->post("r/a"); //The input name of the form in the front-end page is r [corresponding field name]
  	if ($params) {
      $id = $params['id'];    //Get data assignment 
    }
  //Then the sql method can be used for processing
  ............sql process.............
  if ($result !== false) {
     $res = $this->temMsg($openid, $problem, $orderreply);   //I encapsulate a wechat push function here
     $this->success('Update success', null, $res);    //Transfer res data to the front end
     //$this - > redirect ('mypchelper / orders / index ', 5,' page skipping... '; / / don't try this, it will jump in the pop-up window
  } else {
    $this->error(__('No rows were updated'));
  }
}

For details Customize the pop-up page. After Ajax submission, the current pop-up will not be closed?

And there's the mainstream approach of others, Share custom button BTN dialog refresh the parent form after closing the pop-up window refresh close button callback custom

Pit 5 fastadmin bootstrap table table accessing multi table data (joint query multi table) (thinkphp association model)

Sometimes we have this situation

When a database table is linked with other tables to output data, we need to work hard when fetching data

The official gives an example. In controller/example/relationmodel.php, you can watch the change, but we will write it ourselves

Let's give you an example

For instance

data base

Now there are orders and users tables

The id field in the orders table and the id field in the users table are the same thing

That is to say, the orders.id'users field is a foreign key

When outputting, we need to output the information of orders and users together. This is very easy to implement in sql, but now it is implemented with the php method of fastadmin, so let's look at the controller first

Controller initialization

Actively construct index method in controller/demo/orders.php instead of inheriting the method encapsulated by backend itself

Be sure to have $this - > relationsearch = true; it means multi table joint query, and then load the required subsidiary table $this - > searchfields = "users"; / / the required table

It's easy to confuse here, because users is a table and users is a data layer model. We need to use the with() function to preload the model corresponding to users in the subsidiary table, that is

$total = $this->model  //Load the model corresponding to this controller, which is the model of orders
                ->with("Users") //Preload the model of the corresponding attachment table
                ->where($where)
                ->order($sort, $order)
                ->count();
$list = $this->model
                ->with("Users")
                ->where($where)
                ->order(['processstatus' => 'ASC', $sort => $order])
                ->limit($offset, $limit)
                ->select();
$result = array("total" => $total, "rows" => $list);

Then go to the corresponding model and add the belongTo() function. The corresponding parameter is belongto (table name, id of the original table, id of the external table. I don't know the connection type [left connection, right connection, etc.). Here we are

public function users()
    {
        return $this->belongsTo('Users', 'id_users', 'id', [], 'LEFT')->setEagerlyType(0);
        //Corresponding table
    }

Then you need to set the output in the front-end js, the location is public/assets/js/[backend|frontend], which is determined in the foreground and background according to your bt table / < plug-in name > / < Table >. js

Fields here should be set as attached tables. Fields are like some field s here. If the following header title wants native output, its location is in application/[admin to see if it is a background file] / Lang / < plug-in name / table. PHP >

Here are some fields after adding the attached table fields to be output

//Bootstrap table render field in orders.js
{ field: 'users.name', title: __('Master name') }, //Corresponding to the field in the model
{ field: 'users.mobile', title: __('Master mobile phone') },
{
    field: 'users.QQ',
    title: __('Machine owner QQ'),
    formatter: Controller.api.formatter.tolink
},
 { field: 'users.address', title: __('Dormitory address') },
 { field: 'pcmodel', title: __('Pcmodel') },
 { field: 'problem', title: __('Problem') },

After that, the front end can display the data after joint query normally

Attach complete controller/index

//In controller/demo/orders.php
/**
     * See
     */
    public function index()
    {
        $this->relationSearch = true;
        $this->searchFields = "users"; //Tables needed
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with("Users") //Preload the corresponding model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with("Users")
                ->where($where)
                ->order(['process' => 'ASC', $sort => $order])
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

Reference: FastAdmin multi table associated query

Pit 6 - the user cannot access the customized module after changing

Remember to set it in the controller header

protected $noNeedRight = ['*'];  //Access without permission

Of course, the authorities also gave instructions

Base class parsing

/**
 * No login method, no authentication
 * @var array
 */
protected $noNeedLogin = [];  //It contains corresponding modules such as' add','edit 'and so on

/**
 * Authentication free method, but login required
 * @var array
 */
protected $noNeedRight = [];

/**
 * Permission Auth
 * @var Auth 
 */
protected $auth = null;

Similar cases

Why authority management does not have authority access

Official references

A diagram to analyze the function of pop-up window in FastAdmin

The function of parsing table list in FastAdmin with one chart

https://www.jianshu.com/p/7c90cddb583f

35 original articles published, 41 praised, 30000 visitors+
Private letter follow

Tags: PHP emoji Database Mobile

Posted on Tue, 04 Feb 2020 04:27:03 -0800 by colforbin05