Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't update user custom field #1

Closed
gino8080 opened this issue Feb 5, 2016 · 20 comments
Closed

Can't update user custom field #1

gino8080 opened this issue Feb 5, 2016 · 20 comments

Comments

@gino8080
Copy link

gino8080 commented Feb 5, 2016

Hello tried using the same user (id = 4) and also an Admin

using end point
POST or PUT
/wp-json/acf/v2/user/4
payload sended (ragione is the custom field associated to the user):

 fields: {
        ragione: "pippo" 
      }

I'm sending also the nonce

I always got this error
(it works good updating post acf fields)

{
code: "rest_forbidden",
data : { 
 status: 403
},
message: "You don't have permission to do this."
}

thank you very much!

@gino8080
Copy link
Author

gino8080 commented Feb 5, 2016

If I try with another ADMIN user (or changing the same user role as EDITOR ) I got a different error:

{
code: "cant_update_item",
data : { 
 status: 500
},
message: "Cannot update item"
}

@airesvsg
Copy link
Owner

airesvsg commented Feb 5, 2016

Hi @gino8080,

In my example I used the method POST, but I should have used the method PUT to update the ACF fields.
( I updated in my last commit )

See below each method and theirs actions.

Method Action
POST Create
GET Retrieve
PUT Update
DELETE Delete

Please, can you send me a dump of your database?
airesvsg@gmail.com

Thanks

@gino8080
Copy link
Author

gino8080 commented Feb 6, 2016

Hello Aire,

thank you for fast answer!

