How to store and retrieve a custom billing address field the right way in WooCommerce?

In The Netherlands addresses are made up of a street name and a number (e.g. Straat 12). A lot of people forget to fill in their number so I want to make a separate field for the number, next to the address. I managed to do that with the woocommerce_default_address_fields as the woocommerce_checkout_fields didn’t work for this.

I thought WooCommerce would take care of the rest, but unfortunately there’s some more things to do that I can’t manage. I hope we can make a good reference point here for adding custom billing fields and cover every step, as the WooCommerce docs lack at this point. I want to:

  1. Show the number after the street name in the WooCommerce mails in
    the address box
  2. Show the number in the single order detail page

I tried adding the number to the email, but this is where I start having trouble. I’ll show you the code I think necessary. This is how I add the number field.

 $address_fields('huisnummer') = array(
    'label'     => __('Huisnummer', 'woocommerce'),
    'placeholder'   => _x('Huisnummer', 'placeholder', 'woocommerce'),
    'required'  => true,
    'class'     => array('form-row-last'),
    'clear'     => true,
    'priority'  => 50
 );

And this is how I’m trying to add this field to the emails, a code that should work according to the WooCommerce docs, but probably only for fields added with the ‘woocommerce_checkout_fields’ hook, as the address fields are saved differently.

 add_filter('woocommerce_email_order_meta_keys', 'my_custom_order_meta_keys');

 function my_custom_order_meta_keys( $keys ) {

     $keys() = 'huisnummer';
     return $keys;

 }

How do I add the number to the email properly? And can I choose where to put it exactly? I would like to put it directly after the street name on the same line.

For this I tried the following, which is showing the label, but not the value. Also, I would like to show this like in the email, on the same line as the street name.

add_action( ‘woocommerce_admin_order_data_after_billing_address’, ‘my_custom_checkout_field_display_admin_order_meta’, 10, 1 );

function my_custom_checkout_field_display_admin_order_meta( $order ){

    echo '<p><strong>'.__('Huisnummer').':</strong> ' . get_post_meta( $order->get_id(), ('billing')('huisnummer'), true ) . '</p>';

}

Thank you for helping!

8 – How to delete a field programmatically

I’ve got a service managing the install/uninstall of my module.

Install create a field attached to the user but I am not able to delete it during the uninstall process…

stacko.services.yml

services:
  stacko.module_installer:
    class: DrupalstackoModuleInstaller
    arguments:
      - '@entity_type.manager'
    tags:
      - { name: service_collector, tag: 'module_install.uninstall_validator', call: addUninstallValidator }

stacko.install

/**
 * Implements hook_install().
 */
function stacko_install() {
  $module_installer = Drupal::service('stacko.module_installer');
  $module_installer->install(());
}

/**
 * Implements hook_uninstall().
 */
function stacko_uninstall() {
  $module_installer = Drupal::service('stacko.module_installer');
  $module_installer->uninstall(());
}

src/ModuleInstaller.php

namespace Drupalstacko;

use DrupalCoreEntityEntityTypeManagerInterface;
use DrupalCoreExtensionModuleInstallerInterface;
use DrupalCoreExtensionModuleUninstallValidatorInterface;
use DrupalfieldEntityFieldStorageConfig;

/**
 * Module installer.
 */
class ModuleInstaller implements ModuleInstallerInterface {

  /**
   * Field storage config manager.
   *
   * @var DrupalfieldFieldStorageConfigStorage
   */
  protected $fieldStorageConfigManager;

  /**
   * Field config manager.
   *
   * @var DrupalfieldFieldConfigInterface
   */
  protected $fieldConfigManager;

  /**
   * Constructor.
   *
   * @param DrupalCoreEntityEntityTypeManagerInterface $entity_type_manager
   *   The entityt type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->fieldStorageConfigManager = $entity_type_manager->getStorage('field_storage_config');
    $this->fieldConfigManager = $entity_type_manager->getStorage('field_config');
  }

  /**
   * {@inheritdoc}
   */
  public function install(array $module_list, $enable_dependencies = TRUE) {
    $this->createFields();
  }

  /**
   * {@inheritdoc}
   */
  public function uninstall(array $module_list, $uninstall_dependents = TRUE) {
    $this->deleteFields();
  }

  /**
   * {@inheritdoc}
   */
  public function addUninstallValidator(ModuleUninstallValidatorInterface $uninstall_validator) {
  }

