mrsharko
mrsharko

Reputation: 295

how to use if isset() with symfony and post parameters

in the flat php I can just writing this line like that

if(isset($_POST['MoveString'])){

//code here 


}

but in symfony when I write my code like that

if(isset($request->get('MoveString'))){

//my code here

}

I get this error

Compile Error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

so what's the wrong aren't they the same result ?

Upvotes: 1

Views: 6921

Answers (2)

Toni Alvarez
Toni Alvarez

Reputation: 1032

In case you want to know if the parameter exists, even with a null value, you can use the has() method instead of get():

if ($request->has('MoveString')){

     //my code here

}

Upvotes: 0

hassan
hassan

Reputation: 8288

according to this part of isset documentation :

Warning

isset() only works with variables as passing anything else will result in a parse error.

and where is the result of expression in your code ?

to figure out this, take a quick look at the implementation of Request\get method :

public function get($key, $default = null)
{
    if ($this !== $result = $this->attributes->get($key, $this)) {
        return $result;
    }
    if ($this !== $result = $this->query->get($key, $this)) {
        return $result;
    }
    if ($this !== $result = $this->request->get($key, $this)) {
        return $result;
    }
    return $default;
}

and as you can see, for example from the ParameterBag object which is called via $this->attributes property, and you can check the other properties [ query, request ]'s objects too.

$result is returning a result of an expression

public function get($key, $default = null)
{
    return array_key_exists($key, $this->parameters) ? $this->parameters[$key] : $default;
}

so you simply needs to -as the error explains- to use your statement as follows:

if($request->get('MoveString') !== null){

//my code here

}

or even simpler :

if($request->get('MoveString')){

//my code here

}

Upvotes: 4

Related Questions