0

i'm trying to create a twig function that insert a new value in a associated array using variable variables but when i print the new value, the value doesn't appear, showing me an error that says 'key MynewKey doesn't exist'.

i am supposing that its a reference value problem.

/**
 * add a value to your twig array instead of using merge
 *
 * @param $originalArray  Array or object(public access) to set a new value
 * @param $value value to be inserted
 * @param string $Key arrayKey/objec associated name
 * @param string $sKey subarrayKey associated name
 * 
 */ 
public function arrayKeyValueSetter($originalArray, $value, $Key, $sKey= null, $ssKey= null, $sssKey= null, $ssssKey= null, $sssssKey = null){
    $array = $originalArray;
    $realKey = "Key";
    $arrayKeys = "";

    for ($i=0; $i < 5 ; $i++) { 
        if(!empty($$realKey)){
            if(strpos($$realKey,"array_") !== false) {
                $$realKey = str_replace("array_", "", $$realKey);
                $arrayKeys .= "['" . $$realKey . "']";
            }else{
                $arrayKeys .= "->" . $$realKey;
            }
        }
        $realKey = "s". $realKey;
    }

    $realArray = 'array'; #variable name
    $realArrayAccess = $realArray . $arrayKeys;  #variable name with access "foo['var']->access->['new']"
    $$realArrayAccess = $value; #setting the new value $foo['var']->access->['new'] = value

    return $array;
}

twig

{% if value is defined and value is not null %}
    {% set form = form|array_key_value_setter(value.id, 'children','array_media','vars','array_contentHasMediaId') %}
{% endif %}

example: i want to create a new key with a new value in this object(has public access) that cotains arrays expected result:

dump(form.children.media.vars.contentHasMediaId) #output: value inserted

actual

dump(form.children.media.vars.contentHasMediaId) #error: key contentHasMediaId doesn't exist

maybe it is not the best way to add a new value to a twig array, but i tried to omit the use of merge() function that is limited adding specific values to associated names,and that's why i tried to create a function that replace twig merge() function.

2

0

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.