  /**
   * {@inheritdoc}
   */
  public function validateUninstall(array $module_list) {
  }

  /**
   * Create all fields.
   */
  protected function createFields() {
    $this->createStackoField();
  }

  /**
   * Create Stacko field.
   */
  protected function createStackoField() {
    $this->createStackoFieldStorage();
    $this->createStackoFieldInstance();
  }

  /**
   * Delete all fields.
   */
  protected function deleteFields() {
    $this->deleteStackoField();
  }

  /**
   * Create Stacko field storage.
   */
  protected function createStackoFieldStorage() {
    try {
      $this->fieldStorageConfigManager->create((
        'field_name' => 'field_stacko',
        'entity_type' => 'user',
        'type' => 'text',
        'cardinality' => 1,
        'locked' => FALSE,
        'indexes' => (),
        'settings' => (
          'max_length' => 14,
          'is_ascii' => false,
          'case_sensitive' => false,
        ),
      ))->save();
    }
    catch (Exception $e) {
      if (PHP_SAPI === 'cli') {
        drush_print_r('Either the field_stacko storage already exists or an error occured and it has not been created.');
      }
    }
  }

  /**
   * Create Stacko field instance.
   */
  protected function createStackoFieldInstance() {
    try {
      $this->fieldConfigManager->create((
        'field_name' => 'field_stacko',
        'entity_type' => 'user',
        'bundle' => 'user',
        'label' => 'The stacko',
        'required' => FALSE,
        'settings' => (),
      ))->save();
    }
    catch (Exception $e) {
      if (PHP_SAPI === 'cli') {
        drush_print_r('Either the field_stacko instance already exists or an error occured and it has not been created.');
      }
    }
  }

  /**
   * Delete Stacko field storage.
   */
  protected function deleteStackoField() {
    // Leads to Error: Call to undefined method DrupalfieldFieldStorageConfigStorage::loadByName()
    /* if ($this->fieldStorageConfigManager->loadByName('user', 'field_stacko')) {
      $field_storage->delete();
    } */
    // Doesn't load the field storage | doesn't delete the field.
    /* if ($field_storage = $this->fieldStorageConfigManager->loadByProperties((
      'entity_type' => 'user',
      'field_name' => 'field_stacko',
    ))) {
      kint('test 1');
      $field_storage->delete();
    }
    kint('test 2'); */
    // Doesn't load the field storage | doesn't delete the field.
    if ($field_storage = FieldStorageConfig::loadByName('user', 'field_stacko')) {
      kint('test 1');
      $field_storage->delete();
    }
    kint('test 2');
  }

}

While running deleteStackoField() I only have the ‘test 2’ message. As it’s unable to load the field storage, the field is not deleted.

So I am wondering how can I properly delete my field programmatically ?

content type – Update field default value on a subfolder REST

I have multifolder structure like that:

Opportunities (document library of custom type OPFolder)
     OP0026 (folder of custom type OPFolder)
        Incoming (normal folder)

custom type OPFolder has field OPNumber

I wanted to update Default value for this field at last level e.g. Incoming folder
I’ve tried to post $"{{ '__metadata': {{ 'type':'SP.Field' }}, 'DefaultValue': 'Hello' }}"; to

https://{site}/_api/web/Lists/GetByTitle('Opportunities')/RootFolder/Folders('OP0026')/Folders('Incoming')/ListItemAllFields/OPNumber

Request succeeded but nothing gets set.

Note: Posting the same payload to Doc Library level works fine but it sets default on the content type itself which is not what I want:

https://{site}/_api/web/Lists/GetByTitle('Opportunities')/fields/getbytitle('OPNumber')";

entities – How to properly manage field types for a content type created by a module for Drupal 9?

I’m a bit confused about two different errors I get, which seem to contradict each other. I guess I didn’t register my field types properly. The first one appears when I try to uninstall my module.

DrupalCoreFieldFieldException: Attempt to create a field field_example that does not exist on entity type node. in DrupalfieldEntityFieldConfig->getFieldStorageDefinition() (line 312 of coremodulesfieldsrcEntityFieldConfig.php).

The second one appears as an error message within the UI when I try to fix it by introducing another module which should only create the field type.

Unable to install Helper, field.field.node.content_type_example.field_example already exists in active configuration.

