This forum is in READ-ONLY mode.
You can look around, but if you want to ask a new question, please use the new forum.
Home » support » symfony 1.3 and 1.4 » How to create a link to this routing
How to create a link to this routing [message #102644] Sat, 17 July 2010 04:47 Go to next message
jstuardo  is currently offline jstuardo
Messages: 49
Registered: May 2010
Location: Santiago
Member
Hello...

I have a backend module called "currency" which lists all currencies that the system supports.

One of the action that can be executed for each currency is the configuration of exchange rates.

I want a route to be: /exchangeRate/1, where that "1" is the ID of the currency.

I tried using this instruction:

public function linkToExchange($object, $params)
{
  return link_to('<img src="/images/icons/exchange.png" title="' . __($params['label'], array(), 'sf_admin') . '" width="16" height="16" />', '@exchangeRate', $object);  	
}


where $object is the currency.

The route I defined is:

exchangeRate:
  class: sfDoctrineRouteCollection
  options:
    model:                ExchangeRate
    module:               exchangeRate
    prefix_path:          /exchangeRate/:currency_id
    column:               id
    with_wildcard_routes: true
    requirements:
      currency_id: \d+


But an error is shown because id parameter is not defined.

The "/exchangeRate/:currency_id/.:sf_format" route has some missing mandatory parameters (:currency_id).

How can I do it?

Thanks
Jaime

[Updated on: Sat, 17 July 2010 04:48]


Symfony 1.4
Re: How to create a link to this routing [message #102648 is a reply to message #102644 ] Sat, 17 July 2010 05:09 Go to previous messageGo to next message
sescandell  is currently offline sescandell
Messages: 65
Registered: December 2008
Location: France
Member
Hi,

If I am not wrong, it is because of your pattern routing.
Just have a look on what you are doing :
prefix_path:          /exchangeRate/:currency_id

That means, if you use the link_to() method with an object as argument, to generate the URL, it will try to call the method getCurrencyId() from your object (and I think this one doesn't exist. If it exists, forget my answer Very Happy)

Two possibilities to correct your problem :
in model/ExchangeRate.php add the function
public function getCurrencyId()
{
  return $id; // if currency_id correspond to ExchangeRate id
}

The best one would be to change your pattern routing by :
prefix_path:          /exchangeRate/:id

if currency_id correspond to the ExchangeRate id (if not, just adapt the code Very Happy)
Good luck !

[Updated on: Sat, 17 July 2010 15:55]

Re: How to create a link to this routing [message #102653 is a reply to message #102648 ] Sat, 17 July 2010 13:05 Go to previous messageGo to next message
septem  is currently offline septem
Messages: 19
Registered: January 2009
Location: Riga, Latvia
Junior Member
You don't have to use '@' sign before the route name for object routes.


Ivo Az.
Re: How to create a link to this routing [message #102663 is a reply to message #102644 ] Sat, 17 July 2010 17:06 Go to previous messageGo to next message
jstuardo  is currently offline jstuardo
Messages: 49
Registered: May 2010
Location: Santiago
Member
Hello...

I have 2 tables, Currency and ExchangeRate. The relationship is one to many. The Currency table is the parent table, and the ExchangeRate is the child. So, ExchangeRate has an id column which is its own identity, and a currency_id column which is the foreign key.

The doctrine generator, automatically created getCurrencyId() method of the ExchangeRate model.

Now I have a page that manages currencies. The index template of it contains the list of currencies. For each currency, I want to be able to manage the corresponding exchange rates.

If I use only this link "/exchangeRate", the index page of the exchange rate is shown, which displays all exchange rates, for all currencies. So I want to pass a parameter to the index page that corresponds to the currency id. For that, I want to generate a link such as "/exchangeRate/1" that causes the index page to list only exchange rates belonging to currency whose id is 1.

I tried without the @ as well and even manually concatenating the /1 but it is not working.

Any further help will be appreciated

Thanks
Jaime


Symfony 1.4
Re: How to create a link to this routing [message #102664 is a reply to message #102644 ] Sat, 17 July 2010 18:06 Go to previous messageGo to next message
jstuardo  is currently offline jstuardo
Messages: 49
Registered: May 2010
Location: Santiago
Member
Hello... I have finally left the exchangeRate as the original value, that is,

exchangeRate:
  class: sfDoctrineRouteCollection
  options:
    model:                ExchangeRate
    module:               exchangeRate
    prefix_path:          /exchangeRate
    column:               id
    with_wildcard_routes: true


and created this new route:

currency_exchange_rate:
  url:   /:module/:id/index
  class: sfDoctrineRoute
  param: { module: exchangeRate }
  options: { model: ExchangeRate, type: object }
  requirements:
    id: \d+


And the link_to call is:

public function linkToExchange($object, $params)
{
  return link_to('<img src="/images/icons/exchange.png" title="' . __($params['label'], array(), 'sf_admin') . '" width="16" height="16" />', $this->getUrlForAction('exchange_rate'), $object);  	
  }


The final URL is:
/backend_dev.php/exchangeRate/3/index

I don't know if this a right solution, but the URL is generated as I expected, at least Smile

Any advice will be welcome.

Thanks
Jaime


Symfony 1.4
Re: How to create a link to this routing [message #102668 is a reply to message #102644 ] Sat, 17 July 2010 18:56 Go to previous messageGo to next message
sescandell  is currently offline sescandell
Messages: 65
Registered: December 2008
Location: France
Member
Hi,

I am realizing that I didn't notice that you were using a RouteCollection ... so, sorry Very Happy ...

So ... here is how it works :
<prefix_path> is the parameter to (as the name means) prefix all your routes corresponding to the object from the module <module>. In fact, the code
exchangeRate:
  class: sfDoctrineRouteCollection
  options:
    model:                ExchangeRate
    module:               exchangeRate
    prefix_path:          /exchangeRate
    column:               id
    with_wildcard_routes: true


is just a shortcut for
exchangeRate:
  url:     /exchangeRate.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: list }
  param:   { module: exchangeRate, action: index, sf_format: html }
  requirements: { sf_method: get }
 
exchangeRate_new:
  url:     /exchangeRate/new.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: new, sf_format: html }
  requirements: { sf_method: get }
 
exchangeRate_create:
  url:     /exchangeRate.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: create, sf_format: html }
  requirements: { sf_method: post }
 
exchangeRate_edit:
  url:     /exchangeRate/:id/edit.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: edit, sf_format: html }
  requirements: { sf_method: get }
 
exchangeRate_update:
  url:     /exchangeRate/:id.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: update, sf_format: html }
  requirements: { sf_method: put }
 
exchangeRate_delete:
  url:     /exchangeRate/:id.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: delete, sf_format: html }
  requirements: { sf_method: delete }
 
exchangeRate_show:
  url:     /exchangeRate/:id.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: show, sf_format: html }
  requirements: { sf_method: get }


