0

I am trying to implement a new way for users to enter data into an HTML form with Slim Select JS library.

I have basic functionality working, with a pre-populated list of <option> items.

Originally, the PHP code would grab the list of names from a database (now in MongoDB), which is then looped through when the <select> element is created.

With Slim Select, you can pass in a "data array" as a parameter of the JS script. The manually-created format is this:

var jsPlayers2 = [
    {"placeholder": true, "text": "Type Name"},
    {"text": "Ernie Els", "value": "abc1"},
    {"text": "Rory McIlroy", "value": "abc2"},
    {"text": "Tiger Woods", "value": "abc3"}
];
        
new SlimSelect({
    select: '#slim-select',
    data: jsPlayers2, // THIS WOULD BE REPOINTED TO THE JSPLAYERS ARRAY VAR...
    
    onChange: (info) => {
        console.log(info)
    }
})

My MongoDB document structure returned currently is:

var jsPlayers = [{
        "_id": {
            "$oid": "62b49410e63c2f8469089189"
        },
        "name": "Tiger Woods",
        "clubs": [{
            "clubId": {
                "$oid": "6076030465508936f00e086c"
            },
            "name": "Jupiter FL",
            "nickName": "Jupiter",
            "logoPath": "jupiter.png"
        }]
    }, {
        "_id": {
            "$oid": "609d0993906429612483cfb1"
        },
        "name": "Ernie Els",
        "clubs": [{
            "clubId": {
                "$oid": "6076030465508936f00e086c"
            },
            "name": "Wentworth UK",
            "nickName": "Wentworth",
            "logoPath": "wentworth.png"
        }]
    }, ...
}];

I have used a simplistic echo of this variable into a new JS variable:

var jsPlayers = <?php echo json_encode($players); ?>;

How can I only pick out the fields I need from within each document? Or is there a way to filter the array elements when I add them to the slim-select.data property?

1 Answer 1

1

You need to loop through your players to create the array you want to output as JSON. Something like this:

$options = [];
foreach ($players as $player) {
    $options[] = (object)["text"  => $player->name,
                          "value" => $player->getId()];
}
echo json_encode($options);

This only outputs the JSON.

Note that I used $player->getId(), which might not work for you. If your players are really objects you might have defined a method yourself to get their id.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.