vendredi 7 juillet 2023

Handling unchecked checkboxes when the element name uses array notation

I have a form that is displayed in a table. This table has some elements and javascript which allows the template row to be duplicated to allow the user to add/remove rows as they want.

Here is a simplified version of the template

<tr data-being_removed="false" data-type="pickup" id="stop_table_row_template" style="display: none;">
    <td>
        <div class="input-group" style="margin: 0px;">
            <input type="text" placeholder="Pickup Number" class="form-control form-control-sm" name="stops[stop_number][]">
            <div class="input-group-text">
                <input class="form-check-input mt-0" name="stops[require_appointment][]" type="checkbox" value="1">
                &nbsp;Req. Appt.
            </div>
        </div>
        <select placeholder="Location" class="form-select ship_to_selector form-control-sm mt-1" name="stops[location_id][]">
            <option value="">Location</option>
        </select>
    </td>
</tr>

However, checkboxes are not sent to the server if they are not checked. Usually to get around this I would create a hidden input with an identical name. However, in this case, that would cause the actual checkbox to be associated to the wrong row because the hidden input will ALWAYS be sent but the checkboxes will also SOMETIMES be sent, throwing off the implied indexes.

In the current code, it does not work for the opposite reason. For example, if the user has 3 rows, but the checkbox is only checked on the 2nd row, the form thinks the checkbox belongs to the first row because there is no matching name attribute sent to the server from the first row.

I would like to avoid having to specify indexes in the name attributes themselves. Is there any way I can send a "0" value for the name of the checkbox if the one with "1" value is not checked?




jeudi 6 juillet 2023

How to make a custom FlutterFlow checkBox

i am trying to build a custom check box like this: enter image description here

which is simply a round container containing an icon inside, clicking on it will change the container background color and the icon color,

i tried to build a custom widget in flutter flow using custom checkbox flutter packages but they all need me to pass a function to the custom but i have the following error:

Unknown error compiling custom code. A common cause is a custom widget or action whose name in the code does not match the name provided in the editor.

that happened again when i tried to build it myself without using packages here is the code i searched and found:

    // Automatic FlutterFlow imports
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/widgets/index.dart'; // Imports other custom widgets
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom widget code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

class IngridentsCheckBox extends StatefulWidget {
  const IngridentsCheckBox({
    Key? key,
    this.width,
    this.height,
    required this.onChange,
    required this.isChecked,
    required this.size,
    required this.iconSize,
    required this.selectedColor,
    required this.selectedIconColor,
    required this.borderColor,
    required this.checkIcon,
  }) : super(key: key);

  final double? width;
  final double? height;
  final Function onChange;
  final bool isChecked;
  final double size;
  final double iconSize;
  final Color selectedColor;
  final Color selectedIconColor;
  final Color borderColor;
  final Icon checkIcon;

  @override
  _IngridentsCheckBoxState createState() => _IngridentsCheckBoxState();
}

class _IngridentsCheckBoxState extends State<IngridentsCheckBox> {
  bool _isSelected = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _isSelected = !_isSelected;
          widget.onChange(_isSelected);
        });
      },
      child: AnimatedContainer(
        margin: EdgeInsets.all(4),
        duration: Duration(milliseconds: 500),
        curve: Curves.fastLinearToSlowEaseIn,
        decoration: BoxDecoration(
            color: _isSelected
                ? widget.selectedColor ?? Colors.blue
                : Colors.transparent,
            borderRadius: BorderRadius.circular(3.0),
            border: Border.all(
              color: widget.borderColor ?? Colors.black,
              width: 1.5,
            )),
        width: widget.size ?? 18,
        height: widget.size ?? 18,
        child: _isSelected
            ? Icon(
                Icons.check,
                color: widget.selectedIconColor ?? Colors.white,
                size: widget.iconSize ?? 14,
              )
            : null,
      ),
    );
  }
}

and those are the parameters i am sending to the custom widget: enter image description here

i am getting the same error which is not clear enough to know exactly what is the issue, in previous versions of the code the error disappeared when i removed "onChange" function, so i do not know if it was the reason,

i also tried to do it using flutter state but couldn't make it, so i will be thankful if someone helps,

PLEASE NOTE: the code quoted is for a custom checkbox i found on stackoverflow, i used to customize it later if worked on flutterflow but i couldn't make it work




mercredi 5 juillet 2023

Need to get or populate the checkbox status when clicked on edit

I've check boxes displayed in the Recycler view with edit and delete options. Now I need to see / populate the data / get the Clicked / checked checkBox when I click on edit.