In general, the module calls an external API and fetches data which is then used to create nodes with several fields. These are defined inside the config/install directory. Furthermore, inside src/Plugin/Field there are FieldType, FieldFormatter and FieldWidget classes, more or less as described here.

I used this module when I tried to fix the first error without a helper module. With its help, I removed the field types created by my module in the first place. Unfortunately, I don’t know a lot about drush, which seems to be capable of solving the issue. On the other hand, it would be great if it was possible to “reset” the content type and the field types programmatically whenever the module is installed or uninstalled. So far, I tried the following code, without much luck:

<?php
// mymodule.install file
use DrupalfieldEntityFieldStorageConfig;

function mymodule_install() {
  if (FieldStorageConfig::loadByName('node', 'field_example')) {
    FieldStorageConfig::loadByName('node', 'field_example')->delete();
  }
}

Does someone know how I can fix the error and how I should manage these fields in the future? Thanks!

signal – Field test on iPhone 7. Can’t locate “rsrp0”

I have an unlocked iPhone 7 on T-Mobile, model A1660 on IOS 14.0.1. I’m trying to find the cell signal strength by running the field test as described here. From my reading, rsrp0 is the best option to get a realistic idea of the true cell signal strength. However when I click on the Serving Cell Measurements, instead of seeing a # of fields like “rsrp1”, “rsrp0”, etc, I get the below. Would one of these fields (Measured RSRP perhaps?) provide equivalent information to rsrp0?

Serving Cell Measurements

cakephp – I’m Beginner I need to update my data inlcude some input field text and have 5 file type image in php

this is my database where my all the data is stored

Whenever i want to update my either single data or either single or multiple pictures from existing record only that part would be updated other data would not be changed
this is my update form

Here is my code updatecode

