# Virtual Field Entity

**URL:** <https://discourse.cakephp.org/t/virtual-field-entity/8966>\
**Category:** Uncategorized\
**Created:** [February 6, 2021, 5:38pm UTC](https://discourse.cakephp.org/t/virtual-field-entity/8966 "2021-02-06T17:38:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![wtamayom](https://avatars.discourse-cdn.com/v4/letter/w/b2d939/32.png) [@wtamayom](https://discourse.cakephp.org/u/wtamayom)\
**Post date:** [February 6, 2021, 5:38pm UTC](https://discourse.cakephp.org/t/virtual-field-entity/8966/1 "2021-02-06T17:38:30Z")

</div>

Hi.

I want to create a virtual field in an entity Ciudade for use it in setDisplayField in Ciudadestable… But I need acces the nombre\_departamento located in Departamentos table.

Any way?

protected function \_getCiudadDepartamento()  
{  
return  
$this-\>nombre\_ciudad .  
’ - ’ .  
$this-\>Ciudades-\>Departamentos-\>nombre\_departamento;  
}

---

<div class="post-metadata">

**Author:** ![yousuo](https://avatars.discourse-cdn.com/v4/letter/y/898d66/32.png) [@yousuo](https://discourse.cakephp.org/u/yousuo)\
**Post date:** [February 7, 2021, 11:30am UTC](https://discourse.cakephp.org/t/virtual-field-entity/8966/2 "2021-02-07T11:30:49Z")

</div>

Your question isn’t specific enough. Is `Ciudade` linked to `Departamentos` (belongsTo, hasMany, etc). If linked, then just add a contain and use something `$this->Departamentos->nombre_departamento`

Maybe calling `TableRegistry::getTableLocator()->get('Departamentos');` to get the table, and then get your data.

An alternative. Maybe the `formatResults` feature may help you. [Docs](https://book.cakephp.org/3/en/orm/query-builder.html#adding-calculated-fields)

---

<div class="post-metadata">

**Author:** ![wtamayom](https://avatars.discourse-cdn.com/v4/letter/w/b2d939/32.png) [@wtamayom](https://discourse.cakephp.org/u/wtamayom)\
**Post date:** [February 9, 2021, 3:57pm UTC](https://discourse.cakephp.org/t/virtual-field-entity/8966/3 "2021-02-09T15:57:56Z")

</div>

I share the way I did solved this:

Entity Ciudade.php

protected function \_getCiudadDepartamento()  
{  
return  
$this-\>nombre\_ciudad .  
’ - (’ .  
$this-\>departamento-\>nombre\_departamento .  
‘)’ ;  
}

Ciudadestable.php  
$this-\>setDisplayField([‘ciudad\_departamento’]);

in the controller  
$ciudadEjecucionContratos = $this-\>Contratos-\>Ciudades-\>find(‘list’)-\>contain(‘Departamentos’);

Thanks.