My Recycler View Activity

class RecView : AppCompatActivity() {

private var is_Role01: Boolean = false
private var is_Role02: Boolean = false
private var is_Role03: Boolean = false
private var is_Role04: Boolean = false
private var is_Role05: Boolean = false

private lateinit var addsBtn: FloatingActionButton
private lateinit var recv: RecyclerView
private lateinit var userList: ArrayList<UserData>
private lateinit var myAdapter: MyAdapter
private lateinit var RN: EditText
private lateinit var UN: CheckBox
private lateinit var PN: CheckBox
private lateinit var BD: CheckBox
private lateinit var AN: CheckBox
private lateinit var PR: CheckBox

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_recview)
    userList = ArrayList()
    addsBtn = findViewById(R.id.addingBtn)
    recv = findViewById(R.id.mRecycler)
    myAdapter = MyAdapter(this, userList)
    recv.layoutManager = LinearLayoutManager(this)
    recv.adapter = myAdapter
    addsBtn.setOnClickListener { addInfo() }
}


@SuppressLint("NotifyDataSetChanged")
private fun addInfo() {
    val inflater = LayoutInflater.from(this)
    val v = inflater.inflate(R.layout.adduser, null)
    val addDialog = AlertDialog.Builder(this)

    RN = v.findViewById(R.id.roleName)
    UN = v.findViewById(R.id.role01)
    PN = v.findViewById(R.id.role02)
    BD = v.findViewById(R.id.role03)
    AN = v.findViewById(R.id.role04)
    PR = v.findViewById(R.id.role05)

    addDialog.setView(v)
    addDialog.setPositiveButton("Ok") { dialog, _ ->
        val rolename = RN.text.toString()
        val names = UN
        val number = PN
        val dob = BD
        val anni = AN
        val per = PR

        userList.add(UserData("Role Name : $rolename", names, number, dob, anni, per))
        myAdapter.notifyDataSetChanged()
        Toast.makeText(this, "Adding User Information Success", Toast.LENGTH_SHORT).show()
        dialog.dismiss()

        UN.setOnCheckedChangeListener { compoundButton, b ->
            val checked: Boolean = UN.isChecked
            is_Role01 = checked
        }
        PN.setOnCheckedChangeListener { compoundButton, b ->
            val checked: Boolean = PN.isChecked
            is_Role02 = checked
        }
        BD.setOnCheckedChangeListener { compoundButton, b ->
            val checked: Boolean = BD.isChecked
            is_Role03 = checked
        }
        AN.setOnCheckedChangeListener { compoundButton, b ->
            val checked: Boolean = AN.isChecked
            is_Role04 = checked
        }
        PR.setOnCheckedChangeListener { compoundButton, b ->
            val checked: Boolean = PR.isChecked
            is_Role05 = checked
        }


    }
    addDialog.setNegativeButton("Cancel") { dialog, _ ->
        dialog.dismiss()
        Toast.makeText(this, "Cancel", Toast.LENGTH_SHORT).show()
    }
    addDialog.create()
    addDialog.show()
}

}

My Adapter Class Where I have edit and delete options.

