Support

Account

Home Forums General Issues Hide one field and save calculated data to it.

Solving

Hide one field and save calculated data to it.

  • I have a field group with 3 fields; cars, miles and total_miles. I need to produce a frontend form with only the cars and miles fields viewable (total_miles needs to be hidden.

    Once the form is submitted I want to cars * miles and save that value to the hidden total_miles field and save it to the DB.

    Something similar to this:

    <?php
    if(!isset($_GET['updated'])){
    			acf_form(array(
    				'id' => 'Mixed-Mode',
    				'post_id'		=> 'new_post',
    				'field_groups'	=> array(698),
    				'new_post'		=> array(
    					'post_type'		=> 'mixed_mode',
    					'post_status'	=> 'publish'),
    				'submit_value'		=> 'Submit',
    			));
    
    $miles = get_field(‘miles’,698);
    $cars = get_field(‘cars’,698);
    $Total_miles = get_field(‘total_miles’,698); // This field I want to hide
    
    // I want to take this value and save it to get_field(‘total_miles’,698);
    $total = $cars * $miles;
    
    // Once the calculation is complete, display the total
    if(isset($total_miles)) {
        echo $miles.' * '.$cars.' = '.$total_miles;
    
    }
    ?>

    Is there an easy way to do this?

  • Hi @signalwarrant

    I don’t think saving the total to the database is a good thing to do. It can add loads to your database and make your site slow. Instead, you can create a function to calculate it like this:

    function totalMiles( $post_id ){
        $miles = get_field('miles', $post_id);
        $cars = get_field('cars', $post_id);
        
        return $cars * $miles;
    }

    Then you can use it like this:

    echo totalMiles(698);

    If you still want to save it to the database, you need to do it with the acf/save_post hook and the update_field() function.

    I hope this makes sense 🙂

  • So you think looping through hundreds of posts to get the total for all posts everytime a specific page is loaded is more efficient than pulling that data out of the DB?

    I’m asking because I have no idea.

  • Hi @signalwarrant

    If you want to calculate the total for each post, then calculating it using PHP code would be more efficient. But, if you want to calculate the total from all posts (e.g. the sum of the totals) and show it in a specific post/page, then saving it to the database would be better.

    I hope this helps 🙂

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Hide one field and save calculated data to it.’ is closed to new replies.