<prefix_path> allow you to change the url pattern. For example, if you put it to myExchangeRateUrl, the generated routes will be
exchangeRate:
  url:     /myExchangeRateUrl.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: list }
  param:   { module: exchangeRate, action: index, sf_format: html }
  requirements: { sf_method: get }
 
exchangeRate_new:
  url:     /myExchangeRateUrl/new.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: new, sf_format: html }
  requirements: { sf_method: get }
 
exchangeRate_create:
  url:     /myExchangeRateUrl.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: create, sf_format: html }
  requirements: { sf_method: post }
 
exchangeRate_edit:
  url:     /myExchangeRateUrl/:id/edit.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: edit, sf_format: html }
  requirements: { sf_method: get }
 
exchangeRate_update:
  url:     /myExchangeRateUrl/:id.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: update, sf_format: html }
  requirements: { sf_method: put }
 
exchangeRate_delete:
  url:     /myExchangeRateUrl/:id.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: delete, sf_format: html }
  requirements: { sf_method: delete }
 
exchangeRate_show:
  url:     /myExchangeRateUrl/:id.:sf_format
  class:   sfDoctrineRoute
  options: { model: ExchangeRate, type: object }
  param:   { module: exchangeRate, action: show, sf_format: html }
  requirements: { sf_method: get }


So here with your route
currency_exchange_rate:
  url:   /:module/:id/index
  class: sfDoctrineRoute
  param: { module: exchangeRate }
  options: { model: ExchangeRate, type: object }
  requirements:
    id: \d+