class MyAdapter(val c: Context, val userList: ArrayList) : RecyclerView.Adapter<MyAdapter.UserViewHolder>() {

inner class UserViewHolder(val v: View) : RecyclerView.ViewHolder(v) {
    var roleName: TextView = v.findViewById(R.id.mRoleName)
    var name: CheckBox = v.findViewById(R.id.role01)
    var mbNum: CheckBox = v.findViewById(R.id.role02)
    var dob: CheckBox = v.findViewById(R.id.role03)
    var anni: CheckBox = v.findViewById(R.id.role04)
    var per: CheckBox = v.findViewById(R.id.role05)

    var mMenus: ImageView

    init {
        mMenus = v.findViewById(R.id.mMenus)
        mMenus.setOnClickListener { popupMenus(it) }
    }

    @SuppressLint("DiscouragedPrivateApi", "NotifyDataSetChanged")
    private fun popupMenus(v: View) {
        val position = userList[adapterPosition]
        val popupMenus = PopupMenu(c, v)
        popupMenus.inflate(R.menu.menu)
        popupMenus.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.editText -> {
                    val v = LayoutInflater.from(c).inflate(R.layout.adduser, null)
                    val roleName = v.findViewById<EditText>(R.id.roleName)
                    val name = v.findViewById<CheckBox>(R.id.role01)
                    val number = v.findViewById<CheckBox>(R.id.role02)
                    val dob = v.findViewById<CheckBox>(R.id.role03)
                    val anni = v.findViewById<CheckBox>(R.id.role04)
                    val per = v.findViewById<CheckBox>(R.id.role05)
                    AlertDialog.Builder(c).setView(v).setPositiveButton("Ok") { dialog, _ ->
                        position.roleName = roleName.text.toString()
                        position.userName = name
                        position.userMb = number
                        position.userDob = dob
                        position.userAnni = anni
                        position.per = per
                        notifyDataSetChanged()
                        Toast.makeText(c, "User Information is Edited", Toast.LENGTH_SHORT)
                            .show()
                        dialog.dismiss()

                    }.setNegativeButton("Cancel") { dialog, _ ->
                        dialog.dismiss()

                    }.create().show()

                    true
                }
                R.id.delete -> {
                    /**set delete*/
                    AlertDialog.Builder(c).setTitle("Delete").setIcon(R.drawable.ic_warning)
                        .setMessage("Are you sure delete this Information")
                        .setPositiveButton("Yes") { dialog, _ ->
                            userList.removeAt(adapterPosition)
                            notifyDataSetChanged()
                            Toast.makeText(c, "Deleted this Information", Toast.LENGTH_SHORT)
                                .show()
                            dialog.dismiss()
                        }.setNegativeButton("No") { dialog, _ ->
                            dialog.dismiss()
                        }.create().show()

                    true
                }
                else -> true
            }

        }
        popupMenus.show()
        val popup = PopupMenu::class.java.getDeclaredField("mPopup")
        popup.isAccessible = true
        val menu = popup.get(popupMenus)
        menu.javaClass.getDeclaredMethod("setForceShowIcon", Boolean::class.java)
            .invoke(menu, true)
    }
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    val v = inflater.inflate(R.layout.list_item, parent, false)
    return UserViewHolder(v)
}

override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
    val newList = userList[position]
    holder.roleName.text = newList.roleName

    if (newList.userName.isChecked) {
        holder.name.visibility = View.VISIBLE
    } else {
        holder.name.visibility = View.GONE
    }

    if (newList.userMb.isChecked) {
        holder.mbNum.visibility = View.VISIBLE
    } else {
        holder.mbNum.visibility = View.GONE
    }


    if (newList.userDob.isChecked) {
        holder.dob.visibility = View.VISIBLE
    } else {
        holder.dob.visibility = View.GONE
    }


    if (newList.userAnni.isChecked) {
        holder.anni.visibility = View.VISIBLE
    } else {
        holder.anni.visibility = View.GONE
    }

    if (newList.per.isChecked) {
        holder.per.visibility = View.VISIBLE
    } else {
        holder.per.visibility = View.GONE
    }
}

override fun getItemCount(): Int {
    return userList.size
}

}

My Data Class

data class UserData( var roleName: String, var userName: CheckBox, var userMb:CheckBox, var userDob:CheckBox, var userAnni:CheckBox, var per:CheckBox )

The Data which are given while saving initially should be populated to the edit screen. Could anyone help me out with this.

In here I've selected 2 check boxes and given a Role Name as Admin, now when I click on menu the same data should be populated or get

When I click on edit, the data selected in the previous page should be visible.




How to pass data of the checkbox group with vue quasar?

In the checkbox group I'm itterating through an array, but when I reform the array to the array of objects with label prop, value prop, hence passing it in the template the code doesn't run. Having the error - v-html will override element children. It comes because of the v-html="opt" in the template. I'm expecting to render the text of the stringOptions array.

<q-select
              hide-bottom-space
              options-dense
              hide-dropdown-icon
              input-debounce="500"
              @filter="filterFn"
              style="width: 200px"
              counter
              hint="Selected items"
              use-input
              dense
              hide-selected
              clearable
              filled
              v-model="model"
              :options="filterOptions"
              label="Actors"
              multiple
            >
              <template
                v-slot:option="{ itemProps, opt, selected, toggleOption }"
              >
                <q-item v-bind="itemProps">
                  <q-item-section>
                    <q-item-label v-html="opt"></q-item-label> // error here
                  </q-item-section>
                  <q-item-section side>
                    <q-checkbox
                      :model-value="selected"
                      @update:model-value="toggleOption(opt)"
                    ></q-checkbox>
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
            
