How to access saved entity via metadata using parameters in the route - twig

I have an entity contact
<?php
namespace App\Entity;
use App\Repository\ContactRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=ContactRepository::class)
*/
class Contact
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=50)
*/
private $firstName;
/**
* #ORM\Column(type="string", length=50)
*/
private $lastName;
/**
* #ORM\Column(type="date", nullable=true)
*/
private $dob;
/**
* #ORM\Column(type="string", length=50)
*/
private $email;
/**
* #ORM\Column(type="string", length=15)
*/
private $phone;
public function getId(): ?int
{
return $this->id;
}
public function getFirstName(): ?string
{
return $this->firstName;
}
public function setFirstName(string $firstName): self
{
$this->firstName = $firstName;
return $this;
}
public function getLastName(): ?string
{
return $this->lastName;
}
public function setLastName(string $lastName): self
{
$this->lastName = $lastName;
return $this;
}
public function getDob(): ?\DateTimeInterface
{
return $this->dob;
}
public function setDob(?\DateTimeInterface $dob): self
{
$this->dob = $dob;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(string $phone): self
{
$this->phone = $phone;
return $this;
}
}
I want to select one (or more) contact with this URL: /c00210/readallbyparam/{routeProperty}/{routeValue}
For example: /c00210/readallbyparam/lastname/Mendelsohn
This should return 2 records:
Felix Mendelsohn
Fanny Mendelsohn
How do I write the render() function?
How do I write the twig instructions?
I suppose I should use the metadata, but I don't know
+++++++++++++++++++++++++++++++++++++++
here is the function in my controller
/**
* #Route("/c00210/readallbyparam/{routeProperty}/{routeValue}", name="c00210_read_all_by_param")
*/
public function findAllByparam( $routeProperty,$routeValue)
{
$property = $routeProperty;
$value = $routeValue;
$repository = $this->getDoctrine()->getRepository(Contact::class);
$contacts = $repository->findAll();
return $this->render('c00210/readbycriteria2.html.twig', [
'function' => 'find(<id>)',
'description' => 'finds the with the given Id',
'property' => $property,
'value' => $value,
'contacts' => $contacts,
]);
routeProperty should be a column name, and routeValue a column value
shoud be equivalent to
SELECT * FROM contacts WHERE lastname = 'Mendelsohn'

Related

Using Carbon diffForHumans in my model in laravel 8

I am using laravel 8 framework as my backend for my android application and I want to output time the same way instagram shows time but each time I use carbon diffForHumans it shows 2hours from now and I want it to show 1 minute ago, just now, 2 weeks ago,2 hours ago.
here is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Carbon\Carbon;
class News extends Model
{
use HasFactory;
protected $table = "news";
protected $fillable = [
'title',
'image',
'body'
];
protected $casts = [
'created_at' => 'datetime:d-m-Y',
'updated_at' => 'datetime:d-m-Y'
];
protected $appends=['published'];
public function getPublishedAttribute(){
return Carbon::createFromTimeStamp(strtotime($this->attributes['created_at']) )->diffForHumans();
}
}
here is my controller
<?php
namespace App\Http\Controllers;
use App\News;
use Illuminate\Http\Request;
class NewsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$allposts = News:://get()->sortByDesc(function($query){
// return $query->toArray(['id']);
//})->
all();
return response()->json(['newsitemlist' => $allposts], 200);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$allposts = News::find($id);
if (is_null($allposts)) {
return response()->json(['message' => "News not available"], 404);
}
return response()->json(['newsitemlist' => $allposts], 200);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$allposts = News::find($id);
if (is_null($allposts)) {
return response()->json(['message' => "News not available"], 404);
}
$allposts->delete();
return response()->json(['message' => "News Deleted Succesfully"], 200);
}
}
You can also use
public function getCreatedAtAttribute($value){
return Carbon::parse($value)->diffForHumans();
}
Based on Docs, this is what you need to do to modify created_at value. Its called Accessor
public function getCreatedAtAttribute($value){
return Carbon::createFromFormat('Y-m-d H:i:s', $value)->diffForHumans();
}
Also you can check more about Carbon API here