You are duplicating the exchangeRate_show (except that the url is not exactly the same), so you cannot have the URL you want with this routing.

About what you want to do. Normaly, it is more logic that the URL corresponding to the page listing all exchanges for a given currency, should look like :
currency/:currencyId/exchangeRates (for example). Because, you want to list all exchangeRates from a given currency ... For that, I would use the following routing:
exchangeRate:
  class: sfDoctrineRouteCollection
  options:
    model:                ExchangeRate
    module:               exchangeRate
    prefix_path:          /exchangeRate
    column:               id
    with_wildcard_routes: true

currency:
  class: sfDoctrineRouteCollection
  options:
    model:                Currency
    module:               currency
    prefix_path:          /currency
    column:               id
    with_wildcard_routes: true

currency_exchange_rates:
  url: /currency/:id/exchangeRates
  class: sfDoctrineRoute
  options: {model: ExchangeRate, type: list, method: retrieveByCurrencyId}
  param:   {module: currency, action: exchangeRates}
  requirements:
    id: \d+
    sf_method: [get]


(Moreover the best would be to use a slug whereas the id ...)

If you want to stay in the module exchangeRate, you can add a route like this one
currency_exchange_rates:
  url: /exchangeRates/currency/:currency_id
  class: sfDoctrineRoute
  options: {model: ExchangeRate, type: list, method: retrieveByCurrencyId}
  param:   {module: exchangeRate, action: index}
  requirements:
    currency_id: \d+
    sf_method: [get]


I am not sure, but maybe it will work with the default index action (if it is not, change the action by yours).

