ACF acf_form on admin page works, but when it is loaded in via ajax it breaks - advanced-custom-fields

I'm using acf_form() to embed a form in a metabox on the admin page using this code (simplified):
$submitted_user_id = 'user_3';
$form_settings = array(
'fields' => ['field_625008b509dca'],
'form_attributes' => array(
'method' => 'POST',
'action' => admin_url("admin-post.php"),
),
'post_id' => $submitted_user_id,
);
acf_form( $form_settings );
..and calling the requisite acf_form_head() in admin_init as such:
function append_acf_form_head() {
acf_form_head();
}
add_action( 'admin_init', 'append_acf_form_head', 1 );
This works fine, and updates the values on submit. However I want to pull this form in via ajax, in order to pass the user_id from a select filter above.
The ajax is also working perfectly, and pulling in the form with the passed user_id, however on submission the form does not save the data, and redirects to 'wp-admin/admin-post.php'.
This is the php code for the ajax functionality in functions.php:
add_action( 'wp_ajax_test_action', 'test_action' );
function test_action() {
// Same acf_form() function as above
wp_die()
}
And finally the JS:
$('button#support-ticket-user-filter').on('click', function(e) {
e.preventDefault();
var data = {
'action': 'test_action',
'user_id': $('select#get_user_id').val()
};
$.post(ajaxurl, data, function(response) {
$('#listings-result').append( response );
});
});
Any ideas why it would work perfectly in the first case, but not in the second? Perhaps it's related to the ajaxurl?
Many thanks!

For anyone looking for the solution; I've found a slightly hacky approach which does the trick for now. The ACF Support team mentioned this wasn't out the box functionality but has now been included as a feature request. For those trying to achieve this the trick is to permanently embed a 'dummy form' which loads the necessary stuff to make it all work - then kind of hook this into the form pulled in via ajax:
So, in the meta box a permanent dummy form is embedded:
// This dummy form is required to load all the acf stuff for the ajax version
$dummy_form_settings = array(
// Do not declare any fields
'post_id' => $submitted_user_id, // Make sure the ID corresponds ( for users in my case )
'form' => true,
);
acf_form( $dummy_form_settings );
All we want from this dummy form is the 'update' button - which is the one that actually works, as opposed to the one in the form pulled in via ajax. So that function will remove the submit button like this:
$form_settings = array(
'fields' => ['field_625008b509dca'],
'form_attributes' => array(
'method' => 'POST',
),
'html_before_fields' => sprintf(
'<input type="hidden" name="user_id" value="' . $submitted_user_id . '">',
),
'post_id' => $submitted_user_id,
'form' => true,
'html_submit_button' => '', // The important bit
);
acf_form( $form_settings );
wp_die();
Now your essentially left with a single form that submits properly.

Related

Saving data to the join table using control options in CakePHP 3.x

