Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: minor
Type: added

Forms: add reusable forms list to dashboard.
Comment thread
edanzer marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,144 @@

namespace Automattic\Jetpack\Forms\ContactForm;

use WP_REST_Request;

/**
* REST endpoint for the jetpack_form custom post type.
*/
class Jetpack_Form_Endpoint extends \WP_REST_Posts_Controller {
/**
* Cached map of form_id => entries count for the current request.
*
* @var array<int,int>|null
*/
private $entries_count_by_form_id = null;

/**
* Constructor.
*/
public function __construct() {
parent::__construct( Contact_Form::POST_TYPE );
}

/**
* Add opt-in dashboard fields.
*
* @return array
*/
public function get_collection_params() {
$params = parent::get_collection_params();

// Note: We do not use the built-in WP REST "context" param for this, because it's validated
// against core values (view/embed/edit). This param is for Jetpack Forms dashboard usage only.
$params['jetpack_forms_context'] = array(
'description' => __( 'Request context for Jetpack Forms. Use "dashboard" to include dashboard-only fields.', 'jetpack-forms' ),
'type' => 'string',
'default' => '',
'enum' => array( '', 'dashboard' ),
'sanitize_callback' => 'sanitize_key',
);

return $params;
}

/**
* Return a collection of forms.
*
* We override this to compute dashboard aggregate fields in a single pass.
*
* @param WP_REST_Request $request Full details about the request.
* @return \WP_REST_Response|\WP_Error
*/
public function get_items( $request ) {
$response = parent::get_items( $request );

if ( is_wp_error( $response ) ) {
return $response;
}

$forms_context = (string) $request->get_param( 'jetpack_forms_context' );
if ( 'dashboard' !== $forms_context ) {
return $response;
}

$forms = $response->get_data();
if ( ! is_array( $forms ) || empty( $forms ) ) {
return $response;
}

$form_ids = array();
foreach ( $forms as $form ) {
if ( isset( $form['id'] ) ) {
$form_ids[] = (int) $form['id'];
}
}
$form_ids = array_values( array_unique( array_filter( $form_ids ) ) );

$this->entries_count_by_form_id = $this->get_entries_count_by_form_id( $form_ids );

foreach ( $forms as &$form ) {
$form_id = isset( $form['id'] ) ? (int) $form['id'] : 0;
$form['entries_count'] = (int) ( $this->entries_count_by_form_id[ $form_id ] ?? 0 );
if ( $form_id ) {
$form['edit_url'] = get_edit_post_link( $form_id, 'raw' );
}
}

$response->set_data( $forms );
return $response;
}

/**
* Batch compute feedback counts for a list of form IDs.
*
* @param int[] $form_ids Form IDs to count entries for.
* @return array<int,int> Map of form_id => count
*/
private function get_entries_count_by_form_id( array $form_ids ): array {
global $wpdb;

$form_ids = array_values( array_unique( array_map( 'absint', $form_ids ) ) );
if ( empty( $form_ids ) ) {
return array();
}

// Count only "inbox-visible" feedback statuses.
// Note: This is about feedback (response) statuses, not form post statuses (publish/draft/pending/future/private).
$statuses = array( 'publish', 'draft' );
Comment thread
edanzer marked this conversation as resolved.
Resolved
Comment thread
edanzer marked this conversation as resolved.
Resolved

// Cache the grouped counts briefly to avoid repeated DB hits (e.g. on reload / concurrent requests).
sort( $form_ids );
$cache_key = 'feedback_counts_' . md5( implode( ',', $form_ids ) . '|' . implode( ',', $statuses ) );
$cache_group = 'jetpack_forms';
$cached = wp_cache_get( $cache_key, $cache_group );
if ( false !== $cached && is_array( $cached ) ) {
return $cached;
}

$args = array_merge( array( Feedback::POST_TYPE ), $form_ids, $statuses );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel like this is kind of hard to read and follow.
Can we do without it? $args just passing in array( Feedback::POST_TYPE , $form_ids, $statuses )
instead to $wpdb->prepare(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree hard to read. But I don't think we can do the change you're suggesting - it would change the data structure from flat to nested arrays. That said, this is not my strong suite, and I'm getting AI help with this. After some back and forth, I had my AI try to summarize the issue. You can let me know if you know better :).


$wpdb->prepare( $query, $args ) does not “expand” arrays to fill multiple placeholders.

So if $args is: array( Feedback::POST_TYPE, $form_ids, $statuses )

then from prepare()’s perspective you supplied 3 replacement values total:

  • a string (Feedback::POST_TYPE)
  • an array ($form_ids)
  • an array ($statuses)

But the SQL has many placeholders:

  • %s for post_type (1)
  • one %d per form id (N)
  • one %s per status (M)

prepare() expects 1 + N + M scalar values (string/int), in order. It can’t match an “array value” to “a list of %d placeholders” — it won’t iterate and substitute each element. Best case you get warnings / wrong SQL; worst case you get a broken query or the placeholders don’t get safely substituted.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the explanation Erick.

I think what you have works well.

One thing that I think would help here is still remobing the $args variable.
and just doing

$wpdb->prepare( 
   "SELECT...', 
   array_merge( array( Feedback::POST_TYPE ), $form_ids, $statuses );

instead.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@enej - I think that's still the same thing and presents the same concerns?


// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT post_parent, COUNT(1) AS entry_count
FROM {$wpdb->posts}
WHERE post_type = %s
AND post_parent IN (" . implode( ',', array_fill( 0, count( $form_ids ), '%d' ) ) . ')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure if that is the best way to do this. I think it can be simplified a lot. by just passing in a string in here instead.

@edanzer edanzer Jan 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - Needed to think this through more. I see what you're asking. Again running SQL queries is not my strong suit, so lots of back and forth with AI to try to understand what's needed here.

My current understanding is that prepare() only safely substitutes values into placeholders (%d, %s, etc.). So we could just add as string there, and the query will likely run, but prepare() isn’t protecting that part, PHPCS will complain, and (maybe) it is easier to introduce bugs/injection.

That said, if you want to go straight string route, I can try to update that.

AND post_status IN (' . implode( ',', array_fill( 0, count( $statuses ), '%s' ) ) . ')
GROUP BY post_parent',
$args
)
);
Comment thread
edanzer marked this conversation as resolved.
Resolved
$counts_by_form_id = array();
foreach ( (array) $rows as $row ) {
$counts_by_form_id[ (int) $row->post_parent ] = (int) $row->entry_count;
}

wp_cache_set( $cache_key, $counts_by_form_id, $cache_group, 15 ); // 15 seconds.
return $counts_by_form_id;
}

/**
* Checks if a given request has access to get items.
*
Expand Down
24 changes: 23 additions & 1 deletion projects/packages/forms/src/dashboard/class-dashboard.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,29 @@ public function load_admin_scripts() {
$initial_responses_path,
$initial_responses_locale_path,
);
$preload_data_raw = array_reduce( $preload_paths, 'rest_preload_api_request', array() );

// Only preload the Forms list endpoint when centralized form management is enabled.
if ( Contact_Form_Plugin::has_editor_feature_flag( 'central-form-management' ) ) {
$forms_preload_params = array(
'context' => 'edit',
'page' => 1,
'jetpack_forms_context' => 'dashboard',
'order' => 'desc',
'orderby' => 'modified',
'per_page' => 20,
'status' => 'publish,draft,pending,future,private',
);
ksort( $forms_preload_params );
$preload_paths[] = add_query_arg( $forms_preload_params, '/wp/v2/jetpack-forms' );
$preload_paths[] = add_query_arg(
array_merge(
$forms_preload_params,
array( '_locale' => 'user' )
),
'/wp/v2/jetpack-forms'
);
}
$preload_data_raw = array_reduce( $preload_paths, 'rest_preload_api_request', array() );

// Normalize keys to match what apiFetch will request (without domain).
$preload_data = array();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ const useInstallAkismet = (): UseInstallAkismetReturn => {
};
};

const EmptyWrapper = ( { heading = '', body = '', actions = null }: EmptyWrapperProps ) => (
export const EmptyWrapper = ( { heading = '', body = '', actions = null }: EmptyWrapperProps ) => (
<VStack alignment="center" spacing="2">
{ heading && (
<Text as="h3" weight="500" size="15">
Expand Down
165 changes: 155 additions & 10 deletions projects/packages/forms/src/dashboard/forms/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,139 @@
* External dependencies
*/
import { JetpackLogo } from '@automattic/jetpack-components';
import { useEffect } from '@wordpress/element';
import { DataViews } from '@wordpress/dataviews/wp';
import { dateI18n, getSettings as getDateSettings } from '@wordpress/date';
import { useCallback, useEffect, useMemo } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { useNavigate } from 'react-router';
/**
* Internal dependencies
*/
import useConfigValue from '../../hooks/use-config-value.ts';
import CreateFormButton from '../components/create-form-button/index.tsx';
import { EmptyWrapper } from '../components/empty-responses/index.tsx';
import FormsResponsesTabs from '../components/forms-responses-tabs/index.tsx';
import Page from '../components/page/index.tsx';
import useFormsData from '../hooks/use-forms-data.ts';
import { defaultLayouts, useView } from './views.ts';
import './style.scss';
import type { FormListItem } from '../hooks/use-forms-data.ts';

/**
* Forms dashboard "Forms" route placeholder.
* Forms dashboard "Forms" route.
*
* @return {JSX.Element|null} The placeholder page, or null when redirecting.
* @return {JSX.Element|null} The Forms list page, or null when redirecting.
*/
export default function FormsDashboardForms(): JSX.Element | null {
const navigate = useNavigate();
const isCentralFormManagementEnabled = useConfigValue( 'isCentralFormManagementEnabled' );
const isCentralFormManagementDisabled = isCentralFormManagementEnabled === false;

const dateSettings = getDateSettings();
const [ view, setView ] = useView();
const { records, isLoading, totalItems, totalPages } = useFormsData(
view.page,
view.perPage,
view.search
);

useEffect( () => {
if ( isCentralFormManagementEnabled === false ) {
if ( isCentralFormManagementDisabled ) {
navigate( '/responses', { replace: true } );
}
}, [ isCentralFormManagementEnabled, navigate ] );
}, [ isCentralFormManagementDisabled, navigate ] );

const statusLabel = useCallback( ( status: string ) => {
switch ( status ) {
case 'publish':
return __( 'Published', 'jetpack-forms' );
case 'draft':
return __( 'Draft', 'jetpack-forms' );
case 'pending':
return __( 'Pending review', 'jetpack-forms' );
case 'future':
return __( 'Scheduled', 'jetpack-forms' );
case 'private':
return __( 'Private', 'jetpack-forms' );
default:
return status;
}
}, [] );

const fields = useMemo(
() => [
{
id: 'title',
label: __( 'Form name', 'jetpack-forms' ),
getValue: ( { item }: { item: FormListItem } ) => item.title,
render: ( { item }: { item: FormListItem } ) =>
item.title || __( '(no title)', 'jetpack-forms' ),
enableSorting: false,
enableHiding: false,
},
{
id: 'entries',
label: __( 'Entries', 'jetpack-forms' ),
getValue: ( { item }: { item: FormListItem } ) => item.entriesCount ?? 0,
render: ( { item }: { item: FormListItem } ) => item.entriesCount ?? 0,
enableSorting: false,
},
{
id: 'status',
label: __( 'Status', 'jetpack-forms' ),
getValue: ( { item }: { item: FormListItem } ) => item.status,
render: ( { item }: { item: FormListItem } ) => statusLabel( item.status ),
enableSorting: false,
},
{
id: 'modified',
label: __( 'Last updated', 'jetpack-forms' ),
type: 'date' as const,
render: ( { item }: { item: FormListItem } ) =>
dateI18n( dateSettings.formats.datetime, item.modified ),
enableSorting: false,
Comment thread
edanzer marked this conversation as resolved.
Resolved
},
],
[ dateSettings.formats.datetime, statusLabel ]
);

const actions = useMemo(
() => [
{
id: 'edit-form',
isPrimary: false,
label: __( 'Edit', 'jetpack-forms' ),
supportsBulk: false,
async callback( items: FormListItem[] ) {
const [ item ] = items;
if ( ! item ) {
return;
}
const fallbackEditUrl = `post.php?post=${ item.id }&action=edit&post_type=jetpack_form`;
const editUrl = item.editUrl || fallbackEditUrl;
const url = new URL( editUrl, window.location.origin );
window.location.href = url.toString();
Comment thread
edanzer marked this conversation as resolved.
Resolved
},
Comment thread
edanzer marked this conversation as resolved.
Resolved
},
],
[]
);

const paginationInfo = useMemo(
() => ( {
totalItems: totalItems ?? 0,
totalPages: totalPages ?? 0,
} ),
[ totalItems, totalPages ]
);

const onChangeView = useCallback( newView => setView( newView ), [ setView ] );
Comment thread
edanzer marked this conversation as resolved.
Resolved

// Avoid rendering the placeholder if the flag is off (we'll redirect).
if ( isCentralFormManagementEnabled === false ) {
const headerActions = useMemo( () => [ <CreateFormButton key="create" /> ], [] );
const getItemId = useCallback( ( item: FormListItem ) => String( item.id ), [] );

// Avoid rendering if the flag is off (we'll redirect).
if ( isCentralFormManagementDisabled ) {
return null;
}

Expand All @@ -43,11 +149,50 @@ export default function FormsDashboardForms(): JSX.Element | null {
}
subTitle={ __( 'View and manage all your forms in one place.', 'jetpack-forms' ) }
tabs={ <FormsResponsesTabs /> }
actions={ headerActions }
hasPadding={ false }
>
<p style={ { fontWeight: 'bold', margin: '20px' } }>
{ __( 'Forms will appear here', 'jetpack-forms' ) }
</p>
<DataViews
paginationInfo={ paginationInfo }
fields={ fields }
actions={ actions }
data={ records || [] }
isLoading={ isLoading }
empty={
Comment thread
edanzer marked this conversation as resolved.
Resolved
<EmptyWrapper
heading={ __( "You're set up. No forms yet.", 'jetpack-forms' ) }
body={ __(
'Create a shared form pattern to manage and reuse it across your site.',
'jetpack-forms'
) }
actions={
<CreateFormButton
label={ __( 'Create a new form', 'jetpack-forms' ) }
variant="primary"
/>
}
/>
}
view={ view }
onChangeView={ onChangeView }
getItemId={ getItemId }
defaultLayouts={ defaultLayouts }
>
<div className="jp-forms-filters-bar">
<div className="jp-forms-filters-bar__chips">
<DataViews.FiltersToggled className="jp-forms-filters-container" />
</div>
<div className="jp-forms-filters-bar__controls">
<DataViews.Search />
<DataViews.FiltersToggle />
<DataViews.ViewConfig />
</div>
</div>
<div className="jp-forms-dataviews-layout-container">
<DataViews.Layout />
<DataViews.Footer />
</div>
</DataViews>
</Page>
</div>
);
Expand Down
Loading
Loading