Symfony forms - Expected argument of type , "string" given at property path

I get this error message:
Expected argument of type "App\Entity\Artist or null", "string" given at property path "artist".
This is the code of my form in symfony
$builder
->add('date', DateType::class, [
'widget' => 'single_text'
])
->add('artist', TextType::class)
->add('City',TextType::class)
;
And this is the template:
{{ form_start(form)}}
{{ form_widget(form)}}
<button class="btn btn-secondary">{{ button|default('Enregistrer')}}</button>
{{ form_end(form)}}
Entity
class Artist
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=45)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Event", mappedBy="artist", cascade={"persist","remove"})
*/
private $events;
public function __construct()
{
$this->events = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(?string $name): self
{
$this->name = $name;
return $this;
}
/**
* #return Collection|Event[]
*/
public function getEvents(): Collection
{
return $this->events;
}
public function addEvent(Event $event): self
{
if (!$this->events->contains($event)) {
$this->events[] = $event;
$event->setArtist($this);
}
return $this;
}
public function removeEvent(Event $event): self
{
if ($this->events->contains($event)) {
$this->events->removeElement($event);
// set the owning side to null (unless already changed)
if ($event->getArtist() === $this) {
$event->setArtist(null);
}
}
return $this;
}
public function __toString()
{
return $this->name;
}
}
This is the error :
Uncaught PHP Exception Symfony\Component\PropertyAccess\Exception\InvalidArgumentException: "Expected argument of type "App\Entity\Artist or null", "string" given at property path "artist"." at D:\wamp64\www\app_music_events\vendor\symfony\property-access\PropertyAccessor.php line 173
{
"exception": {}
}
This is the controller
/**
* Method for editing an event
*
* #Route("/admin/edit/{id}", name="admin.edit", methods="GET|POST")
* #param Request $request
* #return \Symfony\Component\HttpFoundation\Response
*/
public function edit(Event $event, Request $request): Response
{
$form = $this->createForm(EventType::class, $event);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->em->flush();
$this->addFlash('success', 'Le concert a été modifié avec succès !');
return $this->redirectToRoute('admin.index');
}
return $this->render('admin/edit.html.twig', [
'event' => $event,
'form' => $form->createView()
]
);
}
I don't understand.
I do not have this problem when I do not specify Textype in the form.
What is the problem? Thanks
The problem is that you need to persist an Artist entity along with your Event. Symfony expects an Artist entity type and not a string. Try with EntityType::class instead of TextType::class
->add('artist', EntityType::class, [
'class' => Artist::class
]);
For more information on the EntityType field, please check the documentation

parse json and get attributes with rest controller java

