Search code examples
expressionenginesafecracker

Append Playa field via Safecracker


I'm building an artist directory and using Pixel & Tonic's Playa to manage each member's "fans."

In each user's profile, there is a multi-select Playa field that displays all of the members that user has "fanned" (similar to "like" on Facebook).

What I'd like to do is have a "link" that's actually a safecracker submission that will add a member's name to the user's Playa field.

Essentially, it will be a form with hidden fields for the User's ID and the screen name of the member whose page is being viewed. I want to append the screen name to the user's existing Playa field entries.

What's the best way to achieve this?

Thanks!

ty


Solution

  • You'll need to add a custom plugin to do this, so you can perform a custom SQL insert.

    Not sure if you're familar with writing plugins, but you can get started by creating one via pkg.io, and then adding this function to the resulting file. Then you can create a link to a template where you place your new tag, and perhaps pass the ids for the member and the new fan via segments:

    {exp:my_plugin:add_fan member_id="{segment_3}" fan_id="{segment_4}"}
    

    This function makes the (perhaps mistaken) assumption that you're storing your members in channels (I assume so, because you're using a Playa field), and that you have access in your templates to the entry_id of both the member and fan. If not, you may need to perform some more queries to find the entry_id of each. It also calls your Playa field field_id_10 ... you'll need to replace 10 with the proper field_id of your Playa field.

    function add_fan()
    {
        $this->EE =& get_instance();
    
        $member_id = $this->EE->TMPL->fetch_param('member_id');
        $fan_id = $this->EE->TMPL->fetch_param('fan_id');
    
        $data = array(
            'parent_entry_id' => $member_id,
            'child_entry_id' => $fan_id,
            'parent_field_id' => 10
        );
    
        $this->EE->db->query(
            $this->EE->db->insert_string('exp_playa_relationships', $data)
        );
    }