Okay, now I’m getting somewhere. I’m very pleased with the progress I’m making, though I haven’t quite figured out how to get change health I’m close!
Here’s my deal: I want to populate a list with characters to hit. I create a query to only show the category for “alive” (since those are the characters to attack or heal).
add_filter( 'gform_pre_render_2', 'populate_posts' );
add_filter( 'gform_pre_validation_2', 'populate_posts' );
add_filter( 'gform_pre_submission_filter_2', 'populate_posts' );
add_filter( 'gform_admin_pre_render_2', 'populate_posts' );
function populate_posts( $form ) {
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-posts' ) === false ) {
continue;
}
// you can add additional parameters here to alter the posts that are retrieved
// more info: http://codex.wordpress.org/Template_Tags/get_posts
$posts = get_posts( 'numberposts=-1&post_status=publish&post_type=character&cat=2' );
$choices = array();
foreach ( $posts as $post ) {
$choices[] = array( 'text' => $post->post_title . " HP:" . $post->health, 'value' => $post->ID );
}
// update 'Select a Post' to whatever you'd like the instructive option to be
$field->placeholder = 'Select a Character';
$field->choices = $choices;
}
return $form;
}
Having a difficult time taking a screen shot of the results, but it list their name and their current HP; very cool! It also gives us the post_ID of the character chosen as a value, which I want to use later.
add_action( 'gform_after_submission_2', 'set_post_content', 10, 2 );
function set_post_content( $entry, $form ) {
//getting post
$post = get_post( maybe_unserialize( rgar( $entry, '3') ) );
//changing post content
$post->post_content = 'success: ' . maybe_unserialize( rgar( $entry, '3') );
//updating post
wp_update_post( $post );
}
This was tough to figure out, but now I know what get_post
, maybe_unserialize
, rgar
, and wp_update_post
do now…
This was a tough nut to crack, because I missed this from the docs (Entry Object - Gravity Forms Documentation):
List Field
The List field type due to its complex setup compared to other field types (it has many rows and columns of data) it’s stored in serialized format, so you need to unserialize it first to access the data.
maybe_unserialize( rgar(
$entry
,
'3'
) );
// unserialize values associated with list field 3
And of course it works! Currently, it just changed the post_content
to read “success:” and the post ID.
So I think I can include all the math in this function, and just use the form to collect the IDs of both characters. I’ll generate a number, and depending on “attack” or “heal” I’ll apply the number to the targets current health, and save it to the character. Then I’ll add in checks for 0 or 1,000+ health. 