Make woocommerce checkout fields optional - woocommerce

I have already followed the method to make the checkout fields optional with the codes below. However, I found that the alert to fill in address field jumped out when the non-login user submit the order.
add_filter( 'woocommerce_default_address_fields' , 'custom_override_default_address_fields' );
function custom_override_default_address_fields($address_fields) {
$address_fields['first_name']['required'] = false;
$address_fields['last_name']['required'] = false;
$address_fields['address_1']['required'] = false;
$address_fields['address_1']['placeholder'] = '';
$address_fields['address_2']['required'] = false;
$address_fields['address_2']['placeholder'] = '';
$address_fields['postcode']['required'] = false;
$address_fields['city']['required'] = false;
return $address_fields;
}
By the way, I also tried to make the billing and shipping fields optional separately as the method in the link WooCommerce: Disabling checkout fields with a filter hook.

Depending on which checkout fields you would like to make optional (or required), there are two filters that you will need to hook into. The first filter is woocommerce_default_address_fields and is for the address fields, the second is woocommerce_billing_fields and is for the billing_phone and billing_email fields.
add_filter( 'woocommerce_default_address_fields', 'adjust_requirement_of_checkout_address_fields' );
function adjust_requirement_of_checkout_address_fields( $fields ) {
$fields['first_name']['required'] = false;
$fields['last_name']['required'] = false;
$fields['company']['required'] = false;
$fields['country']['required'] = false;
$fields['address_1']['required'] = false;
$fields['address_2']['required'] = false;
$fields['city']['required'] = false;
$fields['state']['required'] = false;
$fields['postcode']['required'] = false;
return $fields;
}
add_filter( 'woocommerce_billing_fields', 'adjust_requirement_of_checkout_contact_fields');
function adjust_requirement_of_checkout_contact_fields( $fields ) {
$fields['billing_phone']['required'] = false;
$fields['billing_email']['required'] = false;
return $fields;
}

go to this thread Make checkout fields required in Woocommerce checkout and change true to false for the fields you don't need to be required
ex : change $address_fields['postcode']['required'] = true;
to $address_fields['postcode']['required'] = false;

Related

Ajax and hook_form_alter