I learned here how one can save the data to the fields of join table CoursesMemberships while adding or editing a student in CakePHP 3.x. In order to add grades for many courses I can do this in my add and edit forms:
echo $this->Form->control('courses.0.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.0._joinData.grade');
echo $this->Form->control('courses.1.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.1._joinData.grade');
echo $this->Form->control('courses.2.id', ['type' => 'select', 'options' => $courses]);
echo $this->Form->control('courses.2._joinData.grade');
...
but this form:
has a fixed number of courses for each student;
requires to select the course id from the list ('type' => 'select');
adds all courses to the student record even if not attended (well, the corresponding grade field can be kept empty, but still).
Is there a way to have a simpler form, where all courses are listed and one can only checkbox the course attended and enter the corresponding grade? I found it very challenging using control...
EDIT:
After #ndm suggested a very nice method below, I implemented it in the add.ctp:
foreach ($courses as $key => $course) {
echo $this->Form->control('courses.'.$key.'.id', ['type' => 'checkbox', 'hiddenField' => false, 'value' => $key,
'label' => $key]);
echo $this->Form->control('courses.'.$key.'._joinData.grades');
}
and corrected StudentsTable.php accordingly. And it runs with no problems.
However, if I do the same in edit.ctp, the previously saved records (e.g. for 1, 3, 5 and 7 courses are now listed as 1, 2 and 3 showing the grades for former 3rd 5th and 7th courses and the form forces me to check those three boxes. I understand that the first record disappeared because my courses start with id=1 (and so does the $key in the loop) and 'courses.0.id' is thus missing, but the general problem is that the empty fields removed by beforeMarshal function are no longer recognized in edit.ctp form and I cannot find a reasonable way to edit the student's record.
There is no build in support for what you are trying to achieve, you'll have to come up with a custom solution, which will likely either require a mixture of form and marshalling logic, or JavaScript.
You could create for example a list of checkboxes, and use the id value (wich will be zero in case the checkbox isn't checked, or the ID in case it is checked) to remove unchecked entries from the submitted data before marshalling, something like this:
echo $this->Form->control('courses.0.id', [
'type' => 'checkbox',
'value' => $courses[0]->id,
'label' => $courses[0]->title
]);
echo $this->Form->control('courses.0._joinData.grade');
echo $this->Form->control('courses.1.id', [
'type' => 'checkbox',
'value' => $courses[1]->id,
'label' => $courses[1]->title
]);
echo $this->Form->control('courses.1._joinData.grade');
// ...
// in the `StudentsTable` class
public function beforeMarshal(\Cake\Event\Event $event, \ArrayObject $data, \ArrayObject $options)
{
forach ($data['courses'] as $key => $course) {
if (empty($course['id'])) {
unset($data['courses'][$key])
}
}
}
Alternatively you could use JavaScript to disable the controls related to the checkbox so that they aren't being submitted in the first place. For this to work properly you'll need to make sure that you disable the hidden field that is by default being generated for checkboxes (see the hiddenField option), as otherwise zero will be sent for unchecked checkboxes.
Here's a quick, untested jQuery example to illustrate the principle:
echo $this->Form->control('courses.0.id', [
'class' => 'course-checkbox',
'data-join-data-input' => '#course-join-data-0',
'type' => 'checkbox',
'hiddenField' => false, // no fallback, unchecked boxes aren't being submitted
'value' => $courses[0]->id,
'label' => $courses[0]->title
]);
echo $this->Form->control('courses.0._joinData.grade', [
'id' => 'course-join-data-0',
'disabled' => true
]);
// ...
$('.course-checkbox').each(function () {
var $checkbox = $(this);
var $joinDataInput = $($checkbox.data('join-data-input'));
$checkbox.on('change', function () {
$joinDataInput.prop('disabled', !$checkbox.prop('checked'));
});
});
See also
Cookbook > Database Access & ORM > Saving Data > Modifying Request Data Before Building Entities
Cookbook > Views > Helpers > Form > Creating Select, Checkbox and Radio Controls > Options for Control
Cookbook > Views > Helpers > Form > Creating Select, Checkbox and Radio Controls > Creating Checkboxes

How to populate dropdown from database laravel 5.x

Controller side:
$regs = Model::all('id','name');
return view('aview',compact('regs'));
View side:
{{ Form::select('id', $regs) }}
The dropdown gets rendered and populated but displays JSON objects such as {"id:1","name: Aname"} instead of displaying Aname and setting the post value to 1
Try this
In your controller
$regs = Model::pluck('name','id');
Keep your view same
Hope this will work
You can populate like this:
{!! Form::select('id', $regs->lists('name', 'id'), null, ['class' => 'form-control']) !!}
Form::select accepts four parameters:
public function select($name, $list = [], $selected = null, $options = []);
The name of the html field
the list of options
the selected value
an array of html attributes
You can generate the list by using
$regs = Model::all('id','name');
$plucked = $regs->pluck('name', 'id');
// $plcuked = ['id1' => 'name1', 'id2' => 'name2' ...]
And the blade code should look like this
{{ Form::select('name', $plucked, null, ['class' => 'form-control']); }}
I maybe making this problem a bit complicated but I think its worth using the plugin.
You can take the use of very popular plugin - Select2. This plugin of jQuery helps you to fetch data from server and populate the fetched data into our dropdown in minutes. Your code goes like this.
// Code in your Controller Method
$regs = Model::all();
$data = [];
foreach($regs as $reg) {
$data[] = [
'id' => $reg->id,
'text' => $reg->name
];
}
return json_encode(['items' => $data]);
// Code in your desired View
<select id="select_items"></select>
// Code in js
$('#select_items').select2({
ajax: {
url: '/example/api', // <--------- Route to your controller method
processResults: function (data) {
return {
results: data.items
};
}
}
});
You can also integrate search options using this plugins as it helps you to fetch results based on your search keywords (for more see Select2 Examples). Hope this helps you to solve your problem.

WP API Filter By Post Schema

Is it possible to return a list of posts based from the Wordpress Rest API v2 based on their schema:
For List of Schemas:
http://v2.wp-api.org/reference/posts/
I want to filter by sticky field, but the same would go for the rest of the fields.
So far I have:
/wp-json/wp/v2/posts?filter[sticky]=true
/wp-json/wp/v2/posts?filter[sticky]=1
Both return the same response as the standard endpoint:
/wp-json/wp/v2/posts
I have read other material such detailing how to sort by meta or custom taxonomies but I don't believe that's the same as this.
After going through the documentation and looking and posting issues on the WP-API Github repo, it's become clear that the filter[ignore_sticky_posts] should toggle the expected sorting behaviour, so that sticky posts are either always first (default) or ignored (by using filter[ignore_sticky_posts]=true).
However, there's currently a bug in WP API that makes the filter[ignore_sticky_posts] flag unusable.
The best way to fix it now would be to create you own custom endpoint to get the data or IDs of all the sticky posts in your database. By looking at the code discussed in this thread and in the WP-API documentation, I think adding the following code to your functions.php should do the trick:
// Sticky posts in REST - https://github.com/WP-API/WP-API/issues/2210
function get_sticky_posts() {
$posts = get_posts(
array(
'post__in' => get_option('sticky_posts')
)
);
if (empty($posts)) {
return null;
}
return $posts;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'THEME_NAME/v1', '/sticky', array(
'methods' => 'GET',
'callback' => 'get_sticky_posts',
));
});
If you GET /wp-json/THEME_NAME/v1/sticky, you should get an array of all your sticky posts.
I hope this helps.
In addition to Laust Deleuran's answer (thanks Laust!), i've created an altered version of his script which allows you to use the embedded feature of the REST-api.
Although this might not be 'the cleanest' solution, it does allow you to fully use the wp-json's functionality.
function get_sticky_posts(WP_REST_Request $request) {
$request['filter'] = [
'post__in' => get_option('sticky_posts')
];
$response = new WP_REST_Posts_Controller('post');
$posts = $response->get_items($request);
return $posts;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'THEME_NAME/v1', '/sticky', array(
'methods' => 'GET',
'callback' => 'get_sticky_posts',
));
});
This will output the sticky posts in the same schema as a normal /wp-json/wp/v2/posts query would respond.