<script>
export default {
    stringOptions: [
    'All',
    'Alfa',
    'Omega',
    'Lampda',
    // { label: 'All', value: 'all' },
    // { label: 'Alfa', value: 'alfa' },
    // { label: 'Omega', value: 'omega' },
    // { label: 'Lampda', value: 'lampda' }
  ],
}
</script>



mardi 4 juillet 2023

Saving checkbox state when X item is selected?

I am creating the GUI of a preprocessor to be able to solve flow problems, I need the items that are in the ListWidget to save the state of the checkbox that I want to select

Example of the behavior I require

Is this possible? If so, how would I achieve it?

I tried using the setData method, I wanted to save the state of each checkbox using an array with values ​​of 0 and 1, so every time one of the items was selected, I expected the state to be saved as a value in the array, to later read it when the item is selected again and place the corresponding checkbox as checked.

    self.bordesWindow.ui.listWidgetVarEsc.itemSelectionChanged.connect(self.settingCheckBoxStateBorde)
    self.bordesWindow.ui.listWidgetVarEsc.itemClicked.connect(self.gettingCheckBoxStateValue)

def settingCheckBoxStateBorde(self):
    self.arrayValuesCheckboxesBordes = np.zeros(3)
    self.constDataBordeCheckboxState = Qt.ItemDataRole.UserRole
    item = self.bordesWindow.ui.listWidgetVarEsc.currentItem()
    item.setData(self.constDataBordeCheckboxState, self.arrayValuesCheckboxesBordes)
    if self.bordesWindow.ui.checkBoxVariablesEscValor.isChecked():
        item.data(self.constDataBordeCheckboxState)[0] = 1
    elif self.bordesWindow.ui.checkBoxVariablesEscFlujo.isChecked():
        item.data(self.constDataBordeCheckboxState)[1] = 1
    elif self.bordesWindow.ui.checkBoxVariablesEscConveccion.isChecked():
        item.data(self.constDataBordeCheckboxState)[2] = 1

def gettingCheckBoxStateValue(self):
    item = self.bordesWindow.ui.listWidgetVarEsc.currentItem()
    if item.data(self.constDataBordeCheckboxState)[0] == 1:
        self.bordesWindow.ui.checkBoxVariablesEscValor.setChecked(True)
    elif item.data(self.constDataBordeCheckboxState)[1] == 1:
        self.bordesWindow.ui.checkBoxVariablesEscFlujo.setChecked(True)
    elif item.data(self.constDataBordeCheckboxState)[2] == 1:
        self.bordesWindow.ui.checkBoxVariablesEscConveccion.setChecked(True)



VBA for insert commumn with checkboxes and afterward print checked boxes

I have an Excel file where i want to use VBA to insert a column in front of the excising column A. The file contains other VBA's for generate a list. So, the list can change in numbers of columns and rows. I use below VBA to print, it works just fine. But I want it to do like: Press print bottom, the VBA insert a new column A with check boxes. A Msg box pops up and stay on top (Press OK when you are ready to print), then you can select the lines that you want to print in the check boxes. If you don't select any check boxes the print VBA should print all active lines as it do now, except the new column A with check boxes.

Sub Print()

Call Uden_pre_booking   'Starts the VBA that makes a fresh list

Dim ws3 As Worksheet
Dim EndRow As Long, EndCol As Long

Set ws3 = Sheets("Vis_Oversigt")

EndCol = ws3.Cells(4, 6).Value + 10
EndRow = ws3.Range("B" & Rows.Count).End(xlUp).Row + 2
   
ws3.PageSetup.PrintArea = ws3.Range(Cells(1, 1), Cells(EndRow, EndCol)).Address



ActiveSheet.PrintPreview

End Sub

I have tried several VBA's from different sites, but doesn't manage to get it into a functional VBA.

Hope that someone will help me make a functionally VBA.




lundi 3 juillet 2023

How to handle checkbox change in React.js?

I'm trying to handle change of the value when a check box is clicked. The component loads a response like this:

[
   {
       "id_ver_group": 7,
       "checklist": [
           {
            "check": "Custom ver 1",
            "valor": false,
            "opcional": true
           },
        {
            "check": "Custom ver 2",
            "valor": false,
            "opcional": false
        }
       ],
       "id_ver_group_char": "7",
       "fecha_crea": "2023-07-02T18:07:56.756521"
  },
  {
       "id_ver_group": 6,
       "checklist": [
           {
               "check": "Custom ver 1",
               "valor": false,
               "opcional": true
           },
           {
               "check": "Custom ver 2",
               "valor": false,
               "opcional": false
           },
       ],
       "id_ver_group_char": "7",
       "fecha_crea": "2023-07-02T18:07:56.756521"
  },
]