I'm getting a "The value you selected is not a valid choice." error for an Ajax modified field when I submit a custom altered node/add form. An "Illegal choice error is also written to the log. This a Drupal 9 version of an app that I developed using Drupal 7 which worked. The Ajax functionality is working. Why? How do I fix it?
I believe the error is coming from some Symfony code. I'm dynamically modifying two "select" form elements. The first doesn't appear to have the problem. I'm doing the same thing for both form elements.
function bncreports_form_node_bnc_message_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
$form['actions']['submit']['#submit'][] = 'bncreports_node_bnc_message_form_submit';
$form['#title'] = t('Create Contact Us');
$user = User::load(\Drupal::currentUser()->id());
$district_id = $user->get('field_district')->value;
$form['field_first_name']['widget'][0]['value']['#default_value'] = $user->get('field_first_name')->value;
$form['field_last_name']['widget'][0]['value']['#default_value'] = $user->get('field_last_name')->value;
$form['field_email']['widget'][0]['value']['#default_value'] = $user->getEmail();
$form['field_email']['widget'][0]['value']['#attributes'] = ['onblur' => 'this.value=this.value.toLowerCase();'];
$form['field_phone']['widget'][0]['value']['#default_value'] = $user->get('field_phone')->value;
$form['field_district']['widget'][0]['value']['#default_value'] = $district_id;
if (isset($form['field_district']['widget']['#default_value']))
$form['field_district']['widget']['#default_value'] = $district_id; // wtf?
if ($user->hasRole('administrator') || $user->hasRole('bnc_operator') || $user->hasRole('ao_user')) {
$form['field_office']['#access'] = false;
$form['field_office_name']['#access'] = false;
$form['field_office_names']['#access'] = false;
$form['field_site_codes']['#access'] = false;
$form['field_district']['widget']['#ajax'] = [
'event' => 'change',
'callback' => 'bncreports_ajax_offices_and_user',
'wrapper' => ['ajax-wrapper-field-offices', 'ajax-wrapper-field-user'],
];
$form['field_offices']['#prefix'] = '<div id="ajax-wrapper-field-offices">';
$form['field_offices']['#suffix'] = '</div>';
$form['field_user']['#prefix'] = '<div id="ajax-wrapper-field-user">';
$form['field_user']['#suffix'] = '</div>';
$district_id = $form_state->hasValue('field_district')
? $form_state->getValue('field_district')[0]['value']
: false;
$form['field_offices']['widget']['#options'] = $district_id
? Functions::officeNames($district_id)
: [];
$form['field_user']['widget']['#options'] = $district_id
? ['_none' => '- Select a value -'] + Functions::districtUserLastandFirstNames($district_id)
: ['_none' => '- Select a value -'];
} else { // Alterations for court users only
$form['bnc_prefix']['#markup'] =
'<p>BNC User Support: ' . Constants::BNC_PHONE_NO
. ' ' . Constants::BNC_EMAIL . '</p>'
. '<p>AO Program and CM/ECF Contacts</p>'
. '<h4>Unable to find what you need? Send us a message.</h4>';
$form['bnc_prefix']['#weight'] = -1;
$form['field_offices']['#access'] = false;
$form['field_office_name']['#access'] = false;
$form['field_office_names']['#access'] = false;
$form['field_site_codes']['#access'] = false;
$form['field_user']['#access'] = false;
$form['field_non_user_name']['#access'] = false;
$form['field_non_user_phone']['#access'] = false;
$form['field_assigned_to']['#access'] = false;
$form['revision_information']['#access'] = false;
$office = $user->get('field_office')->value;
$form['field_district']['widget']['#default_value'] = $district_id;
$form['field_office']['widget']['#options'] = Functions::officeNames($district_id);
$form['field_office']['widget']['#default_value'] = $office;
$form['field_office_name']['widget'][0]['value']['#default_value'] = Functions::officeName($district_id, $office);
$form['#attached']['library'][] = 'bncreports/restricted_contact_log';
}
}
function bncreports_ajax_offices_and_user(array $form, FormStateInterface $form_state): AjaxResponse
{
$response = new AjaxResponse();
// Issue a command that replaces the elements 'field_offices' and 'field_user'
$response->addCommand(new ReplaceCommand('#ajax-wrapper-field-office', $form['field_offices']));
$response->addCommand(new ReplaceCommand('#ajax-wrapper-field-user', $form['field_user']));
return $response;
}
Problem is there are no allowed values for the field_user list. Solution is to use an allowed values function callback. This is done in Configuration synchronization for Field Storage. Set the allowed value function property and import. Need to provide uuid to override existing config.
In my hook_form_alter:
$_SESSION['selected_district_id'] = $district_id;
In my xxx.module:
function bncreports_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable): array
{
// NOTE: This is defined in Configuation synchronization for Field Storage (see node.field_user)
if ($entity->bundle() == 'bnc_message') { // Add a custom field_user options for BNC Message nodes.
$district_id = $_SESSION['selected_district_id'] ?? null;
return Functions::districtUserLastandFirstNames($district_id);
}
throw new Exception("Allowed values function for {$entity->bundle()} is not allowed.");
}

404 cehck status for current page

i want to check current page's 404 status in a plugin file
i tried this but page only spinning and never finish loading
public static function check_404_status($my_url)
{
$result = false;
$my_url = self::tc_trim_slash($my_url);
$ch = curl_init($my_url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($retcode != 200) {
$result=true;
return $result;
}
else {
// echo "Specified URL exists";
}
curl_close($ch);
}
i have also tried this but it gives error
is_404 was called incorrectly. Conditional query tags do not work before the query is run. Before then, they always return false. Please see Debugging in WordPress for more information. (This message was added in version 3.1.)
public static function check_404_status($my_url)
{
$result = false;
$my_url = self::tc_trim_slash($my_url);
if(is_404())
{
$result=true;
return $result;
}
}
I am new to wordpress, can someone please help me to solve this??
is_404() conditional is set in the WP_Query class and checks is the query returns a 404 (returns no results)
So, you can try to modify your function like that
public static function check_404_status()
{
global $wp_query;
if (isset($wp_query)) {
return $wp_query->is_404();
}
return false;
}

Doctrine not getting newly added record

I have a function that does 2 things.
Saves an existing or a new item/record
Query and re-order items
The code algorithm is like this
public function doSomething($id = 0)
{
$em = $this->getEntityManagerFromSomewhere();
$service = $this->getSomeServiceFromSomewhere();
$repo = $em->getRepository(Item::class);
$conn = $em->getConnection();
$conn->beginTransaction();
if ($id) {
$item = new Item();
} else {
$item = $repo->find($id);
}
$em->persist($item);
$em->flush();
$items = $repo->getAllItems();
// changes are saved to the database
$service->rearrangeItems($items);
$conn->commit();
}
Now the issue I'm having with this is that, if it is a new Item, when we try to get all items, that new item is not included for some odd reason.
I've tried stuff on my own and the one that works for me is to insert
$em->clear(); // after flush
I am not sure if this is the best way to approach this or if I'm misusing this functionality. It works though, when I tested it.
public function doSomething($id = 0)
There is $id is default 0, Actually, your are creating item every time.
if ($id) {
$item = new Item();
$em->persist($item);
} else {
$item = $repo->find($id);
}
also, you don't need to persist if you don't update or create new Item.
Or the way that I understood.
if($id)
{
$item = $em->getRepository(Item::class)->find($id)
}
else
{
$item = new Item();
$em->persist($item);
}
$em->flush();

Change password using custom controller - FOSUserBundle (without FormBuilder)

I am implementing my own profile settings page. This will allow the user to change their name, email, password etc.
I understand FOSUserBundle has prebuilt /profile/edit and /profile/change-password. I would like to use the same functionality here except in my own twig bundles. I am not using FormBuilder.
This is my controller for changing user settings.
public function applySettings(Request $request)
{
$user = $this->getUser();
$dm = $this->get('doctrine_mongodb')->getManager();
$repository = $dm->getRepository('AppBundle:User');
$name = $request->get('_username');
$email = $request->get('_email');
$password = $request->get('_password');
$confirm = $request->get('_confirm');
if ($name != null) {
if ($name == ($repository->findOneBy(array('username' => $name )))) {
throw $this->createNotFoundException('Username already in use');
} else {
// username changed
$user->setUsername($name);
}
}
if ($email != null) {
if ($email == ($repository->findOneBy(array('email' => $email )))) {
throw $this->createNotFoundException('Email already in use');
} else {
// email changed
$user->setEmail($email);
}
}
if (strcmp($password, $confirm) == 0) {
// password = confirm here
// change password functionality done here
} else {
throw $this->createNotFoundException(
'Passwords do not match '
);
}
$dm->flush();
return $this->redirectToRoute('settings');
}
Is there a way I can do password validation in my own controller, salt and store the password if valid?
Also is there a way to apply the same validation methods that exist in /register/ and /profile/change-password where the alert comes up if the passwords do not match before submitting?
Any help would be greatly appreciated.
I am using Symfony 2.6.1 and the latest version of FOSUserBundle.
This is the function I used. Works but doesn't do the live validation check.
if (strcmp($password, $confirm) == 0) {
$encoder_service = $this->get('security.encoder_factory');
$encoder = $encoder_service->getEncoder($user);
$newpass = $encoder->encodePassword($password, $user->getSalt());
$user->setPassword($newpass);
} else {
throw $this->createNotFoundException(
'Passwords do not match '
);
}

Drupal - Block visibility

I am using the below code in the block visibilty settings, to only show the block if the user is a member, and not the admin.
What can I add to further filter it down to type of Organic Group Node.
i.o.w Only display if the currnt group being viewed = Organic Group Node Type X
<?php
$in_og = FALSE;
if (module_exists('og')){
$in_og = FALSE;
$group_node = og_get_group_context();
$gid02 = $group_node->nid;
$gid = (int)$gid02;
if ($gid02 == null) $gid = 0;
if (og_is_group_member($group_node)) $in_og = TRUE;
if (og_is_group_admin($group_node)) $in_og = FALSE;
if ($gid == 0) $in_og = FALSE;
}
return $in_og;
thanks
Maybe something like"
<?php
$in_og = FALSE;
$right_group = FALSE;
if (module_exists('og')) {
// get OG $group_node
$group_node = og_get_group_context();
if ($group_node->type == 'type-x') {
// we have the correct group type
$right_group = TRUE;
}
$gid = $group_node->nid;
if (og_is_group_member($group_node)) {
// show to members
$in_og = TRUE;
}
if (og_is_group_admin($group_node)) {
// hide from admins
$in_og = FALSE;
}
}
return $in_og && $right_group;
?>

Resources