I have this code, the entity is persistable I want to make it non persistable so I parse json file and get name and icon values and display them instead of getting this values from database so that is why I want to change this code
/**
* A Pcomponent.
*/
#Entity
#Table(name = "pcomponent")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Pcomponent implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "icon")
private String icon;
#Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public Pcomponent icon(String icon) {
this.icon = icon;
return this;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public Pcomponent name(String name) {
this.name = name;
return this;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pcomponent pcomponent = (Pcomponent) o;
if (pcomponent.id == null || id == null) {
return false;
}
return Objects.equals(id, pcomponent.id);
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "Pcomponent{" +
"id=" + id +
", icon='" + icon + "'" +
", name='" + name + "'" +
'}';
}
}
/**
* Spring Data JPA repository for the Pcomponent entity.
*/
public interface PcomponentRepository extends
JpaRepository<Pcomponent,Long> {
}
/**
* A DTO for the Pcomponent entity.
*/
public class PcomponentDTO implements Serializable {
private Long id;
private String icon;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PcomponentDTO pcomponentDTO = (PcomponentDTO) o;
if ( ! Objects.equals(id, pcomponentDTO.id)) {
return false;
}
return true;
}
#Override
public int hashCode() {
return Objects.hashCode(id);
}
#Override
public String toString() {
return "PcomponentDTO{" +
"id=" + id +
", icon='" + icon + "'" +
", name='" + name + "'" +
'}';
}
}
/**
* Mapper for the entity Pcomponent and its DTO PcomponentDTO.
*/
#Mapper(componentModel = "spring", uses = {})
public interface PcomponentMapper {
PcomponentDTO pcomponentToPcomponentDTO(Pcomponent pcomponent);
List<PcomponentDTO> pcomponentsToPcomponentDTOs(List<Pcomponent> pcomponents);
Pcomponent pcomponentDTOToPcomponent(PcomponentDTO pcomponentDTO);
List<Pcomponent> pcomponentDTOsToPcomponents(List<PcomponentDTO> pcomponentDTOs);
/**
* generating the fromId for all mappers if the databaseType is sql, as the class has relationship to it might need it, instead of
* creating a new attribute to know if the entity has any relationship from some other entity
*
* #param id id of the entity
* #return the entity instance
*/
default Pcomponent pcomponentFromId(Long id) {
if (id == null) {
return null;
}
Pcomponent pcomponent = new Pcomponent();
pcomponent.setId(id);
return pcomponent;
}
}
/**
* Service Implementation for managing Pcomponent.
*/
#Service
#Transactional
public class PcomponentService {
private final Logger log =
LoggerFactory.getLogger(PcomponentService.class);
private final PcomponentRepository pcomponentRepository;
private final PcomponentMapper pcomponentMapper;
public PcomponentService(PcomponentRepository pcomponentRepository, PcomponentMapper pcomponentMapper) {
this.pcomponentRepository = pcomponentRepository;
this.pcomponentMapper = pcomponentMapper;
}
/**
* Save a pcomponent.
*
* #param pcomponentDTO the entity to save
* #return the persisted entity
*/
public PcomponentDTO save(PcomponentDTO pcomponentDTO) {
log.debug("Request to save Pcomponent : {}", pcomponentDTO);
Pcomponent pcomponent = pcomponentMapper.pcomponentDTOToPcomponent(pcomponentDTO);
pcomponent = pcomponentRepository.save(pcomponent);
PcomponentDTO result = pcomponentMapper.pcomponentToPcomponentDTO(pcomponent);
return result;
}
/**
* Get all the pcomponents.
*
* #param pageable the pagination information
* #return the list of entities
*/
#Transactional(readOnly = true)
public Page<PcomponentDTO> findAll(Pageable pageable) {
log.debug("Request to get all Pcomponents");
Page<Pcomponent> result = pcomponentRepository.findAll(pageable);
return result.map(pcomponent -> pcomponentMapper.pcomponentToPcomponentDTO(pcomponent));
}
/**
* Get one pcomponent by id.
*
* #param id the id of the entity
* #return the entity
*/
#Transactional(readOnly = true)
public PcomponentDTO findOne(Long id) {
log.debug("Request to get Pcomponent : {}", id);
Pcomponent pcomponent = pcomponentRepository.findOne(id);
PcomponentDTO pcomponentDTO = pcomponentMapper.pcomponentToPcomponentDTO(pcomponent);
return pcomponentDTO;
}
/**
* Delete the pcomponent by id.
*
* #param id the id of the entity
*/
public void delete(Long id) {
log.debug("Request to delete Pcomponent : {}", id);
pcomponentRepository.delete(id);
}
}
/**
* REST controller for managing Pcomponent.
*/
#RestController
#RequestMapping("/api")
public class PcomponentResource {
private final Logger log =
LoggerFactory.getLogger(PcomponentResource.class);
private static final String ENTITY_NAME = "pcomponent";
private final PcomponentService pcomponentService;
public PcomponentResource(PcomponentService pcomponentService) {
this.pcomponentService = pcomponentService;
}
/**
* POST /pcomponents : Create a new pcomponent.
*
* #param pcomponentDTO the pcomponentDTO to create
* #return the ResponseEntity with status 201 (Created) and with body the new pcomponentDTO, or with status 400 (Bad Request) if the pcomponent has already an ID
* #throws URISyntaxException if the Location URI syntax is incorrect
*/
#PostMapping("/pcomponents")
#Timed
public ResponseEntity<PcomponentDTO> createPcomponent(#RequestBody PcomponentDTO pcomponentDTO) throws URISyntaxException {
log.debug("REST request to save Pcomponent : {}", pcomponentDTO);
if (pcomponentDTO.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new pcomponent cannot already have an ID")).body(null);
}
PcomponentDTO result = pcomponentService.save(pcomponentDTO);
return ResponseEntity.created(new URI("/api/pcomponents/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /pcomponents : Updates an existing pcomponent.
*
* #param pcomponentDTO the pcomponentDTO to update
* #return the ResponseEntity with status 200 (OK) and with body the updated pcomponentDTO,
* or with status 400 (Bad Request) if the pcomponentDTO is not valid,
* or with status 500 (Internal Server Error) if the pcomponentDTO couldnt be updated
* #throws URISyntaxException if the Location URI syntax is incorrect
*/
#PutMapping("/pcomponents")
#Timed
public ResponseEntity<PcomponentDTO> updatePcomponent(#RequestBody PcomponentDTO pcomponentDTO) throws URISyntaxException {
log.debug("REST request to update Pcomponent : {}", pcomponentDTO);
if (pcomponentDTO.getId() == null) {
return createPcomponent(pcomponentDTO);
}
PcomponentDTO result = pcomponentService.save(pcomponentDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, pcomponentDTO.getId().toString()))
.body(result);
}
/**
* GET /pcomponents : get all the pcomponents.
*
* #param pageable the pagination information
* #return the ResponseEntity with status 200 (OK) and the list of pcomponents in body
*/
#GetMapping("/pcomponents")
#Timed
public ResponseEntity<List<PcomponentDTO>> getAllPcomponents(#ApiParam Pageable pageable) {
log.debug("REST request to get a page of Pcomponents");
Page<PcomponentDTO> page = pcomponentService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/pcomponents");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /pcomponents/:id : get the "id" pcomponent.
*
* #param id the id of the pcomponentDTO to retrieve
* #return the ResponseEntity with status 200 (OK) and with body the pcomponentDTO, or with status 404 (Not Found)
*/
#GetMapping("/pcomponents/{id}")
#Timed
public ResponseEntity<PcomponentDTO> getPcomponent(#PathVariable Long id) {
log.debug("REST request to get Pcomponent : {}", id);
PcomponentDTO pcomponentDTO = pcomponentService.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(pcomponentDTO));
}
/**
* DELETE /pcomponents/:id : delete the "id" pcomponent.
*
* #param id the id of the pcomponentDTO to delete
* #return the ResponseEntity with status 200 (OK)
*/
#DeleteMapping("/pcomponents/{id}")
#Timed
public ResponseEntity<Void> deletePcomponent(#PathVariable Long id) {
log.debug("REST request to delete Pcomponent : {}", id);
pcomponentService.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
}

Twig Relationship with extra columns

I have a problem and don't know the best practice to solve it.
I want to have a form for my core data. The core data is all versionable.
I solved it with a GUID, to know the togetherness of the versions.
So now I have two versionable entities AgeClass and HighscoreList that can have a many-to-many relationship. The relationship has to be versionable, too, so I created a ReferenceEntity RefAgeClassHighscoreList. Now I have relationships with extra columns
valid-from [and]
valid-to
But now I don't know how I should build my form.
When I edit an AgeClass, all current (valid) HighscoreList items should be show as a checkbox.
But when I build the edit form, the values must be bound with a RefAgeClassHighscoreList entity.
I hope you understand my problem.
AgeClass:
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\DSV\Core\BaseDSVCoreDataRepository")
* */
class AgeClass extends BaseDSVCoreData
{
/**
* #ORM\Column(type="integer")
* #NotBlank()
* #var int
*/
protected $minAge;
/**
* #ORM\Column(type="integer")
* #NotBlank()
* #var int
*/
protected $maxAge;
/**
* #ORM\OneToMany(targetEntity="RefAgeClassHighscoreList", mappedBy="ageClass", cascade={"persist"})
* #var PersistentCollection
*/
private $ageClassHighscoreLists;
/**
* AgeClass constructor.
*/
function __construct()
{
$this->setGuid(GuidHelper::generateGuid());
$this->setValidFrom(new \DateTime());
}
/**
* #return int
*/
public function getMinAge()
{
return $this->minAge;
}
/**
* #param int $minAge
* #return AgeClass
*/
public function setMinAge($minAge)
{
$this->minAge = $minAge;
return $this;
}
/**
* #return int
*/
public function getMaxAge()
{
return $this->maxAge;
}
/**
* #param int $maxAge
* #return AgeClass
*/
public function setMaxAge($maxAge)
{
$this->maxAge = $maxAge;
return $this;
}
/**
* #return array
*/
public function getAgeClassHighscoreLists()
{
if($this->ageClassHighscoreLists == null)
return array();
return $this->ageClassHighscoreLists->toArray();
}
/**
* #param PersistentCollection $valuationClasses
* #return AgeClass
*/
public function seAgeClassHighscoreLists($valuationClasses)
{
$this->ageClassHighscoreLists = $valuationClasses;
return $this;
}
/**
* #return HighscoreList[]
*/
public function getHighscoreLists()
{
return array_map(
function ($ageClassHighscoreList) {
/** #var RefAgeClassHighscoreList $ageClassHighscoreList */
return $ageClassHighscoreList->getHighscoreList();
},
$this->getAgeClassHighscoreLists()
);
}
/**
* #param RefAgeClassHighscoreList $ageClassHighscoreList
* #return $this
*/
public function addAgeClassHighscoreList($ageClassHighscoreList)
{
if (!$this->ageClassHighscoreLists->contains($ageClassHighscoreList)) {
$this->ageClassHighscoreLists->add($ageClassHighscoreList);
$ageClassHighscoreList->setAgeClass($this);
}
return $this;
}
}
HighscoreList
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\DSV\Core\BaseDSVCoreDataRepository")
* */
class HighscoreList extends BaseDSVCoreData
{
/**
* #ORM\OneToMany(targetEntity="RefAgeClassHighscoreList", mappedBy="highscoreList", cascade={"persist"})
* #var PersistentCollection
*/
private $ageClassHighscoreLists;
function __construct()
{
$this->setGuid(GuidHelper::generateGuid());
}
/**
* #return PersistentCollection
*/
public function getAgeClassReferences()
{
return $this->ageClassHighscoreLists;
}
/**
* #param PersistentCollection $valuationClasses
* #return AgeClass
*/
public function setAgeClassReferences($valuationClasses)
{
$this->ageClassReferences = $valuationClasses;
return $this;
}
/**
* #return AgeClass[]
*/
public function getAgeClasses()
{
return array_map(
function ($ageClassHighscoreList) {
/** #var RefAgeClassHighscoreList $ageClassHighscoreList */
return $ageClassHighscoreList->getAgeClass();
},
$this->ageClassHighscoreLists->toArray()
);
}
/**
* #param RefAgeClassHighscoreList $ageClassHighscoreList
* #return HighscoreList
*/
public function addAgeClassReference($ageClassHighscoreList)
{
if (!$this->ageClassHighscoreLists->contains($ageClassHighscoreList)) {
$this->ageClassHighscoreLists->add($ageClassHighscoreList);
$ageClassHighscoreList->setHighscoreList($this);
}
return $this;
}
}
}
RefAgeClassHighscoreList
/**
* #ORM\Entity()
* */
class RefAgeClassHighscoreList implements IVersionable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(type="datetime")
*/
protected $validFrom;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $validTo;
/**
* #ORM\ManyToOne(targetEntity="AgeClass", inversedBy="highscoreListReferences")
* #ORM\JoinColumn(name="ageclass_id", referencedColumnName="id", nullable=FALSE)
*/
protected $ageClass;
/**
* #ORM\ManyToOne(targetEntity="highscoreList", inversedBy="ageClassReferences")
* #ORM\JoinColumn(name="highscorelist_id", referencedColumnName="id", nullable=FALSE)
*/
protected $highscoreList;
protected $hasChanges = false;
/**
* #see IVersionable
*/
public function getId()
{
return $this->id;
}
/**
* #see IVersionable
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #see IVersionable
*/
public function getGuid()
{
return null;
}
/**
* #see IVersionable
*/
public function setGuid($guid)
{
return $this;
}
/**
* #see IVersionable
*/
public function getValidFrom()
{
return $this->validFrom;
}
/**
* #see IVersionable
*/
public function setValidFrom($validFrom)
{
$this->validFrom = $validFrom;
return $this;
}
/**
* #see IVersionable
*/
public function getValidTo()
{
return $this->validTo;
}
/**
* #see IVersionable
*/
public function setValidTo($validTo)
{
$this->validTo = $validTo;
return $this;
}
/**
* #see IVersionable
*/
public function isValid()
{
return ($this->validTo == null);
}
/**
* #see IVersionable
*/
public function createNewVersion()
{
$newVersion = clone $this;
$newVersion->setValidFrom(new \DateTime());
return $newVersion;
}
/**
* #see IVersionable
*/
public function hasChanges()
{
return $this->hasChanges;
}
/**
* #return AgeClass
*/
public function getAgeClass()
{
return $this->ageClass;
}
/**
* #param AgeClass $ageClass
* #return RefAgeClassHighscoreList
*/
public function setAgeClass($ageClass)
{
$this->ageClass = $ageClass;
return $this;
}
/**
* #return HighscoreList
*/
public function getHighscoreList()
{
return $this->highscoreList;
}
/**
* #param HighscoreList $highscoreList
* #return RefAgeClassHighscoreList
*/
public function setHighscoreList($highscoreList)
{
$this->gighscoreList = $highscoreList;
return $this;
}
}
Well, you have a very recurrent and tedious problem. You can do an embed form with AgeClass and embedding a form for RefAgeClassHighscoreList type. In that embedded form you can have an attribute of type HighscoreList , the problem is that the default rendered component for what you need is a multi-select list of HighscoreList, you can see it putting the attribute multiple = true to the property of HighscoreList.
For transform that list to a check-box list you need to create a custom theme extending or adding new blocks to the default one provided by symfony. My advice is to create new widgets and rows for your specific form using the form name. You can find a lot of documentation about what I mention and need to get a small part of each one to do what you ask.
Hope all this clues help you.

java.lang.ClassCastException: com.rdb.entities.TblStaff cannot be cast to com.rdb.beans.UserManagedBean

I got some isses when try to use a login filter for my JSF, PrimeFaces web application.
Here is the stacktrace:
WARNING: StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.ClassCastException: com.rdb.entities.TblStaff cannot be cast to com.rdb.beans.UserManagedBean
at com.rdb.filter.AuthorizationFilter.doFilter(AuthorizationFilter.java:50)
AuthorizationFilter class:
public class AuthorizationFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
UserManagedBean auth = (UserManagedBean) req.getSession().getAttribute("staff");
if (auth != null && auth.isLoggedIn()) {
chain.doFilter(request, response);
} else {
HttpServletResponse res = (HttpServletResponse) response;
res.sendRedirect(req.getContextPath() + "/frontend/login.xhtml?faces-redirect=true");
}
}
}
My LoginBean
#ManagedBean
#SessionScoped
public class UserManagedBean extends TblStaff implements Serializable {
private TblStaff staff = null;
private String currentLogin;
private String username;
private String password;
private boolean loggedIn;
private ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
#ManagedProperty(value="#{navigationBean}")
private NavigationBean navigationBean;
/**
* Creates a new instance of UserManagedBean
*
*/
public UserManagedBean() {
super();
}
public String login() {
int isValid = doLogin();
if (isValid == 1) {
StaffBLL staffBLL = new StaffBLL();
staff = staffBLL.getStaffByUsername(username);
setSession("staff", staff);
String destinationUrl = null;
if (staff.getRoleId() == 1) {
loggedIn = true;
setCurrentLogin("admin");
destinationUrl = navigationBean.redirectToBackend();
} else if (staff.getRoleId() == 2) {
loggedIn = true;
setCurrentLogin("manager");
destinationUrl = navigationBean.redirectToManager();
} else if (staff.getRoleId() == 3) {
loggedIn = true;
setCurrentLogin("faculty");
destinationUrl = navigationBean.redirectToFaculty();
}
return destinationUrl;
} else {
return navigationBean.toLogin();
}
}
/**
* Set new session if try to logged in
*
* #param key
* #param value
*/
public static void setSession(String key, Object value) {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
session.setAttribute(key, value);
}
/**
* Get session if logged in
*
* #param key
* #return Session
*/
public static Object getSession(String key) {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
return session.getAttribute(key);
}
public String logout() {
loggedIn = false;
ec.invalidateSession();
setCurrentLogin(null);
return navigationBean.toFrontend();
}
public void logoutAdmin(ActionEvent actionEvent) throws IOException {
loggedIn = false;
ec.invalidateSession();
setCurrentLogin(null);
ec.redirect(ec.getRequestContextPath() + "/frontend/index.xhtml?faces-redirect=true");
}
public int doLogin() {
CallableStatement objCall;
SHAConverter hash = new SHAConverter();
int result = -1;
String[] params = new String[3];
params[0] = username;
params[1] = hash.hashBasic(password);
params[2] = null;
try {
objCall = SQLHelper.execute("procLogin", params);
result = objCall.getInt("Result");
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
return result;
}
#Override
public String getPassword() {
return password;
}
#Override
public void setPassword(String password) {
this.password = password;
}
#Override
public String getUsername() {
return username;
}
#Override
public void setUsername(String username) {
this.username = username;
}
public String getCurrentLogin() {
return currentLogin;
}
public void setCurrentLogin(String currentLogin) {
this.currentLogin = currentLogin;
}
public boolean isLoggedIn() {
return loggedIn;
}
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
public void setNavigationBean(NavigationBean navigationBean) {
this.navigationBean = navigationBean;
}
}
And NavigationBean
#ManagedBean
#SessionScoped
public class NavigationBean implements Serializable {
// private static final long serialVersionUID = 1520318172495977648L;
/**
* Redirect to login page.
*
* #return Login page name.
*/
public String redirectToLogin() {
return "/frontend/login.xhtml?faces-redirect=true";
}
/**
* Go to login page.
*
* #return Login page name.
*/
public String toLogin() {
return "/frontend/login.xhtml";
}
/**
* Redirect to backend.
*
* #return Backend page name.
*/
public String redirectToBackend() {
return "/backend/AdminHome.xhtml?faces-redirect=true";
}
/**
* Go to backend page.
*
* #return Backend page name.
*/
public String toBackend() {
return "/backend/AdminHome.xhtml";
}
/**
* Redirect to faculty.
*
* #return Faculty page name.
*/
public String redirectToFaculty() {
return "/frontend/faculty/index.xhtml?faces-redirect=true";
}
/**
* Go to faculty.
*
* #return Faculty page name.
*/
public String toFaculty() {
return "/frontend/faculty/index.xhtml";
}
/**
* Redirect to manager.
*
* #return Manager page name.
*/
public String redirectToManager() {
return "/frontend/manager/index.xhtml?faces-redirect=true";
}
/**
* Go to manager.
*
* #return Manager page name.
*/
public String toManager() {
return "/frontend/manager/index.xhtml";
}
/**
* Redirect to frontend.
*
* #return Frontend page name.
*/
public String redirectToFrontend() {
return "/frontend/index.xhtml?faces-redirect=true";
}
/**
* Go to frontend page.
*
* #return Frontend page name.
*/
public String toFrontend() {
return "/frontend/index.xhtml";
}
}
The stacktrace told me that I can't cast entities to a bean, but I MUST extend TblStaff in my login bean.
Can anyone give me a solution for this?

Resources