0

I have a model in Cakephp and want to change a Field in beforeSave function but the saved data is not correct.

Here is my function:

public function beforeSave($options = array()) {

    $address = @ClassRegistry::init('Address')->read(null, $this->data['Entry']['address_id']);

        if($address != false) {
            $url_address = $address['Address']['address']." ".$address['Address']['zip']." ".$address['Address']['city'];
            $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.urlencode($url_address).'&sensor=false');
            $output = json_decode($geocode);

            $lat = @$output->results[0]->geometry->location->lat;
            $lng = @$output->results[0]->geometry->location->lng;

            $this->data['Entry']['latitude'] = 0;
        $this->data['Entry']['longitude'] = 0;

        if($output->status == "OK") {
            $this->data['Entry']['latitude'] = $lat;
            $this->data['Entry']['longitude'] = $lng;
        }
    }

    return true;
}

The result from GoogleAPI is correct I checked it by writing:

print_r($this->data);
exit();

Only the data written in the DB is not correct. Don't know why - any ideas???

Thx

Adam
  • 1,865
  • 2
  • 23
  • 54
Marcel C
  • 55
  • 2
  • 7
  • What is the name of your model? – Wayne Whitty Jul 30 '13 at 10:42
  • I would not use `@ClassRegistry:` calls (@ is bad here). I also wouldn't code too much of that specific third party api request into the beforeSave method of a model. Try wrapping it using a lib or a behavior. Tip: http://www.dereuromark.de/2012/06/12/geocoding-with-cakephp/ – mark Jul 30 '13 at 10:45
  • The name of the model is "Entry" – Marcel C Jul 30 '13 at 10:48
  • @mark The problem is not that incorrect data is retrieved. The problem is to save it! Do I have to format the variables from the GoogleAPI that they fit a decimal(13,9) field? – Marcel C Jul 30 '13 at 10:54
  • What do you mean with not correct? You need to be more specific. – mark Jul 30 '13 at 12:02
  • If I have an address "Bremen" and save this Entry, the output by debugging is lat: 53.0833333 and lng: 8.8, but the saved data in the database is munich lat: 48.08 and lng: 11.31 – Marcel C Jul 30 '13 at 21:19

1 Answers1

0

We use this:

lat     decimal(10,8)
lng     decimal(11,8)
tersmitten
  • 1,248
  • 1
  • 9
  • 22
  • Thanks, but this "only" saves space but doesn't solve the saving-problem. – Marcel C Jul 30 '13 at 21:22
  • Is it possible that validation fails? What do you mean with "not correct"? – tersmitten Jul 31 '13 at 07:40
  • no the validation works, the problem is that if I choose a city like Bremen (Germany) and save the Entry, the coords in the database of this saved entry is Munich. which is about 1000km distance... if i save it again, it saves bremen - I think its a caching problem but I don't know where the values come from – Marcel C Aug 09 '13 at 11:16