Cakephp 3 & Ajax, send $.get additional data

I try to send custom data using $.get from jquery but cakephp 3 does not recognize the variables.
Here is my function in controller:
public function view($cat,$id,$page){
$comments = $this->Comments->find('all')->where(['category =' => $cat, 'AND' => ['category_id =' => $id]])->order(['comments.created' => 'DESC'])
->contain([
'Reports' => function($q){return $q->where(['user_id =' => $this->Auth->user('id')]);},
'Chars' => function($q){ return $q->select(['id','name','class','race','level','guild_id', 'user_id'])
->contain(['Guilds' => function($q){ return $q->select(['id','name']);
}]);
}])->limit(3)->page($page);
if($cat == 'Videos'){
$subject = $this->Comments->Videos->get($id);
}
$category = $cat;
$this->set(compact('subject','comments','category'));
}
}
And here's the .js
$('.more').click(function(){
$.get($(this).attr('href'),{cat:'Videos',id:'44',page:'2',function(data){
$('.coms').empty().append(data);
});
return false;
});
And the link:
<?= $this->Html->link('More', ['controller' => 'Comments','action' => 'view'], ['class' => 'btn btn-primary more']) ?>
The fix values in the .js is for the test, it works if I send the data in the link with $.get(href) but I want to know how to pass custom data in the $.get request.
Thank you for your help
CakePHP doesn't magically map query string parameters to method arguments, that's not even supported by routes.
You can access query string paramters via the request object
$this->request->query('cat');
See also http://book.cakephp.org/3.0/en/controllers/request-response.html#query-string-parameters
The solution
Hi, I did a little api to get the data I need from a json array.
So I created an ApiController to do all the ajax requests I need. Here is test example:
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
class ApiController extends AppController
{
public function test($id)
{
$UsersTable = TableRegistry::get('Users');
$users = $UsersTable->find()->where(['id <' => $id]);
$this->set(compact('users'));
}
}
?>
I want to get the list of all my users from an ajax call (that's the worst idea ever but it's just for the test ;))
Now I need to enable json for this view. For this, I need to go in config/routes.php to add this:
Router::scope('/api', function($routes){
$routes->extensions(['json']);
$routes->connect('/test/*', ['controller' => 'Api', 'action' => 'test', '_ext' => 'json']);
});
Now when I go on http://localhost/mywebsite/api/test/100, I have a json array of all the users with an id < 100, ready to get pulled by an ajax script.
'_ext' => 'json'
means you don't have to go on api/test.json to display the json array
Now on a random view in a random controller, I put a button to try all this and I call my javascript file to do my ajax request.
<button class="test">Test button</button>
<?= $this->Html->script('test', ['block' => true]) ?>
Now in my test.js:
$(document).ready(function(){
var value = 100;
$('.test').click(function(){
$.get('/api/test/' + value, function(data){
console.log(data);
});
});
});
I click the button and the log shows an array with all the users I wanted in my console when I push F12 (on chrome).
Hope this will help someone