if(isset($_POST(‘Submit’)))
{

// var_dump($_POST);

$var1 = rand(1111,9999);  // generate random number in $var1 variable
$var2 = rand(1111,9999);  // generate random number in $var2 variable

$var3 = $var1.$var2;  // concatenate $var1 and $var2 in $var3
$var3 = md5($var3);   // convert $var3 using md5 function and generate 32 characters hex number


$p_name=$_POST('p_name');

$address_desc=$_POST('address_desc');


$fnm1 = $_FILES("image1")("name");    // get the image name in $fnm variable
$dst1 = "./all_images/".$var3.$fnm1;  // storing image path into the {all_images} folder with 32 characters hex number and file name
$dst_db1 = "all_images/".$var3.$fnm1; // storing image path into the database with 32 characters hex number and file name

$fnm2 = $_FILES("image2")("name");    // get the image name in $fnm variable
$dst2 = "./all_images/".$var3.$fnm2;  // storing image path into the {all_images} folder with 32 characters hex number and file name
$dst_db2 = "all_images/".$var3.$fnm2; // storing image path into the database with 32 characters hex number and file name

$fnm3 = $_FILES("image3")("name");    // get the image name in $fnm variable
$dst3 = "./all_images/".$var3.$fnm3;  // storing image path into the {all_images} folder with 32 characters hex number and file name
$dst_db3= "all_images/".$var3.$fnm3; // storing image path into the database with 32 characters hex number and file name

$fnm4 = $_FILES("image4")("name");    // get the image name in $fnm variable
$dst4 = "./all_images/".$var3.$fnm4;  // storing image path into the {all_images} folder with 32 characters hex number and file name
$dst_db4 = "all_images/".$var3.$fnm4; // storing image path into the database with 32 characters hex number and file name

$fnm5 = $_FILES("image5")("name");    // get the image name in $fnm variable
$dst5 = "./all_images/".$var3.$fnm5;  // storing image path into the {all_images} folder with 32 characters hex number and file name
$dst_db5 = "all_images/".$var3.$fnm5; // storing image path into the database with 32 characters hex number and file name

move_uploaded_file($_FILES("image1")("tmp_name"),$dst1);  // move image into the {all_images} folder with 32 characters hex number and image name
move_uploaded_file($_FILES("image2")("tmp_name"),$dst2); 
move_uploaded_file($_FILES("image3")("tmp_name"),$dst3); 
move_uploaded_file($_FILES("image4")("tmp_name"),$dst4); 
move_uploaded_file($_FILES("image5")("tmp_name"),$dst5); 

$id=$_POST('id');
$p_name=$_POST('p_name');
$address_desc=$_POST('address_desc');
$rooms=$_POST('rooms');
$bathrooms=$_POST('bathrooms');

$bedrooms=$_POST('bedrooms');
$parking=$_POST('parking');

$area=$_POST('area');

$price=$_POST('price');
$region=$_POST('region');
$add_content=$_POST('add_content');
$property_type=$_POST('property_type');
$added_on=$_POST('added_on');

$userid=$_POST('userid');
$statusid=$_POST('statusid');


$query=mysqli_query($con,"update tbltest1 set id='$id' ,p_name='$p_name' , address_desc='$address_desc', image1='$dst_db1', image2='$dst_db2', image3='$dst_db3', image4='$dst_db4', image5='$dst_db5',rooms='$rooms',bathrooms='$bathrooms',bedrooms='$bedrooms',parking='$parking',area='$area', price='$price', region='$region'
,add_content='$add_content',property_type='$property_type',added_on='$added_on',userid='$userid', statusid='$statusid'
where id='$id'");

8 – Node save slow with a field containing lots of paragraphs

I have a node (which uses revisions) that has a Paragraph field. It has around 80 Paragraphs referenced to it. When I save the node programmatically it’s very slow. It seems like the slow down is happening in the preSave() of the Paragraph field. I’m wondering if every referenced Paragraph is being loaded when the node is being saved? And if so is this normal functionality?

Could it just be bad design by myself that I created a node that has a field with 80+ Paragraphs referenced to it? Or is it legitimate to do it this way?

Make “ACF V4 star rating field type” compatible for Advaced custom fields 5

Hello every body i want to make this ACF 4 Star rating plugin compatible for ACF 5. Who can help me please.
I installed the plugin but i can not see star rating field among other field types. This is plugin link.
https://github.com/lienann/acf-starrating

// Include field type for ACF4
function acf_srf_register_fields() {
    
    include_once('acf-starrating-v4.php');
    
}
add_action('acf/register_fields', 'acf_srf_register_fields');   

splistitem – Date of when a Field was populated

Is it possible to get the date of when a choice field was populated? I’m asking because we have a SharePoint list which is automatically populated by an automation and the entries are later reviewed by one of our team members. Whoever is reviewing the entry add his name to the entry through a choice field, and I’d like to get the date when the ‘Reviewed By’ field is populated. I thought about using a calculated column but I’m not sure what formula would get the results I’m looking for.

database – Extracting user field values from dynamic SQL queries

Aim

I have successfully written a fairly long dynamic sql query, however am struggling with a seemingly simple part at the end.

Although, I am able to successfully extract mail and name from the users table, when I try to extract field_first_name it returns the error below.

The users table has a column with the machine name: field_first_name

Code

    $database = Drupal::service('database');

    $select = $database->select('flagging', 'f');
    $select->fields('f', array('uid', 'entity_id'));
    $select->leftJoin('node__field_start_datetime', 'nfds', 'nfds.entity_id = f.entity_id');
    $select->fields('nfds', array('field_start_datetime_value'));
    $select->leftJoin('node_field_data', 'nfd', 'nfd.nid = f.entity_id');
    $select->fields('nfd', array('title'));
    $select->leftJoin('users_field_data', 'ufd', 'ufd.uid = f.uid');
    // TODO extract first name
    $select->fields('ufd', ('mail', 'name', 'field_first_name'));

    $executed = $select->execute();
    $results = $executed->fetchAll(PDO::FETCH_ASSOC);

    $username = $result('name');
    $email = $result('mail');
    $first_name = $result('field_first_name');

Error

DrupalCoreDatabaseDatabaseExceptionWrapper: SQLSTATE(42S22): Column not found: 1054 Unknown column 'ufd.field_first_name' in 'field list': SELECT f.uid AS uid, f.entity_id AS entity_id, nfds.field_start_datetime_value AS field_start_datetime_value, nfd.title AS title, ufd.mail AS mail, ufd.name AS name, ufd.field_first_name AS field_first_name FROM {flagging} f LEFT OUTER JOIN {node__field_start_datetime} nfds ON nfds.entity_id = f.entity_id LEFT OUTER JOIN {node_field_data} nfd ON nfd.nid = f.entity_id LEFT OUTER JOIN {users_field_data} ufd ON ufd.uid = f.uid; Array ( ) in event_notification_cron() (line 63 of /app/modules/custom/event_notification/event_notification.module).