The response is grouped by "id_ver_group" in an "Accordion" tag where each "checklist" item is displayed in a table, its columns are: "verify" (string), "value" (bool) and "optional " (bool) , the checkbox tag is used to display the "value" and "optional" columns, the latter being read-only. This is the component code:

// imports...
import {
  Accordion,
  AccordionSummary,
  AccordionDetails,
  Typography,
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableCell,
  Checkbox,
  Select,
  InputLabel,
  Button,
} from '@material-ui/core'

export function AddEditChecklist(props) {
     
const { Tanques, onClose, onRefetch } = props
const { Successful, errores } = alertas()
const { Data, getBaseVer } = useVerificaciones()
const { addTankVer, updateTankVer } = useTanques()
const { OperadorDB, getOperadorDB } = useOperador()
const [selectedOperator, setSelectedOperator] = useState('');
const [isOperatorSelected, setIsOperatorSelected] = useState(true);

const [selectedGroup, setSelectedGroup] = useState(null);
  const [selectedGroupIndex, setSelectedGroupIndex] = useState(null);

  useEffect(() => {
    getOperadorDB()
    getBaseVer()
  }, []);

  const [data, setData] = useState([]);

  useEffect(() => {
    setData(Data?.map(item => ({
      ...item,
      checklist: item.checklist.map(checklistItem => ({
        ...checklistItem,
        valor: false  
      }))
    })) || []);
  }, [OperadorDB, Data]);

  const handleAccordionChange = (groupId) => {
    setSelectedGroupIndex(groupId); 
    setSelectedGroup(groupId)
    
    if (selectedGroup === groupId) {
      setSelectedGroup(null); 
    } else {
      setSelectedGroup(groupId); 
    }
  };

// check box handle
  const handleCheckboxChange = (groupId, itemIndex, checklistItem) => {
    setData((prevData) => {
      const updatedData = [...prevData];
      const groupData = updatedData[groupId];

      if (groupData && groupData[itemIndex]) {
        checklistItem.valor = !checklistItem.valor; 
      }

      return updatedData;
    });
  };

  // group data by id
  const groupedData = data ? data.reduce((groups, item) => {
    const groupId = item.id_ver_group;
    if (!groups[groupId]) {
      groups[groupId] = [];
    }
    groups[groupId].push(item);
    return groups;
  }, {}) : {};
// handleSubmit...

return (
    <>
      {/* checklist */}
      {Object.keys(groupedData).map((groupId) => (
        <Accordion
          key={groupId}
          expanded={selectedGroup === groupId}
          onChange={() => handleAccordionChange(groupId)}
        >
          <AccordionSummary expandIcon={<ExpandMoreIcon />}>
            <Typography variant="h6">Conjunto de verificaciones # {groupId}</Typography>
          </AccordionSummary>
          <AccordionDetails>
            <div>
              {groupedData[groupId].map((item, index) => (
                <div key={item.id_ver_group}>
                  <Table>
                    <TableHead>
                      <TableRow>
                        <TableCell><strong>Verificación</strong></TableCell>
                        <TableCell><strong>¿Cumple?</strong></TableCell>
                        <TableCell><strong>¿Opcional? (no modificable)</strong></TableCell>
                      </TableRow>
                    </TableHead>
                    {item.checklist.map((checklistItem) => (
                      <TableBody key={checklistItem.check}>
                        <TableRow>
                          <TableCell>
                            {checklistItem.check}
                          </TableCell>
                          <TableCell>
                            <Checkbox
                              checked={checklistItem.valor}
                              name={checklistItem.check}
                              onChange={() => handleCheckboxChange(groupId, index, checklistItem)}
                            />
                          </TableCell>
                          <TableCell>
                            <Checkbox
                              readOnly
                              checked={checklistItem.opcional}
                              name={checklistItem.check}
                            />
                          </TableCell>
                        </TableRow>
                      </TableBody>
                    ))}
                  </Table>
                </div>
              ))}
            </div>
          </AccordionDetails>
        </Accordion>
      ))}
      <br></br>
      <Divider></Divider>
      <br></br>
      <Button variant="contained" color="primary" onClick={handleSubmit}>
        Save
      </Button>
    </>
  )
} 

Doing some research, I was able to come up with something to handle the checkbox changing, but the checkbox doesn't change its value when clicked. I really don't know how to solve this. Any help is appreciated.