just tried with PUT and same results :(

Sent my dump (just removed some personal infos)

waiting for you!
thank you!

@airesvsg
Copy link
Owner

airesvsg commented Feb 8, 2016

Hi @gino8080 ,
you are sending the nonce code?

Thanks

@gino8080
Copy link
Author

gino8080 commented Feb 9, 2016

sure, I'm using http angular , the nonce is in the interceptor request

calling GET /users/me path works

REQUEST:
GET /traipler-web/wp-json/wp/v2/users/me HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, /
X-WP-Nonce: b8d0e7520b
User-Agent: Mozilla/5.0....

RESPONSE OK

Calling the PUT or POST to /wp-json/acf/v2/user/ID (my logged ID user) Does NOT work :(

REQUEST

//the nonce is added to headers in the interceptors
 $http({
        method: "PUT", //tried also POST
        url: '/traipler-web/wp-json/acf/v2/user/1', //1 is my logged id user
        data: fields: {
           work: "Developer" //work is the acf field name
       }
      })

PUT /traipler-web/wp-json/acf/v2/user/1 HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Content-Length: 31
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, /
Origin: http://localhost:8888
X-WP-Nonce: b8d0e7520b
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
Content-Type: application/json;charset=UTF-8
DNT: 1
Referer: ....

RESPONSE KO
500 (Internal Server Error)
"cant_update_item" message

don't know why

@airesvsg
Copy link
Owner

airesvsg commented Feb 9, 2016

Hi @gino8080,
Please, check how you are sending the data:

Follow the example below:

$http( {
    method: "PUT",
    url: '/traipler-web/wp-json/acf/v2/user/1',
    // headers: { 'X-WP-Nonce' : WP_API_Settings.nonce },
    data: {
        "fields": {
            "work": "Developer"
        }
    }
} )

@gino8080
Copy link
Author

hello good aire,

Tried formatting the request data as you suggested..but nothing :(

So I tried using your example php (so just jquery ajax)
updating a simple acf post type works!

update a User acf field NOT!

this is the simple html and javascript used

<form id="myform" action="http://localhost:8888/traipler-web/wp-json/acf/v2/user/1" method="POST">
        <input type="text" name="fields[work]"  id="acf-title">
        <button type="submit">Save</button>
 </form>
jQuery(document).ready(function($) {
      $('#myform').on("submit", function(e) {
        e.preventDefault();
        var _this = $(this);
        var url = _this.attr('action');
        var data = _this.serializeArray();
        var btn = _this.find('button[type="submit"]');
        var modal = $('#modalResponse');
        $.ajax({
          url: url,
          method: 'POST',
          beforeSend: function(xhr) {
            xhr.setRequestHeader('X-WP-Nonce', myLocalized.nonce);
          },
          data: data,
          dataType: 'json'
        }).always(function(data) {
          btn.removeProp('disabled');
          modal.find('.modal-body').html('<pre>' + JSON.stringify(data, null, "\t") + '</pre>');
          modal.modal('show');
        });
        return false;
      });
    });

error: 500
cant_update_item

please can you give me a working user acf editing example?

tank you very much!

@airesvsg
Copy link
Owner

Hi @gino8080,

please, add this filter in your functions.php

add_filter( 'acf/rest_api/item_permissions/update', function( $permission, $request, $type ) {
    if ( 'user' == $type && method_exists( $request, 'get_param' ) && get_current_user_id() == $request->get_param( 'id' ) ) {
        return true;
    }
    return $permission;
}, 10, 3 );

Example: gino.zip

Instructions:

  1. Extract files;
  2. Import the database ( dump.sql );
  3. Set the urls with the below constants in your wp-config.php
define( 'WP_HOME', 'http://localhost:8888/traipler-web' );
define( 'WP_SITEURL', 'http://localhost:8888/traipler-web' );

Thanks

@gino8080
Copy link
Author

First thank you for your support airesvsg !!

these are the feedbacks:

using your wp setup example it works BUT:

when I call these endpoints (this happens on both your and mine wp setup):

(Either with the ajax or going directly using the browser)
in the 50% of the times i got a: No data received ERR_EMPTY_RESPONSE error ??
what the hell can be??

with my wp setup

  • I just realized that I'm using the ACF PRO 5.3.3.2 version and switching to advanced custom field (NORMAL FREE) it works
  • It works also without the acf/rest_api/item_permissions/update filter (i really hoped was that the problem !)

So the questions are:

  • Maybe the PRO version has something different?
  • Why i got these ERR_EMPTY_RESPONSE errors calling the /wp-json/acf/v2/.. endopoints?
  • What I can do to help solving the problem? (i can give you mine acf pro files if needed :))

thank you very much!!

@gino8080
Copy link
Author

ok i can confirm that the problem is acf pro,

tested online on staging server,

exactly same setup, just swapped ACF PRO (v5.3.3.2 ) with ACF FREE (v4.4.5 ) and it works
Also I'm not getting the ERR_EMPTY_RESPONSE from the api endpoints (so should be a localhost problem)

Maybe the v5 has some breaking changes ?

@gino8080
Copy link
Author

Ok @airesvsg I got it!

To EDIT a custom field on a USER
I had to set the LOCATION Rule of the Field Group in the Admin to:

Current User -- is equal to -- Logged In
location rule required for acf pro user editing
Other wise the acf_get_field_group_visibility function returned always empty!

using the others User location rules : User Form / User Role was not enought!

thank you very much for your great support!
and sorry If I stolen your time! :)

you can close this now!

@airesvsg
Copy link
Owner

Hi @gino8080,

Sorry, I can't answer before.

Ok, I'll test this rule and put on readme.

Thanks

@DrBGM
Copy link

DrBGM commented Nov 3, 2016

I have the same issue with Advanced Custom Fields PRO 5.4.8:

for example - acf rest returns correct data for products

https://subdomain.domain.at/wp-json/acf/v2/post/3656

it returns:

{"acf":{"product_manual":"abc.pdf","product_youtube_url":"dsadasdasdas"}}

now I'm trying to post costom fields
but all times i get the error from acf rest api site:
{"code":"rest_forbidden","message":"You don't have permission to do this.","data":{"status":403}}

It did not help to change "Current User -- is equal to -- Logged In" (see above)

Thank you in advance

@DrBGM
Copy link

DrBGM commented Nov 5, 2016

I think we found some interesting thing:

(1) Access Control Headers:
https://joshpress.net/access-control-headers-for-the-wordpress-rest-api/

to get :

Access-Control-Allow-Methods:POST, GET, OPTIONS, PUT, DELETE
allow: GET, POST, PUT, PATCH

image

(2) since October 07, 2016: WordPress REST API (Version 2)

https://de.wordpress.org/plugins/rest-api/changelog/

2.0 Beta 15.0 (October 07, 2016)

Introduce support for Post Meta, Term Meta, User Meta, and Comment Meta in their parent endpoints.

For your meta fields to be exposed in the REST API, you need to register them. WordPress includes a register_meta() function which is not usually required to get/set fields, but is required for API support.

To register your field, simply call register_meta and set the show_in_rest flag to true. Note: register_meta must be called separately for each meta key.

Introduce Settings endpoint.

Expose options to the REST API with the register_setting() function, by passing $args = array( 'show_in_rest' => true ). Note: WordPress 4.7 is required. See changeset [38635][https://core.trac.wordpress.org/changeset/38635].

@rajuodedara006
Copy link

Hello @airesvsg first thanks for awesome plugin. i'm having issue to update user fields

Here is details what we have in our admin panel :

ACF to REST API --- Version 3.1.0
Advanced Custom Fields PRO --- Version 5.7.13
JSON Basic Authentication --- Version 0.1

This is htaccess link : https://url.upwork.com/_01Hp0Ddp5lbjtnkVudB_RqKfMK5hx8O-5K

End point : https://example.com/wp-json/acf/v3/users/1

Body:
{
"fields": {
"vehicle_make": "Ferrari",
"vehicle_model": "360 Modena",
"vehicle_year": "2007"
}
}

Response :
{
"code": "cant_update_item",
"message": "Cannot update item",
"data": {
"status": 500
}
}

What could be the issue as i have tried your every thread regarding this issue but no luck yet.

Please help regarding this.

@koystrubvs
Copy link

Hello @airesvsg first thanks for awesome plugin. i'm having issue to update user fields

Here is details what we have in our admin panel :

ACF to REST API --- Version 3.1.0
Advanced Custom Fields PRO --- Version 5.7.13
JSON Basic Authentication --- Version 0.1

This is htaccess link : https://url.upwork.com/_01Hp0Ddp5lbjtnkVudB_RqKfMK5hx8O-5K

End point : https://example.com/wp-json/acf/v3/users/1

Body:
{
"fields": {
"vehicle_make": "Ferrari",
"vehicle_model": "360 Modena",
"vehicle_year": "2007"
}
}

Response :
{
"code": "cant_update_item",
"message": "Cannot update item",
"data": {
"status": 500
}
}

What could be the issue as i have tried your every thread regarding this issue but no luck yet.

Please help regarding this.

I have this problem :(

@airesvsg
Copy link
Owner

airesvsg commented May 6, 2019

Hi,

Please read about authentication, it's necessary to create or update.

Thanks

@jimmckay
Copy link

jimmckay commented Jul 1, 2019

Be sure "Location" section in the "Edit Field Group" page of the Custom Field admin allows access to the user or role your API calls are made as. It took me a while to find this solution.

@gleenk
Copy link

gleenk commented Mar 8, 2021

Hi guys, unfortunately, I got stuck in the same problem. I can update all User fields (description etc) but not custom ACF fields. I set Current User -> is equal to -> Logged In but I always get "undefined" as an answer from the endpoint. I'm using Bearer Token for auth and Axios to make POST call.

1
4
3
2

@Crownie
Copy link

Crownie commented Jul 6, 2021

For anyone having similar problem to @gino8080 Here is my workaround;
Add this snippet to your functions.php or a custom plugin

// Allow current user to update own profile
add_filter( 'acf/rest_api/item_permissions/update', function( $permission, $request, $type ) {
    if ( 'user' == $type && method_exists( $request, 'get_param' ) && get_current_user_id() == $request->get_param( 'id' ) ) {
        return true;
    }
    return $permission;
}, 10, 3 );

// Allow user acf rest user update to be detected as location "user_form".
add_filter( 'acf/location/screen', function( $screen, $deprecated ) {
    if(!empty($screen['post_id']) && preg_match("/^user_\d+$/i",$screen['post_id'])){
       $screen = wp_parse_args($screen, array(
           'user_form'    => 'edit'
       ));
    }
    return $screen;
}, 10, 2 );

Set field location to: User Form = all or edit

Example request
POST /wp-json/acf/v3/users/2
body {"fields":{"foo":"bar"}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants