diceline-chartmagnifiermouse-upquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

How to order an ACF repeater field in descending order by key

The problem:

<?php if ( have_rows( 'repeater_field' ) ) while ( have_rows( 'repeater_field' ) ) : the_row(); ?>
    <?php
        $name = get_sub_field( 'name' );
        $age = get_sub_field( 'age' );
    ?>
	
    <p><?php echo $name; ?></p>
    <p><?php echo $age; ?></p>
<?php endwhile; ?>

This only gets you the normal, ascending order for those repeater rows. But what if you need to reverse the order of those rows, making first the last and vice-versa?

The Advanced Custom Fields documentation gives an example, but that didn't work at the time of this writing. They instruct you to use the get_field() function for the main repeater field, but for some reason that returns null on a repeater field.

What I've found to work was to use the get_sub_field() to get the field and the krsort() php method which sorts an array by key in descending order.

<?php
    $repeater = get_sub_field('repeater_field');
    krsort($repeater);
?>
<?php foreach ($repeater as $row): ?>
    <p><?php echo $row['name']; ?></p>
    <p><?php echo $row['age']; ?></p>
<?php endforeach; ?>

One thing to note is that with this method you need to change the way you access those variables.

How use Laravel's Bootable Eloquent Traits

Given the following bootable trait:

trait WithCreator
{
    //no need to define a 'boot' method
    public static function bootWithCreator()
    {
        self::observe(CreatorObserver::class);
    }
}
class CreatorObserver
{
    public function creating($model)
    {
        $model->creator()->associate(auth()->user());
    }
}

We can use it to register the observer without colliding with existing boot methods inside the model.

class Comment extends Model
{
    use HasFactory;
    use WithCreator;
    
    public static function boot()
    {
        ...
    }
}

macOS asks for a PIN instead of a password

Whenever you try to athenticate macOS asks for a PIN instead of a password. This happens if you paired your key at some point with macOS.

Just open Terminal.app and unpair it:

sudo /usr/sbin/sc_auth unpair -u YourUserName

or simply

sudo /usr/sbin/sc_auth unpair

Take out your key if you have it plugged in and reboot.

Your key should be unpaired from your username. Remember you don't have to pair your key to use it. You only have to pair it if you want to use it for macOS authentication.

Regex simplicity vs normal

There are some cases when making use of regular expressions (regex) can exempt a lot of fuss from a programmers head. For example, let's compare the complexity between traditional logic and regex, in a function that excludes the vowels from a given string:

Traditional way:

function removeVowel(str) {
  let strList = str.split('');
  for (let i = 0; i < str.length; i++) {
    let char = str[i].toLowerCase();
    if (char == "a" || char == "e" || char == "i" || char == "o" || char == "u") {
      strList[i] = '';
    }
  }
  return strList.join('');
}

Regex Way:

function removeVowel(str){
  return str.replace( /[aeiou]/ig, '')
}

Temporarily render empty container until image is loaded to the screen

If we have a component that contains an image or video, we may face the case in which the component takes a different size from the one that is expected in the loading phase. This is because, while the image is loading, the size of the image is unknown, therefore the component will not render the image initially. This topic will throw a lot of issues and it can affect the user experience in a negative way, because components may take unnatural shapes while in the loading process.

This problem can be overcome by temporarily rendering:

  • an empty container with the estimated photo dimensions
  • a low resolution preview of the photo
  • a default blurred image that will show the user what to expect from the UI

In the case we want to temporarily render a empty div to the screen, we may need to mimic a responsive feel to the box, therefore "calc()" CSS function may come in handy:

.empty-div {
     background-color: transparent;
     background-size: 100% auto;
     width: calc(100vw - 100px);
     height: calc((100vw - 100px) * 0.46); /* decimal = height aspect ratio */
}

Add event listener on page resize

There is a special event listener in javascript that is called whenever a page resize is detected. The event listener is named 'resize' and can be used in the following way:

function onFrameResize(){
  console.table(
    {
      Height: window.innerHeight,
      Width: window.innerWidth  
    }
  );
}

window.addEventListener("resize", onFrameResize);

"window.innerHeight" and "window.innerWidth" are functions to access the width and the height of the frame.

This functionality will come in handy when working with responsive components.

Call function when image is loaded in VueJS using @load.

In VueJS, there is a way to find out when an image is fully loaded on a web page (when the image request is finished). We achieve this using the @load event that is available in VueJS and works in the following way:

<template>
  <div>
    <img 
      class="img__class"
      src="/photo.jpg"
      @load="onImageLoad"
     />
  </div>
</template>

export default {
  data: {
    isImageLoaded: false,
  },

  methods: {
    onImageLoad() {
      this.isImageLoaded = true
      // optional
      // console.log('Image is loaded')
    }
  }
}

This feature will come in handy if we want to render skeleton components while images are loading or if we want to implement lazy loading functionality.

How to use Makefiles to boost command-line productivity

Makefiles are an awesome tool which can help you become more productive command-line wise by encapsulating long commands and/or sequences of commands. They also help abstract away complexity.

One practical example of creating a make command would be setting up a Laravel project. All you need to do is create a file called Makefile and type in the following.

.PHONY setup
setup: # Setup project
    composer install
    php artisan migrate:fresh --seed
    npm install
    ...

Now, a new developer who needs to setup his/her project can skip writing down that series of commands by simply typing in the following:

make setup

But this doesn't end here. You can create virtually any command to help you automate certain processes such as creating or deleting files, changing permissions etc.