Create and edit office with JQuery.
authorGustavo Martin Morcuende <gu.martinm@gmail.com>
Mon, 4 Jun 2012 05:04:52 +0000 (07:04 +0200)
committerGustavo Martin Morcuende <gu.martinm@gmail.com>
Mon, 4 Jun 2012 05:04:52 +0000 (07:04 +0200)
Country, Region and City are chosen using JQuery.

apps/companyfront/modules/office/actions/actions.class.php
apps/companyfront/modules/office/templates/_formCustomOffice.php
lib/form/doctrine/CityForm.class.php
lib/form/doctrine/CountryForm.class.php
lib/form/doctrine/OfficeForm.class.php
lib/form/doctrine/RegionForm.class.php

index 70d8527..d505502 100644 (file)
@@ -55,6 +55,7 @@ class officeActions extends sfActions
 
     //Get company owned by that user and insert value in form
     $officeInit->company_id = CompanyTable::getInstance()->findOneByUserId($userId)->getId();
+    $officeInit->city_id = null;
 
     $this->form = new OfficeForm($officeInit);
 
@@ -285,7 +286,13 @@ class officeActions extends sfActions
     return $orderBy;
   }
 
-  public function executeChosencountry($request)
+ /**
+  * Run action from JQuery POST while chosing the country in the select HTML field
+  * for offices creation and edition.
+  *
+  * @param sfWebRequest with the chosen country
+  */
+  public function executeChosencountry(sfWebRequest $request)
   {
     $countryId = $request->getParameter('countryId');
 
@@ -325,42 +332,52 @@ class officeActions extends sfActions
     return $this->renderText(json_encode($regionsJSON));
   }
 
-  public function executeChosencountry($request)
+ /**
+  * Run action from JQuery POST while chosing the region in the select HTML field
+  * for offices creation and edition.
+  *
+  * @param sfWebRequest with the chosen region
+  */
+  public function executeChosenregion(sfWebRequest $request)
   {
     $regionId = $request->getParameter('regionId');
 
+    //set content type HTTP field  with the right value (we are going to use a JSON response)
+    $this->getResponse()->setContentType('application/json');
+
+
     //Never trust data coming from user
     if (!isset($regionId))
     {
-        //Incorrect data from user. Using default value.
-        $country = RegionTable::getInstance()->findOnebyCountryName(sfConfig::get('app_default_country'));
+        //Incorrect data from user.
+        //TODO: JSON error
+        return $this->renderText(json_encode("")); 
     }
     else
     {
-        $country = CountryTable::getInstance()->findOneById($countryId);
-        if (!isset($country))
+        $region = RegionTable::getInstance()->findOneById($regionId);
+        if (!isset($region))
         {
-            //Incorrect data from user. Using default value.
-            $country = CountryTable::getInstance()->findOnebyCountryName(sfConfig::get('app_default_country'));
+            //Incorrect data from user.
+            //TODO: JSON error
+            return $this->renderText(json_encode(""));
         }
     }
 
-    $regionsJSON = array();
+    $citiesJSON = array();
     //Retrieve Doctrine_Collection
-    $regions = RegionTable::getInstance()->findByCountryId($country->getId());
+    $cities = CityTable::getInstance()->findByRegionId($region->getId());
     //Using Doctrine_Collection_Iterator
-    $iterator = $regions->getIterator();
-    while ($region = $iterator->current())
+    $iterator = $cities->getIterator();
+    while ($city = $iterator->current())
     {
-        $regionsJSON[$region->getId()] = $region->getRegionName();
+        $citiesJSON[$city->getId()] = $city->getCityName();
         $iterator->next();
     }
 
-    //set content type HTTP field  with the right value (we are going to use a JSON response)
-    $this->getResponse()->setContentType('application/json');
 
     //Bypass completely the view layer and set the response code directly from this action.
     //In this way the user may know if the data were updated
-    return $this->renderText(json_encode($regionsJSON));
+    return $this->renderText(json_encode($citiesJSON));
   }
 }
index 717f8dd..8963f67 100644 (file)
@@ -8,6 +8,7 @@
                 function(data){
                     $('#office_City_region_id').empty();
                     $('#office_City_region_id').removeAttr('disabled');
+                    $('#office_City_region_id').append($("<option></option>").attr("value", "").text(""));
                     $.each(data, function(value, key) {
                         $('#office_City_region_id').append($("<option></option>").attr("value", value).text(key));
                     });
     });
 </script>
 