Of course you have to create the function retrieveByCurrencyId() (but maybe this function is auto-generated ... I don't know Doctrine enough to know that ... I know that with Propel Symfony provides automatically these kinds of method ... so maybe with Doctrine too)

Good luck !

[Updated on: Sat, 17 July 2010 19:54]

Re: How to create a link to this routing [message #102679 is a reply to message #102644 ] Sat, 17 July 2010 23:52 Go to previous messageGo to next message
jstuardo  is currently offline jstuardo
Messages: 49
Registered: May 2010
Location: Santiago
Member
Hello...

thanks for your complete answer...

I did it but I had an error about the id parameter. To solve it,
I modified the route as this:

currency_exchange_rates:
  url:   /currency/:id/exchangeRates
  class: sfDoctrineRoute
  param: { module: currency }
  options: { model: ExchangeRate, type: object }
  requirements:
    id: \d+
    sf_method: [ get ]


The exchangeRate action of the currency module is called. The Currency module does have an auto generated method called
getExchangeRate() which returns the exchange rates collection, but I want to redirect to the Exchange Rate module so that I can list, edit and create new exchange rates for selected currency.

So, how can I make a redirect to the @exchangeRate route passing the currency id parameter? Something like:

	public function executeExchangeRates(sfWebRequest $request) {
		$this->redirect ('exchangeRate/currency/' . $request->getParameter('id'));
	}	


Thanks
Jaime


Symfony 1.4
Re: How to create a link to this routing [message #102684 is a reply to message #102644 ] Sun, 18 July 2010 03:09 Go to previous messageGo to next message
sescandell  is currently offline sescandell
Messages: 65
Registered: December 2008
Location: France
Member
Hi !

Quote:

The exchangeRate action of the currency module is called. The Currency module does have an auto generated method called getExchangeRate()


Yes, you can try something like that :

currency_exchange_rates:
  url:   /currency/:id/exchangeRates
  class: sfDoctrineRoute
  param: { module: exchangeRates, action: index}
  options: { model: ExchangeRate, type: list, method: getExchangeRatesByCurrencyId()}
  requirements:
    id: \d+
    sf_method: [ get ]


I think this can work ...

And so to create your route just use :
link_to('currency_exchange_rates',$myCurrencyObject);
// or maybe 
// link_to('@currency_exchange_rates',$myCurrencyObject);


I am just guessing here ... I will try it and coming back with more feedbacks and tested results Very Happy

See you

[Updated on: Sun, 18 July 2010 03:10]

Re: How to create a link to this routing [message #102685 is a reply to message #102644 ] Sun, 18 July 2010 04:01 Go to previous messageGo to next message
sescandell  is currently offline sescandell
Messages: 65
Registered: December 2008
Location: France
Member
Hi again !

Ok I have something functionnal to propose you.
I used the following example schema:
Currency:
  actAs: { Timestampable: ~ }
  columns:
    name: { type: string(255), notnull: true, unique: true }

ExchangeRate:
  actAs: { Timestampable: ~ }
  columns:
    currency_id:  { type: integer, notnull: true }
    name: { type: string(255), notnull: true, unique: true }
  relations:
    Currency: { onDelete: CASCADE, local: currency_id, foreign: id, foreignAlias: ExchangeRates } 


I generated a frontend application:
php symfony doctrine:generate-app frontend


I generated two modules :
php symfony doctrine:generate-module frontend currencies Currency
php symfony doctrine:generate-module frontend exchangeRates ExchangeRate


I modify the /apps/frontend/config/routing.yml as follow:
homepage:
  url:   /
  param: { module: default, action: index }

currency_exchange_rates:
  url:   /currencies/:id/exchangeRates
  class: sfDoctrineRoute
  param:   { module: exchangeRates, action: indexCurrency}
  options: { model: Currency, type: object}
  requirements:
    id: \d+
    sf_method: [ get ]

exchangeRate:
  class: sfDoctrineRouteCollection
  options:
    model:                ExchangeRate
    module:               exchangeRates
    prefix_path:          /exchangeRates
    column:               id
    with_wildcard_routes: true

currency:
  class: sfDoctrineRouteCollection
  options:
    model:                Currency
    module:               currencies
    prefix_path:          /currencies
    column:               id
    with_wildcard_routes: true

# generic rules
# please, remove them by adding more specific rules
#default_index:
#  url:   /:module
#  param: { action: index }
#
#default:
#  url:   /:module/:action/*



Then, in the exchangeRates module, I created the following action:
// file /apps/frontend/module/exchangeRates/actions/actions.class.php
public function executeIndexCurrency(sfWebRequest $request)
  {
    $this->currency       = $this->getRoute()->getObject(); 
    $this->exchange_rates = $this->currency->getExchangeRates();
    $this->setTemplate('index');
  }



And I modified the currencies list template as following (which is just an example to show you how to use the new route):
// file /apps/frontend/module/currencies/template/indexSucess.php
<h1>Currencys List</h1>

<table>
  <thead>
    <tr>
      <th>Id</th>
      <th>Name</th>
      <th>Created at</th>
      <th>Updated at</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($currencys as $currency): ?>
    <tr>
      <td><a href="<?php echo url_for('currency_exchange_rates',$currency) ?>"><?php echo $currency->getId() ?></a></td>
      <td><?php echo $currency->getName() ?></td>
      <td><?php echo $currency->getCreatedAt() ?></td>
      <td><?php echo $currency->getUpdatedAt() ?></td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table>

  <a href="<?php echo url_for('currencies/new') ?>">New</a>


And everything is working as you want ... (so now you can adapt the code to exactly fit to what you want).

Of course, next step is to adapt the code to automaticaly define the currency when you create a new exchange rate and modify the "back to list" link ...


See you !

[Updated on: Sun, 18 July 2010 04:24]

Re: How to create a link to this routing [message #102702 is a reply to message #102644 ] Sun, 18 July 2010 21:22 Go to previous messageGo to next message
jstuardo  is currently offline jstuardo
Messages: 49
Registered: May 2010
Location: Santiago
Member
Hello! Thanks a lot for your help.. it worked perfectly! but now I have a question in order to finish it. When I add a new currency, the currency_id combobox appears without any selection.

I know how to convert it to a hidden field ut, I was trying to set the value with the actual currency id, but I could not do it.

The easiest solution would be to hardcode the field as

<input type="hidden" id="currency_id" value="<?php echo $currency->getId() ?>" />


But I want to use the generator.yml to define the currency_id field and to be populated with the actual currency identity.

For example, I tried with:

$this->exchangeRate = $this->form->getObject ();
$this->exchangeRate->setCurrencyId($this->currency->getId());


in the executeIndexCurrency action, but without success.

How can i do it?

Thanks a lot
Jaime


Symfony 1.4
Re: How to create a link to this routing [message #102746 is a reply to message #102644 ] Mon, 19 July 2010 15:16 Go to previous messageGo to next message
sescandell  is currently offline sescandell
Messages: 65
Registered: December 2008
Location: France
Member
Hi Smile
Quote:


Hello! Thanks a lot for your help.. it worked perfectly! but now I have a question in order to finish it. When I add a new currency, the currency_id combobox appears without any selection.



Yes it is normal ... we don't ask Symfony to fill the field Very Happy

Quote:

But I want to use the generator.yml to define the currency_id field and to be populated with the actual currency identity.

Which generator.yml ? How did you generate your application or modules ? (because with what I give you, I didn't use the admin-generator ... so before give you an answer - or at least, trying to give you - I want to be sure you are using it Very Happy). And BTW, if you use the admin generator, how did you exactly implement my code (especialy the template modification) ?


Please, when you say "I try this code or this one" precise in wich file you made the modification Very Happy


With all of this, I think I will be able to give you the best answer possible Very Happy
Waiting for you Wink
Re: How to create a link to this routing [message #102779 is a reply to message #102746 ] Tue, 20 July 2010 01:25 Go to previous messageGo to next message
jstuardo  is currently offline jstuardo
Messages: 49
Registered: May 2010
Location: Santiago
Member
Hello again.... the generator.yml is the corresponding to the exchangeRate module.

This is the generator.yml file:

generator:
  class: sfDoctrineGenerator
  param:
    model_class:           ExchangeRate
    theme:                 admin
    non_verbose_templates: true
    with_show:             false
    singular:              ~
    plural:                ~
    route_prefix:          exchangeRate
    with_doctrine_route:   true
    actions_base_class:    sfActions

    config:
      actions: ~
      fields:
        exchange_date: { label: Fecha, attributes: { class: req-string req-date }, help: Fecha del cambio (requerido). }
        exchange_value: { label: Tasa de cambio, attributes: { size: 9, maxlength: 8, class: req-string req-numeric }, type: number, help: Valor del cambio (requerido). }
        created_at: { label: Fecha Creación, type: plain }
      list: ~
      filter:
        display: [ exchange_date ]
      form:    ~
      edit:
        display:
          General: [ exchange_date, exchange_value ]
          Información: [ created_at ]        
      new:
        display:
          General: [ exchange_date, exchange_value, currency_id ]


This is the actions file:

<?php
require_once dirname ( __FILE__ ) . '/../lib/exchangeRateGeneratorConfiguration.class.php';
require_once dirname ( __FILE__ ) . '/../lib/exchangeRateGeneratorHelper.class.php';

/**
 * exchangeRate actions.
 *
 * @package    SouthernBulbs
 * @subpackage exchangeRate
 * @author     DESYTEC
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class exchangeRateActions extends autoExchangeRateActions {
 	public function executeIndex(sfWebRequest $request) {
 		if ($request->getReferer() == null)
 			$this->getUser ()->setAttribute('currency_id', null);
 		
 		$id = $this->getUser ()->getAttribute('currency_id');
 		if ($id)
 		{
	 		$query = Doctrine_Query::create()
	 		         ->from('Currency')
	 		         ->where('id = ?', $id);
	 		$this->currency = $query->fetchOne();
	 		$this->retrieveList($request);
 		}
 		else
			$this->redirect('@currency');
 	}
	
	public function executeIndexCurrency(sfWebRequest $request) {
		$this->currency = $this->getRoute ()->getObject ();
		$this->getUser ()->setAttribute('currency_id', $this->currency->getId());
		
		$this->retrieveList($request);
	}

 	private function retrieveList(sfWebRequest $request)
 	{
		// sorting
		if ($request->getParameter ( 'sort' ) && $this->isValidSortColumn ( $request->getParameter ( 'sort' ) )) {
			$this->setSort ( array ($request->getParameter ( 'sort' ), $request->getParameter ( 'sort_type' ) ) );
		}
		
		// pager
		if ($request->getParameter ( 'page' )) {
			$this->setPage ( $request->getParameter ( 'page' ) );
		}
		
		$this->pager = $this->getPager ();
		$this->sort = $this->getSort ();
		
		// Este form es para el formulario "Nueva Tasa de Cambio"
		$this->form = $this->configuration->getForm ();
		$this->exchangeRate = $this->form->getObject ();
		$this->exchangeRate->setCurrencyId($this->currency->getId());
		$this->setTemplate ( 'index' );
 	}
	
	public function executeFilter(sfWebRequest $request) {
		$this->setPage ( 1 );
		
		if ($request->hasParameter ( '_reset' )) {
			$this->setFilters ( $this->configuration->getFilterDefaults () );
			
			$this->redirect ( '@exchangeRate' );
		}
		
		$this->filters = $this->configuration->getFilterForm ( $this->getFilters () );
		
		$this->filters->bind ( $request->getParameter ( $this->filters->getName () ) );
		if ($this->filters->isValid ()) {
			$this->setFilters ( $this->filters->getValues () );
			$this->redirect ( '@exchangeRate' );
		}
		
		$this->pager = $this->getPager ();
		$this->sort = $this->getSort ();
		
		// Este form es para el formulario "Nueva Tasa de Cambio"
		$this->form = $this->configuration->getForm ();
		$this->exchangeRate = $this->form->getObject ();
		$this->setTemplate ( 'index' );
	}
	
	public function executeCreate(sfWebRequest $request) {
		$this->form = $this->configuration->getForm ();
		$this->exchangeRate = $this->form->getObject ();
		
		$this->processForm ( $request, $this->form );
	}
	
	public function executeBatch(sfWebRequest $request) {
		$request->checkCSRFProtection ();
		
		if (! $ids = $request->getParameter ( 'ids' )) {
			$this->getUser ()->setFlash ( 'error', 'Debe seleccionar al menos 1 tasa de cambio.' );
			
			$this->redirect ( '@exchangeRate' );
		}
		
		if (! $action = $request->getParameter ( 'batch_action' )) {
			$this->getUser ()->setFlash ( 'error', 'Debe seleccionar una acción a ejecutar sobre los ítemes seleccionados.' );
			
			$this->redirect ( '@exchangeRate' );
		}
		
		if (! method_exists ( $this, $method = 'execute' . ucfirst ( $action ) )) {
			throw new InvalidArgumentException ( sprintf ( 'Debe crear un método "%s" para la acción "%s"', $method, $action ) );
		}
		
		if (! $this->getUser ()->hasCredential ( $this->configuration->getCredentials ( $action ) )) {
			$this->forward ( sfConfig::get ( 'sf_secure_module' ), sfConfig::get ( 'sf_secure_action' ) );
		}
		
		$validator = new sfValidatorDoctrineChoice ( array ('multiple' => true, 'model' => 'ExchangeRate' ) );
		try {
			// validate ids
			$ids = $validator->clean ( $ids );
			
			// execute batch
			$this->$method ( $request );
		} catch ( sfValidatorError $e ) {
			throw $e;
			$this->getUser ()->setFlash ( 'error', 'Ocurrió un problema al realizar la acción solicitada.' );
		}
		
		$this->redirect ( '@exchangeRate' );
	}
	
	protected function executeBatchDelete(sfWebRequest $request) {
		$ids = $request->getParameter ( 'ids' );
		
		$records = Doctrine_Query::create ()->from ( 'ExchangeRate' )->whereIn ( 'id', $ids )->execute ();
		
		foreach ( $records as $record ) {
			$record->delete ();
		}
		
		$this->getUser ()->setFlash ( 'notice', 'Las tasas de cambio seleccionadas fueron eliminadas correctamente.' );
		$this->redirect ( '@exchangeRate' );
	}
	
	protected function executeBatchPublish(sfWebRequest $request) {
		$ids = $request->getParameter ( 'ids' );
		
		$records = Doctrine_Query::create ()->from ( 'ExchangeRate' )->whereIn ( 'id', $ids )->execute ();
		
		foreach ( $records as $record ) {
			$record->publish ( 1 );
		}
		
		$this->getUser ()->setFlash ( 'notice', 'Las tasas de cambio seleccionadas fueron publicadas correctamente.' );
		$this->redirect ( '@exchangeRate' );
	}
	
	protected function executeBatchUnpublish(sfWebRequest $request) {
		$ids = $request->getParameter ( 'ids' );
		
		$records = Doctrine_Query::create ()->from ( 'ExchangeRate' )->whereIn ( 'id', $ids )->execute ();
		
		foreach ( $records as $record ) {
			$record->publish ( 0 );
		}
		
		$this->getUser ()->setFlash ( 'notice', 'Las tasas de cambio seleccionadas fueron despublicadas correctamente.' );
		$this->redirect ( '@exchangeRate' );
	}
	
	public function executeUpdate(sfWebRequest $request) {
		parent::executeUpdate ( $request );
	}
	
	protected function processForm(sfWebRequest $request, sfForm $form) {
		$form->bind ( $request->getParameter ( $form->getName () ), $request->getFiles ( $form->getName () ) );
		if ($form->isValid ()) {
			
			$notice = $form->getObject ()->isNew () ? 'La tasa de cambio fue creada correctamente.' : 'La tasa de cambio fue actualizada correctamente.';
			try {
				$exchangeRate = $form->save ();
			} catch ( Doctrine_Validator_Exception $e ) {
				
				$errorStack = $form->getObject ()->getErrorStack ();
				
				$message = get_class ( $form->getObject () ) . ' has ' . count ( $errorStack ) . " field" . (count ( $errorStack ) > 1 ? 's' : null) . " with validation errors: ";
				foreach ( $errorStack as $field => $errors ) {
					$message .= "$field (" . implode ( ", ", $errors ) . "), ";
				}
				$message = trim ( $message, ', ' );
				
				$this->getUser ()->setFlash ( 'error', $message );
				return sfView::SUCCESS;
			}
			
			$this->dispatcher->notify ( new sfEvent ( $this, 'admin.save_object', array ('object' => $exchangeRate ) ) );
			
			$this->getUser ()->setFlash ( 'notice', $notice );
			
	 		$query = Doctrine_Query::create()
	 		         ->from('Currency')
	 		         ->where('id = ?', $exchangeRate->getCurrencyId());
	 		$currency = $query->fetchOne();
			
			$this->redirect ( '@exchangeRate' );
		} else {
			$this->getUser ()->setFlash ( 'error', 'Existieron algunos errores al almacenar la tasa de cambio.', false );
			$this->pager = $this->getPager ();
			$this->sort = $this->getSort ();
			$this->setTemplate ( 'index' );
		}
	}
	
	protected function buildQuery() {
		$query = parent::buildQuery ();
		$rootAlias = $query->getRootAlias ();
		$query->andWhere ( $rootAlias . '.currency_id = ?', $this->currency->getId());
			
		return $query;
	}
}


And finally, I think, this is the form class:

<?php

/**
 * ExchangeRate form.
 *
 * @package    SouthernBulbs
 * @subpackage form
 * @author     DESYTEC
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ExchangeRateForm extends BaseExchangeRateForm {
	public function configure() {
		$this->widgetSchema ['exchange_date'] = new sfWidgetFormJQueryDate ( array ('date_widget' => new sfWidgetFormFilterInput ( array ('with_empty' => false, 'template' => '%input%' ) ), 'image' => '/images/icons/calendar.png', 'culture' => 'es' ) );
		$this->validatorSchema ['exchange_date'] = new sfValidatorDate(array('required' => true), array('invalid' => '"%value%" no es una fecha.', 'required' => 'La fecha es requerida.'));
		$this->validatorSchema ['exchange_value'] = new sfValidatorNumber(array('required' => true), array('invalid' => '"%value%" no es un número.', 'required' => 'El valor es requerido.'));
		
		//$this->setWidget('currency_id', new sfWidgetFormInputHidden(array(
		//	  )));
			  
		if ($this->isNew) {
			unset ( $this->widgetSchema ['created_at'] );
		} else {
			$this->setWidget ( 'created_at', new sfWidgetFormPlain ( array ('value' => $this->getObject ()->created_at ) ) );
			unset ( $this->validatorSchema ['created_at'] );
		}
	}
}


If you need more information, just ask for it.

Thanks four your patience Smile

Jaime


Symfony 1.4
Re: How to create a link to this routing [message #102950 is a reply to message #102644 ] Thu, 22 July 2010 17:15 Go to previous messageGo to next message
sescandell  is currently offline sescandell
Messages: 65
Registered: December 2008
Location: France
Member
Hi again Smile

For the time, wasn't really available this last time ... But I am still with you Very Happy

Sorry, there is something I do not understand. is that you who fill the action file like that ? I mean, normally, if you use the doctrine:generate-admin command, it will create an empty file ... (just to be sure, I am working with the same situation as you are Very Happy)
Re: How to create a link to this routing [message #102963 is a reply to message #102950 ] Fri, 23 July 2010 00:24 Go to previous messageGo to next message
jstuardo  is currently offline jstuardo
Messages: 49
Registered: May 2010
Location: Santiago
Member
I don't remember how that actions file was generated, but was automatic. The task you mention creates an empty actions file, but I used other task that created all CRUD operations. That way, the actions class inherits an auto generated class in cache. I cannot explain cleartly the process, but the fact is that I created the first CRUD operations that way (concerning a Category table) which created the actions files, some helpers, the forms, filters and the index page, from that moment on, I created empty files and then copied and pasted the code.

For example, as you see, I have some files in the lib folder (a helper and a class that handles configuration). If I use the task you talk about, all that is not created.

You can see the application I'm developing at http://qasb.desytec.com/backend.php/currency

When asked the first time, enter sbtest as login and password. Then, enter admin as login and password.

Thanks
Jaime


Symfony 1.4
Re: How to create a link to this routing [message #103082 is a reply to message #102644 ] Mon, 26 July 2010 13:29 Go to previous messageGo to next message
sescandell  is currently offline sescandell
Messages: 65
Registered: December 2008
Location: France
Member
Hi,

Ok, I don't really understand where the generator.yml came from, but ... it's not really important. You should be able to adapt the code by yourself I think.

So to do what you want, we have to add a new route and a new action:
Routing.yml add the following route:
exchangeRate_new_with_currency:
  url:     /myExchangeRateUrl/new/:id.:sf_format
  class:   sfDoctrineRoute
  options: { model: Currency, type: object }
  param:   { module: exchangeRate, action: newWithCurrency, sf_format: html }
  requirements: { id: \d+, sf_method: get }


In your action file add the following action:
public function executeNewWithCurrency(sfWebRequest $request)
{
  $exchangeRate = new ExchangeRate();
  $exchangeRate->setCurrency($this->getRoute()->getObject());
  $this->form   = new ExchangeRateForm($exchangeRate);
  
  $this->setTemplate('new');
}


And so in the template where you list your exchangeRates for a given Currency, you have to add the following link:
<a href="<?php echo url_for('exchangeRate_new_with_currency',$currency) ?>"><?php echo $currency ?></a>



I didn't try this, but the main idea is here.

Let me know if you need something better ...
Re: How to create a link to this routing [message #103100 is a reply to message #103082 ] Mon, 26 July 2010 19:25 Go to previous message
jstuardo  is currently offline jstuardo
Messages: 49
Registered: May 2010
Location: Santiago
Member
Hello... I have almost finished the currencies and exchange rates management. You can enter to http://qasb.desytec.com/backend.php/currency. In the first authentication box, please enter sbtest / sbtest. And in the second, admin / admin. In actions you can see the icon to load the exchange rates page.

All works but I want to make impossible for the user to choose a currency because the currency will be the selected one in the previous page. As you will see, a combobox appears in order to choose the currency.

Since I have the currency id when the page is loaded, the problem is reduced to know how can I convert that combobox to a hidden field and with that currency id in the value attribute.

I can convert that combobox in the configure method of the form, but I did not know how to set the value of the field to the currency id.

Please, this is the last help I ask you for Smile

Thanks a lot
Jaime

[Updated on: Mon, 26 July 2010 19:28]


Symfony 1.4
Previous Topic:Admin Generator - batch action question
Next Topic:Validate/save an embedded form based on a value in the parent form
Goto Forum:
  

powered by FUDforum - copyright ©2001-2004 FUD Forum Bulletin Board Software