Element_Responses::get_chart_json( awsmug\Torro_Forms\DB_Objects\Forms\Form $form, string $id, array $x_values, array $y_values )

Returns the JSON data to generate the chart.

Description

Parameters

$form

(awsmug\Torro_Forms\DB_Objects\Forms\Form) (Required) Form object.

$id

(string) (Required) ID attribute of the element to bind the chart to.

$x_values

(array) (Required) Values for the 'x' axis.

$y_values

(array) (Required) Values for the 'y' axis. Must match the number of $x_values passed.

Return

(array) JSON data for the chart.

Source

File: src/modules/evaluators/element-responses.php

	protected function get_chart_json( $form, $id, $x_values, $y_values ) {
		$display_mode = $this->get_form_option( $form->id, 'display_mode', 'bar' );

		if ( 'bar' === $display_mode ) {
			$data_point_labels = $this->get_form_option( $form->id, 'data_point_labels', 'none' );

			$less_than_10 = array_reduce( $y_values, function( $carry, $y_value ) {
				if ( $y_value > 10 ) {
					return false;
				}

				return $carry;
			}, true );

			$labels = false;
			if ( 'value' === $data_point_labels ) {
				$labels = true;
			} elseif ( 'percentage' === $data_point_labels ) {
				$aggregate = array_reduce( $y_values, function( $carry, $y_value ) {
					$carry += $y_value;

					return $carry;
				}, 0 );

				$labels = array(
					'format' => array(
						'template'  => '%percentage%%',
						'aggregate' => $aggregate,
					),
				);
			}

			array_unshift( $x_values, 'x' );
			array_unshift( $y_values, 'responseCount' );

			$data = array(
				'bindto' => '#' . $id,
				'data'   => array(
					'x'       => 'x',
					'columns' => array( $x_values, $y_values ),
					'names'   => array(
						'responseCount' => __( 'Response Count', 'torro-forms' ),
					),
					'type'    => $display_mode,
					'labels'  => $labels,
				),
				'axis'   => array(
					'x' => array(
						'type' => 'category',
					),
					'y' => array(
						'min'   => 1,
					),
				),
				'legend' => array(
					'show' => false,
				),
			);

			if ( $less_than_10 ) {
				$data['axis']['y']['max'] = 10;
			}

			return $data;
		}

		$data = array(
			'bindto' => '#' . $id,
			'data'   => array(
				'columns' => array(),
				'names'   => array(),
				'type'    => $display_mode,
			),
		);

		foreach ( $x_values as $index => $x_value ) {
			if ( ! isset( $y_values[ $index ] ) ) {
				continue;
			}

			$data['data']['columns'][] = array( 'data' . ( $index + 1 ), $y_values[ $index ] );
			$data['data']['names'][ 'data' . ( $index + 1 ) ] = $x_value;
		}

		return $data;
	}

Changelog

Changelog
Version Description
1.0.0 Introduced.