+<script type="text/javascript">
+    $(document).ready(function(){
+        $('#office_City_region_id').change(function() {
+            $.post('<?php echo url_for('office/chosenregion') ?>', { 'regionId': $(this).val() },
+                function(data){
+                    $('#office_city_id').empty();
+                    $('#office_city_id').removeAttr('disabled');
+                    $('#office_city_id').append($("<option></option>").attr("value", "").text(""));
+                    $.each(data, function(value, key) {
+                        $('#office_city_id').append($("<option></option>").attr("value", value).text(key));
+                    });
+            }, "json");
+        });
+    });
+</script>
+
+
 <form action="<?php echo url_for('office/'.($form->getObject()->isNew() ? 'create' : 'update').'?page='.$page.'&sort='.$sort.(!$form->getObject()->isNew() ? '&id='.$form->getObject()->getId() : '')) ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" ' ?>>
 <?php if (!$form->getObject()->isNew()): ?>
 <input type="hidden" name="sf_method" value="put" />
index 5bd697c..4bb45a2 100644 (file)
@@ -5,8 +5,8 @@
  *
  * @package    mobiads
  * @subpackage form
- * @author     Your name here
- * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
+ * @author     Gustavo Martin Morcuende
+ * @version
  */
 class CityForm extends BaseCityForm
 {
@@ -14,6 +14,9 @@ class CityForm extends BaseCityForm
   {
     unset($this['city_name']);
 
+    $this->widgetSchema['region_id'] = new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Region'), 
+                                                                            'add_empty' => true));
+
     $this->widgetSchema['region_id']->setAttribute('disabled', 'disabled');
 
     $this->embedRelation('Region');
index 04f4d49..77df0bc 100644 (file)
@@ -5,8 +5,8 @@
  *
  * @package    mobiads
  * @subpackage form
- * @author     Your name here
- * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
+ * @author     Gustavo Martin Morcuende
+ * @version
  */
 class CountryForm extends BaseCountryForm
 {
index cb5417e..b6f4b5d 100644 (file)
@@ -28,6 +28,10 @@ class OfficeForm extends BaseOfficeForm
                                                                           'add_empty' => true,
                                                                           'query' => $query));
 
+    $this->validatorSchema['city_id'] = new sfValidatorDoctrineChoice(array('model'   => $this->getRelatedModelName('City'),
+                                                                            'required' => true));
+
+
 
     $this->widgetSchema['city_id']->setAttribute('disabled', 'disabled');
 
@@ -91,7 +95,29 @@ class OfficeForm extends BaseOfficeForm
   */
   protected function doSave($con = null)
   {
-    parent::doSave($con);
+    if (null === $con)
+    {
+      $con = $this->getConnection();
+    }
+
+
+    if (!$this->getObject()->isNew())
+    {
+        $office = OfficeTable::getInstance()->findOneById($this->getObject()->getId());
+    }
+    else
+    {
+        $office = new Office();
+        $office->company_id = $this->getObject()->getCompanyId();
+    }
+    $office->city_id = $this->values['city_id'];
+    $office->office_street_address = $this->values['office_street_address'];
+    $office->office_zip = $this->values['office_zip'];
+
+    //TODO: Symfony sucks
+    $this->object = $office;
+
+    $office->save();
 
     //Get latitude and longitude values. They will be translated to GEOGRAPHIC data.
     foreach ($this->values as $field => $value)
@@ -102,10 +128,10 @@ class OfficeForm extends BaseOfficeForm
             $latitude = $value;
     }
     //Catch id element. We will use this id to insert the PostGIS value in the right row.
-    $arrowId = $this->getObject()->getId();
+    $rowId = $office->getId();
     //Update PostGIS
     //This connection will throw exception in case of error.
-    Doctrine_Manager::connection()->execute("UPDATE office SET office_gps=ST_GeographyFromText('SRID=4326;POINT($longitude $latitude)') WHERE id=$arrowId");
+    Doctrine_Manager::connection()->execute("UPDATE office SET office_gps=ST_GeographyFromText('SRID=4326;POINT($longitude $latitude)') WHERE id=$rowId");
   }
 
 
index 5f48455..b10071e 100644 (file)
@@ -5,8 +5,8 @@
  *
  * @package    mobiads
  * @subpackage form
- * @author     Your name here
- * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
+ * @author     Gustavo Martin Morcuende
+ * @version
  */
 class RegionForm extends BaseRegionForm
 {
@@ -14,6 +14,9 @@ class RegionForm extends BaseRegionForm
   {
     unset($this['region_name']);
 
+    $this->widgetSchema['country_id'] = new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Country'),
+                                                                             'add_empty' => true));
+
     $this->embedRelation('Country');
   }
 }