How can I add a "Link Destination" field in the WordPress image attachment editor?

I'm using the WordPress "attachment" feature to allow end users of my theme to upload images that will appear above the post content (not inserted into the post itself).
The only problem I have is that there is not a field to allow the end user to specify the link that should be loaded when the end user clicks on one of the attached images. I'd like to add this field to the post attachment editor (the one that lists the "Gallery" of images attached to the post).
Alternately, and perhaps in addition, I'd like to be able to do the same thing when viewing images via the Media manager listing.
Currently, I'm using the "description" field to store the hyperlink to the image. and retrieving it like so (works perfectly but description is not semantic to link destination):
if ($images = get_children(array('post_parent' => get_the_ID(),'post_type' => 'attachment','post_mime_type' => 'image', 'orderby' => 'menu_order ASC, ID', 'order' => 'DESC' )))
{
foreach( $images as $image ) :
echo "<a href='".$image->post_content."'><img src='".wp_get_attachment_url($image->ID, 'medium')."' /></a>";
endforeach;
}
}
function my_image_attachment_fields_to_edit($form_fields, $post) {
$form_fields["custom1"] = array(
"label" => __("Image Links To"),
"input" => "text", // this is default if "input" is omitted
"value" => get_post_meta($post->ID, "_custom1", true)
);
return $form_fields;
}
function my_image_attachment_fields_to_save($post, $attachment) {
if( isset($attachment['custom1']) ){
update_post_meta($post['ID'], '_custom1', $attachment['custom1']);
}
return $post;
}
add_filter("attachment_fields_to_edit", "my_image_attachment_fields_to_edit", null, 2);
add_filter("attachment_fields_to_save", "my_image_attachment_fields_to_save", null, 2);