Hi everyone this is my first question!
I would like to have an Entity, with a field that indicates order, say EntityInstance1 with order 1, EntityInstance2 with order 2, EntityInstance3 with order 3... etc. Then for example I want to create a new instance, and give it order 2. So the result would be EntityInstance1 with order 1, EntityInstance4 with order 2, EntityInstance2 with order 3 and Entity Instance3 with order 4. An then let's say that I delete EntityInstance1, so I'll have EntityInstance4 with order 1, EntityInstance2 with order 2, EntityInstance3 with order 3. How could be this achieved??
Thanks!!!
Well... I really don't know why anybody would do something like that, but ok, it's realizeable. Let's think logical.
1) You have multiple instances of the same object => means you have a collection of object
2) A Collection has some kind of iterator
3) You can use the iterator to iterate over the list and update the instances orders.
So the easiest, but most expensive way to realize your vision is:
$objectCollection = $this -> get('doctrine.orm.entity_manager') -> getRepository('YOUR_ENTITY') -> findBy(array(),array('order','asc'));
$iterator = $objectCollection -> getArrayIterator();
$i = 1;
while($object = $iterator -> next()){
$object -> setOrder($i);
$i++;
}
$this -> get('doctrine.orm.entity_manager') -> flush();
Note: order can not be used as a property name. So you need another name and change it in the code sample, too.
Got it working! Using lifecycle events and bulk updates!
Here's my entity:
namespace LuchoNat\Icna\Website\BackendBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Meeting
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="LuchoNat\Icna\Website\BackendBundle\Entity\MeetingRepository")
*/
class Meeting {
/* ***************************************************************************************/
/* Properties ****************************************************************************/
/* ***************************************************************************************/
// Mapped
/**
*
* #var integer #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* #var string #ORM\Column(name="name", type="string", length=255, nullable=false)
* #Assert\NotBlank(message="El campo nombre es obligatorio")
*/
private $name;
/**
*
* #var integer #ORM\Column(name="production_order", type="integer", nullable=true)
*/
private $productionOrder;
/**
*
* #var integer #ORM\Column(name="staging_order", type="integer", nullable=true)
*/
private $stagingOrder;
/**
*
* #var boolean #ORM\Column(name="production_enabled", type="boolean", nullable=false)
*/
private $productionEnabled;
/**
*
* #var boolean #ORM\Column(name="staging_enabled", type="boolean", nullable=false)
*/
private $stagingEnabled;
/* ***************************************************************************************/
/* Getters & Setters *********************************************************************/
/* ***************************************************************************************/
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Meeting
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set productionOrder
*
* #param integer $productionOrder
* #return Meeting
*/
public function setProductionOrder($productionOrder) {
$this->productionOrder = $productionOrder;
return $this;
}
/**
* Get productionOrder
*
* #return integer
*/
public function getProductionOrder() {
return $this->productionOrder;
}
/**
* Set stagingOrder
*
* #param integer $stagingOrder
* #return Meeting
*/
public function setStagingOrder($stagingOrder) {
$this->stagingOrder = $stagingOrder;
return $this;
}
/**
* Get stagingOrder
*
* #return integer
*/
public function getStagingOrder() {
return $this->stagingOrder;
}
/**
* Set productionEnabled
*
* #param boolean $productionEnabled
* #return Meeting
*/
public function setProductionEnabled($productionEnabled) {
$this->productionEnabled = $productionEnabled;
return $this;
}
/**
* Get productionEnabled
*
* #return boolean
*/
public function getProductionEnabled() {
return $this->productionEnabled;
}
/**
* Set stagingEnabled
*
* #param boolean $stagingEnabled
* #return Meeting
*/
public function setStagingEnabled($stagingEnabled) {
$this->stagingEnabled = $stagingEnabled;
return $this;
}
/**
* Get stagingEnabled
*
* #return boolean
*/
public function getStagingEnabled() {
return $this->stagingEnabled;
}
/* ***************************************************************************************/
/* Other Methods *************************************************************************/
/* ***************************************************************************************/
}
Then, here is the EventListener
namespace LuchoNat\Icna\Website\BackendBundle\EventListener;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use LuchoNat\Icna\Website\BackendBundle\Entity\Meeting;
class MeetingIndexerSubscriber implements EventSubscriber
{
public function getSubscribedEvents() {
return array(
'prePersist',
'preUpdate',
'postRemove'
);
}
public function prePersist(LifecycleEventArgs $args) {
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
if($entity instanceof Meeting) {
$stagingOrder = $entity->getStagingOrder();
if(isset($stagingOrder)) {
$dql = "UPDATE LuchoNat\Icna\Website\BackendBundle\Entity\Meeting
m set m.stagingOrder = m.stagingOrder + 1
WHERE m.stagingOrder >= $stagingOrder";
$entityManager->createQuery($dql)->execute();
}
$productionOrder = $entity->getProductionOrder();
if(isset($productionOrder)) {
$dql = "UPDATE LuchoNat\Icna\Website\BackendBundle\Entity\Meeting
m set m.productionOrder = m.productionOrder + 1
WHERE m.productionOrder >= $productionOrder";
$entityManager->createQuery($dql)->execute();
}
}
}
public function preUpdate(LifecycleEventArgs $args) {
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
if($entity instanceof Meeting) {
if($args->hasChangedField('stagingOrder')) {
if($args->getNewValue('stagingOrder') > $args->getOldValue('stagingOrder')) {
$dql = 'UPDATE LuchoNat\Icna\Website\BackendBundle\Entity\Meeting
m set m.stagingOrder = m.stagingOrder - 1
WHERE m.stagingOrder > ' . $args->getOldValue('stagingOrder') .
' AND m.stagingOrder <= ' . $args->getNewValue('stagingOrder');
$entityManager->createQuery($dql)->execute();
}
if($args->getNewValue('stagingOrder') < $args->getOldValue('stagingOrder')) {
$dql = 'UPDATE LuchoNat\Icna\Website\BackendBundle\Entity\Meeting
m set m.stagingOrder = m.stagingOrder + 1
WHERE m.stagingOrder >= ' . $args->getNewValue('stagingOrder') .
' AND m.stagingOrder < ' . $args->getOldValue('stagingOrder');
$entityManager->createQuery($dql)->execute();
}
}
if($args->hasChangedField('productionOrder')) {
if($args->getNewValue('productionOrder') > $args->getOldValue('productionOrder')) {
$dql = 'UPDATE LuchoNat\Icna\Website\BackendBundle\Entity\Meeting
m set m.productionOrder = m.productionOrder - 1
WHERE m.productionOrder > ' . $args->getOldValue('productionOrder') .
' AND m.productionOrder <= ' . $args->getNewValue('productionOrder');
$entityManager->createQuery($dql)->execute();
}
if($args->getNewValue('productionOrder') < $args->getOldValue('productionOrder')) {
$dql = 'UPDATE LuchoNat\Icna\Website\BackendBundle\Entity\Meeting
m set m.productionOrder = m.productionOrder + 1
WHERE m.productionOrder >= ' . $args->getNewValue('productionOrder') .
' AND m.productionOrder < ' . $args->getOldValue('productionOrder');
$entityManager->createQuery($dql)->execute();
}
}
}
}
public function postRemove(LifecycleEventArgs $args) {
$entity = $args->getEntity();
$entityManager = $args->getEntityManager();
if($entity instanceof Meeting) {
$stagingOrder = $entity->getStagingOrder();
if(isset($stagingOrder)) {
$dql = "UPDATE LuchoNat\Icna\Website\BackendBundle\Entity\Meeting
m set m.stagingOrder = m.stagingOrder - 1
WHERE m.stagingOrder > $stagingOrder";
$entityManager->createQuery($dql)->execute();
}
$productionOrder = $entity->getProductionOrder();
if(isset($productionOrder)) {
$dql = "UPDATE LuchoNat\Icna\Website\BackendBundle\Entity\Meeting
m set m.productionOrder = m.productionOrder - 1
WHERE m.productionOrder > $productionOrder";
$entityManager->createQuery($dql)->execute();
}
}
}
}
And finally, in the config file:
services:
meeting.indexer_suscriber:
class: LuchoNat\Icna\Website\BackendBundle\EventListener\MeetingIndexerSubscriber
tags:
- { name: doctrine.event_subscriber, connection: default }
It works!!!
I used Symfony 2: How to Register Event Listeners and Subscribers and Doctrine 2: Events documentation!
Related
I already had a question regarding "importing" records and there data of different plugins/extensions. I got it working after adding the pid and implemented a query builder to get the data of a different plugin (or table in this case). But now I got the problem that the images of the "foreign" table/records or whatever is not included.. when I debug the var the image is only set to int 1. But they are not correctly included. What do I need to do to get this s*** working? :)
//MY CONTROLLER
<?php
namespace Formschoen\Mitarbeiterajax\Controller;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* MitarbeiterController
*/
class MitarbeiterController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController
{
/**
* mitarbeiterRepository
*
* #var \Formschoen\Mitarbeiterajax\Domain\Repository\MitarbeiterRepository
*/
protected $mitarbeiterRepository = null;
/**
* #param \Formschoen\Mitarbeiterajax\Domain\Repository\MitarbeiterRepository $mitarbeiterRepository
*/
public function injectMitarbeiterRepository(\Formschoen\Mitarbeiterajax\Domain\Repository\MitarbeiterRepository $mitarbeiterRepository)
{
$this->mitarbeiterRepository = $mitarbeiterRepository;
}
/**
* optionRecordRepository
*
* #var \Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository
*/
protected $optionRecordRepository;
/**
* #param \Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository
*/
public function injectOptionRecordRepository(\Sebkln\Ajaxselectlist\Domain\Repository\OptionRecordRepository $optionRecordRepository) {
$this->optionRecordRepository = $optionRecordRepository;
}
/**
* action list
*
* #return void
*/
public function listAction()
{
$mitarbeiters = $this->mitarbeiterRepository->findAll();
$this->view->assign('mitarbeiters', $mitarbeiters);
$this->view->assign("currentPageID", $GLOBALS['TSFE']->id);
$options['autohaus'] = array(
1 => 'some strings'
);
$options['abteilung'] = array(
1 => 'some strings'
);
$this->view->assign('options', $options);
}
/**
* action callAjax
*
* #param \Formschoen\Mitarbeiterajax\Domain\Model\Mitarbeiter $mitarbeiter
* #return void
*/
public function callAjaxAction(\Formschoen\Mitarbeiterajax\Domain\Model\Mitarbeiter $mitarbeiter)
{
$optionRecords = $this->optionRecordRepository->findAll();
$arguments = $this->request->getArguments();
$selectedAutohaus = $arguments['autohaus'];
$selectedAbteilung = $arguments['abteilung'];
if ($selectedAbteilung == null && $selectedAutohaus == null) {
echo("Bitte ein Autohaus auswählen / eine Abteilung.");
} else if ($selectedAbteilung == null) {
$autohausResult = $this->mitarbeiterRepository->findAutohaus($selectedAutohaus);
$this->view->assign('autohausResult', $autohausResult);
} else {
$mitarbeiterResult = $this->mitarbeiterRepository->findByFilter($selectedAutohaus, $selectedAbteilung);
$this->view->assign('mitarbeiterResult', $mitarbeiterResult);
}
$this->contentObj = $this->configurationManager->getContentObject();
$images=$this->getFileReferences($this->contentObj->data['uid']);
$this->view->assign('images', $images);
}
}
//MY REPOSITORY
<?php
namespace Formschoen\Mitarbeiterajax\Domain\Repository;
/**
* The repository for Mitarbeiters
*/
class MitarbeiterRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
/**
* #param $selectedAutohaus
* #param $selectedAbteilung
*/
public function findByFilter($selectedAutohaus,$selectedAbteilung){
$query = $this->createQuery();
$result = $query->matching($query->logicalAnd(
$query->equals('autohausName', $selectedAutohaus),
$query->equals('abteilung', $selectedAbteilung)
))
->execute();
return $result;
}
/**
* #param $uid
*/
public function findAutohaus($uid)
{
$queryBuilder = $this->objectManager->get(\TYPO3\CMS\Core\Database\ConnectionPool::class)
->getConnectionForTable('tx_ajaxselectlist_domain_model_optionrecord')->createQueryBuilder();
$queryBuilder
->select('*')
->from('tx_ajaxselectlist_domain_model_optionrecord')
->where(
$queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($uid))
);
$result = $queryBuilder->execute()->fetchAll();
if ($returnRawQueryResult) {
$dataMapper = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper::class);
return $dataMapper->map($this->objectType, $result);
}
return $result;
}
}
Why dont you just replace this
$autohausResult = $this->mitarbeiterRepository->findAutohaus($selectedAutohaus);
with this
$autohausResult = $this->optionRecordRepository->findByUid($selectedAutohaus);
This way TYPO3 will construct the Models and you will get the image they way you want it
I am trying to use this but keep getting an error message:
After editing the file on the web page the only thing showing up is "[".
Can anyone please advise me on how to resolve my issue.
I am a first year student I am not very experienced. This is my code:
<?php
include('forecast.io.php');
$apiKeyParam = $_GET["apiKey"];
$latParam = $_GET["lat"];
$lonParam = $_GET["lon"];
$unitsParam = $_GET["units"];
$langParam = (isset($_GET["lang"]) ? $_GET["lang"] : null);
$units = 'us'; // Can be set to 'us', 'si', 'ca', 'uk' or 'auto' (see forecast.io API); default is auto
$lang = 'en'; // Can be set to 'en', 'de', 'pl', 'es', 'fr', 'it', 'tet' or 'x-pig-latin' (see forecast.io API); default is 'en'
if($unitsParam != "") {
$units = $unitsParam;
}
if($langParam != "") {
$lang = $langParam;
}
//error_log(date(DATE_RFC822)." -- api=".$apiKeyParam.",lat=".$latParam.",lon=".$lonParam.",units=".$units.",lang=".$lang."\n", 3, '/home/weather.log');
$forecast = new ForecastIO($apiKeyParam, $units, $lang);
$condition = $forecast;
echo "CURRENT_TEMP=".round($condition->getTemperature())."\n";
echo "CURRENT_HUMIDITY=".($condition->getHumidity()*100)."\n";
echo "CURRENT_ICON=".($condition->getIcon())."\n";
echo "CURRENT_SUMMARY=".$condition->getSummary()."\n";
$conditions_week = $forecast->getForecastWeek($latParam, $lonParam);
echo "MAX_TEMP_TODAY=".round($conditions_week[0]->getMaxTemperature()) . "\n";
echo "MIN_TEMP_TODAY=".round($conditions_week[0]->getMinTemperature()) . "\n";
echo "ICON_TODAY=".$conditions_week[0]->getIcon()."\n";
echo "SUMMARY_TODAY=".$conditions_week[0]->getSummary()."\n";
echo "MAX_TEMP_TOMORROW=" . round($conditions_week[1]->getMaxTemperature()) . "\n";
echo "ICON_TOMORROW=".$conditions_week[1]->getIcon()."\n";
echo "MIN_TEMP_TOMORROW=".round($conditions_week[1]->getMinTemperature()) . "\n";
echo "SUMMARY_TODAY=".$conditions_week[1]->getSummary()."\n";
?>
This is my forecast.io.php:
<?php
/**
* Helper Class for forecast.io webservice
*/
class ForecastIO
{
private $api_key;
private $units;
private $language;
const API_ENDPOINT ='https://darksky.net/forecast/53.2789,-9.0109/uk12/en';
/**
* Create a new instance
*
* #param String $api_key
* #param String $units
* #param String $language
*/
function __construct($api_key, $units = 'auto', $language = 'en')
{
$this->api_key = $api_key;
$this->units = $units;
$this->language = $language;
}
/**
* #return string
*/
public function getUnits()
{
return $this->units;
}
/**
* #param string $units
*/
public function setUnits($units)
{
$this->units = $units;
}
/**
* #return string
*/
public function getLanguage()
{
return $this->language;
}
/**
* #param string $language
*/
public function setLanguage($language)
{
$this->language = $language;
}
private function requestData($latitude, $longitude, $timestamp = false, $exclusions = false)
{
$validUnits = array('auto', 'us', 'si', 'ca', 'uk');
if (in_array($this->units, $validUnits)) {
$request_url = self::API_ENDPOINT .
$this->api_key . '/' .
$latitude . ',' . $longitude .
($timestamp ? ',' . $timestamp : '') .
'?units=' . $this->units . '&lang=' . $this->language .
($exclusions ? '&exclude=' . $exclusions : '');
/**
* Use Buffer to cache API-requests if initialized
* (if not, just get the latest data)
*
* More info: http://git.io/FoO2Qw
*/
if (class_exists('Buffer')) {
$cache = new Buffer();
$content = $cache->data($request_url);
} else {
$content = file_get_contents($request_url);
}
} else {
return false;
}
if (!empty($content)) {
return json_decode($content);
} else {
return false;
}
}
/**
* Will return the current conditions
*
* #param float $latitude
* #param float $longitude
* #return \ForecastIOConditions|boolean
*/
public function getCurrentConditions($latitude, $longitude)
{
$data = $this->requestData($latitude, $longitude);
}
/**
* Will return historical conditions for day of given timestamp
*
* #param float $latitude
* #param float $longitude
* #param int $timestamp
* #return \ForecastIOConditions|boolean
*/
public function getHistoricalConditions($latitude, $longitude, $timestamp)
{
$exclusions = 'currently,minutely,hourly,alerts,flags';
$data = $this->requestData($latitude, $longitude, $timestamp, $exclusions);
if ($data !== false) {
return new ForecastIOConditions($data->daily->data[0]);
} else {
return null;
}
}
/**
* Will return conditions on hourly basis for today
*
* #param type $latitude
* #param type $longitude
* #return \ForecastIOConditions|boolean
*/
public function getForecastToday($latitude, $longitude)
{
$data = $this->requestData($latitude, $longitude);
if ($data !== false) {
$conditions = array();
$today = date('Y-m-d');
foreach ($data->hourly->data as $raw_data) {
if (date('Y-m-d', $raw_data->time) == $today) {
$conditions[] = new ForecastIOConditions($raw_data);
}
}
return $conditions;
} else {
return false;
}
}
/**
* Will return daily conditions for next seven days
*
* #param float $latitude
* #param float $longitude
* #return \ForecastIOConditions|boolean
*/
public function getForecastWeek($latitude, $longitude)
{
$data = $this->requestData($latitude, $longitude);
if ($data !== false) {
$conditions = array();
foreach ($data->daily->data as $raw_data) {
$conditions[] = new ForecastIOConditions($raw_data);
}
return $conditions;
} else {
return false;
}
}
}
/**
* Wrapper for get data by getters
*/
class ForecastIOConditions
{
private $raw_data;
function __construct($raw_data)
{
$this->raw_data = $raw_data;
}
/**
* Will return the temperature
*
* #return String
*/
function getTemperature()
{
return $this->raw_data->temperature;
}
/**
* get the min temperature
*
* only available for week forecast
*
* #return type
*/
function getMinTemperature()
{
return $this->raw_data->temperatureMin;
}
/**
* get max temperature
*
* only available for week forecast
*
* #return type
*/
function getMaxTemperature()
{
return $this->raw_data->temperatureMax;
}
/**
* get apparent temperature (heat index/wind chill)
*
* only available for current conditions
*
* #return type
*/
function getApparentTemperature()
{
return $this->raw_data->apparentTemperature;
}
/**
* Get the summary of the conditions
*
* #return String
*/
function getSummary()
{
return $this->raw_data->summary;
}
/**
* Get the icon of the conditions
*
* #return String
*/
function getIcon()
{
return $this->raw_data->icon;
}
/**
* Get the time, when $format not set timestamp else formatted time
*
* #param String $format
* #return String
*/
function getTime($format = null)
{
if (!isset($format)) {
return $this->raw_data->time;
} else {
return date($format, $this->raw_data->time);
}
}
/**
* Get the pressure
*
* #return String
*/
function getPressure()
{
return $this->raw_data->pressure;
}
/**
* Get the dew point
*
* Available in the current conditions
*
* #return String
*/
function getDewPoint()
{
return $this->raw_data->dewPoint;
}
/**
* get humidity
*
* #return String
*/
function getHumidity()
{
return $this->raw_data->humidity;
}
/**
* Get the wind speed
*
* #return String
*/
function getWindSpeed()
{
return $this->raw_data->windSpeed;
}
/**
* Get wind direction
*
* #return type
*/
function getWindBearing()
{
return $this->raw_data->windBearing;
}
/**
* get precipitation type
*
* #return type
*/
function getPrecipitationType()
{
return $this->raw_data->precipType;
}
/**
* get the probability 0..1 of precipitation type
*
* #return type
*/
function getPrecipitationProbability()
{
return $this->raw_data->precipProbability;
}
/**
* Get the cloud cover
*
* #return type
*/
function getCloudCover()
{
return $this->raw_data->cloudCover;
}
/**
* get sunrise time
*
* only available for week forecast
*
* #param String $format String to format date pph date
*
* #return type
*/
function getSunrise($format = null)
{
if (!isset($format)) {
return $this->raw_data->sunriseTime;
} else {
return date($format, $this->raw_data->sunriseTime);
}
}
/**
* get sunset time
*
* only available for week forecast
*
* #param String $format String to format date pph date
*
* #return type
*/
function getSunset($format = null)
{
if (!isset($format)) {
return $this->raw_data->sunsetTime;
} else {
return date($format, $this->raw_data->sunsetTime);
}
}
}
Where am I going wrong? It's line 19 causing the issue.
In your code method getCurrentConditions is a void method and doesn't return anything. Update the method content to a something similar as getHistoricalConditions where you instantiate ForecastIOConditions class and return it.
Do note that your code may still fail unless the method is guaranteed to return a value and you should wrap it in an if statement.
$condition = $forecast->getCurrentConditions($latParam, $lonParam);
if ($condition) {
echo "CURRENT_TEMP=".round($condition->getTemperature())."\n";
}
Line (18):
$condition = $forecast->getCurrentConditions($latParam, $lonParam);
ought to return an instance of class ForecastIOConditions as promised in the comment block above the definition. At the moment, it doesn't so the call to the member function getTemperature causes the error.
EDIT in the light of edited question:
These lines:
$forecast = new ForecastIO($apiKeyParam, $units, $lang);
$condition = $forecast->getCurrentConditions($latParam, $lonParam);
echo "CURRENT_TEMP=".round($condition->getTemperature())."\n";
are still wrong. $forecast does now contain an instance of ForecastIO, which is what $forecast->getCurrentConditions(...) should be returning. So, in order to take your code a stage further, change the second line above to:
$condition = $forecast
Once you've got something working, you fix getCurrentConditions(..) to make it return the instance of ForecastIO.
So, i am new to Symfony and i'm trying to create a functional calendar based application with events rendered from the database using calendar-bundle.
Passing with the documentation i was able to make a relationship between users and events rendered on the calendar but i'm stuck passing particular data, more exactly the user name.
Below is it shown the EventEntity which is responsible for calendar event's details.
<?php
namespace ADesigns\CalendarBundle\Entity;
/**
* Class for holding a calendar event's details.
*
* #author Mike Yudin <mikeyudin#gmail.com>
*/
class EventEntity
{
/**
* #var mixed Unique identifier of this event (optional).
*/
protected $id;
/**
* #var string Title/label of the calendar event.
*/
protected $title;
/**
* #var string URL Relative to current path.
*/
protected $url;
/**
* #var string HTML color code for the bg color of the event label.
*/
protected $bgColor;
/**
* #var string HTML color code for the foregorund color of the event label.
*/
protected $fgColor;
/**
* #var string css class for the event label
*/
protected $cssClass;
/**
* #var \DateTime DateTime object of the event start date/time.
*/
protected $startDatetime;
/**
* #var \DateTime DateTime object of the event end date/time.
*/
protected $endDatetime;
/**
* #var boolean Is this an all day event?
*/
protected $allDay = false;
/**
* #var array Non-standard fields
*/
protected $otherFields = array();
public function __construct($title, \DateTime $startDatetime, \DateTime $endDatetime = null, $allDay = false)
{
$this->title = $title;
$this->startDatetime = $startDatetime;
$this->setAllDay($allDay);
if ($endDatetime === null && $this->allDay === false) {
throw new \InvalidArgumentException("Must specify an event End DateTime if not an all day event.");
}
$this->endDatetime = $endDatetime;
}
/**
* Convert calendar event details to an array
*
* #return array $event
*/
public function toArray()
{
$event = array();
if ($this->id !== null) {
$event['id'] = $this->id;
}
$event['title'] = $this->title;
$event['start'] = $this->startDatetime->format("Y-m-d\TH:i:sP");
if ($this->url !== null) {
$event['url'] = $this->url;
}
if ($this->bgColor !== null) {
$event['backgroundColor'] = $this->bgColor;
$event['borderColor'] = $this->bgColor;
}
if ($this->fgColor !== null) {
$event['textColor'] = $this->fgColor;
}
if ($this->cssClass !== null) {
$event['className'] = $this->cssClass;
}
if ($this->endDatetime !== null) {
$event['end'] = $this->endDatetime->format("Y-m-d\TH:i:sP");
}
$event['allDay'] = $this->allDay;
foreach ($this->otherFields as $field => $value) {
$event[$field] = $value;
}
return $event;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
public function setUrl($url)
{
$this->url = $url;
}
public function getUrl()
{
return $this->url;
}
public function setBgColor($color)
{
$this->bgColor = $color;
}
public function getBgColor()
{
return $this->bgColor;
}
public function setFgColor($color)
{
$this->fgColor = $color;
}
public function getFgColor()
{
return $this->fgColor;
}
public function setCssClass($class)
{
$this->cssClass = $class;
}
public function getCssClass()
{
return $this->cssClass;
}
public function setStartDatetime(\DateTime $start)
{
$this->startDatetime = $start;
}
public function getStartDatetime()
{
return $this->startDatetime;
}
public function setEndDatetime(\DateTime $end)
{
$this->endDatetime = $end;
}
public function getEndDatetime()
{
return $this->endDatetime;
}
public function setAllDay($allDay = false)
{
$this->allDay = (boolean) $allDay;
}
public function getAllDay()
{
return $this->allDay;
}
/**
* #param string $name
* #param string $value
*/
public function addField($name, $value)
{
$this->otherFields[$name] = $value;
}
/**
* #param string $name
*/
public function removeField($name)
{
if (!array_key_exists($name, $this->otherFields)) {
return;
}
unset($this->otherFields[$name]);
}
}
Besides this i have the CalendarEventListener.php which is responsible for data sent to render on the calendar:
<?php
namespace AppBundle\EventListener;
use ADesigns\CalendarBundle\Event\CalendarEvent;
use ADesigns\CalendarBundle\Entity\EventEntity;
use Doctrine\ORM\EntityManager;
class CalendarEventListener
{
private $entityManager;
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function loadEvents(CalendarEvent $calendarEvent)
{
$startDate = $calendarEvent->getStartEventDate();
$endDate = $calendarEvent->getEndEventDate();
// The original request so you can get filters from the calendar
// Use the filter in your query for example
$request = $calendarEvent->getRequest();
$filter = $request->get('filter');
// load events using your custom logic here,
// for instance, retrieving events from a repository
$companyEvents = $this->entityManager->getRepository('AppBundle:companyEvents')
->createQueryBuilder('companyEvents')
->where('companyEvents.startEventDate BETWEEN :startEventDate and :endEventDate')
->setParameter('startEventDate', $startDate->format('Y-m-d H:i:s'))
->setParameter('endEventDate', $endDate->format('Y-m-d H:i:s'))
->getQuery()->getResult();
// $companyEvents and $companyEvent in this example
// represent entities from your database, NOT instances of EventEntity
// within this bundle.
//
// Create EventEntity instances and populate it's properties with data
// from your own entities/database values.
foreach($companyEvents as $companyEvent) {
$eventEntity = new EventEntity($companyEvent->getEventName(),
//
$companyEvent->getStartEventDate(),
$companyEvent->getEndEventDate()
,null, true);
//optional calendar event settings
$eventEntity->setAllDay(true); // default is false, set to true if this is an all day event
$eventEntity->setBgColor('#3366ff'); //set the background color of the event's label
$eventEntity->setFgColor('#FFFFFF'); //set the foreground color of the event's label
$eventEntity->setUrl('http://www.google.com'); // url to send user to when event label is clicked
$eventEntity->setCssClass('my-custom-class'); // a custom class you may want to apply to event labels
//finally, add the event to the CalendarEvent for displaying on the calendar
$calendarEvent->addEvent($eventEntity);
}
}
}
And the companyEvents entity for structuring events:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="companyEvents")
*/
class companyEvents
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* events are created by users
* #ORM\ManyToOne(targetEntity="User", inversedBy="events")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
/**
* #ORM\Column(name="event_name")
*/
private $eventName;
/**
* #ORM\Column(name="event_date", type="datetime")
*/
private $eventDate;
/**
* #ORM\Column(name="startEventDate", type="datetime")
*/
private $startEventDate;
/**
* #ORM\Column(name="endEventDate", type="datetime")
*/
private $endEventDate;
/**
* Set eventName
*
* #param string $eventName
*
* #return companyEvents
*/
public function setEventName($eventName)
{
$this->eventName = $eventName;
return $this;
}
/**
* Get eventName
*
* #return string
*/
public function getEventName()
{
return $this->eventName;
}
/**
* Set eventDate
*
* #param string $eventDate
*
* #return CompanyEvents
*/
public function setEventDate($eventDate)
{
$this->eventDate = $eventDate;
return $this;
}
/**
* Get eventDate
*
* #return string
*/
public function getEventDate()
{
return $this->eventDate;
}
/**
* Set start event date
* #param string $startEventDate
*
* #return companyEvents
*/
public function setStartEventDate($startEventDate)
{
$this->startEventDate = $startEventDate;
return $this;
}
/**
*Get start event date
* #return string
*/
public function getStartEventDate()
{
return $this->startEventDate;
}
/**
* Set start event date
* #param string $endEventDate
*
* #return companyEvents
*/
public function setEndEventDate($endEventDate)
{
$this->endEventDate = $endEventDate;
return $this;
}
/**
*Get start event date
* #return string
*/
public function getEndEventDate()
{
return $this->endEventDate;
}
/**
* set user relationship
* #param string $user_id
*
* #return companyEvents
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* #return string
*/
public function getUser()
{
return $this->user;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
So, my problem is that instead of getEventName passed here:
$eventEntity = new EventEntity($companyEvent->getEventName(),
$companyEvent->getStartEventDate(),
$companyEvent->getEndEventDate()
,null, true);
i want to pass the particular user name which belongs to the specific event but when i change the getEventName() (WHICH RENDERS THE TITLE OF THE EVENT) with any other function (i have tried to even pass just the user_id from the entity), nothing else is shown in the calendar without dumping any error.
Any hints on resolving this problem will be hardly appreciated :) !
If you want to render the username in the event's title you can change the getEventName method to return the user name:
public function getEventName()
{
return $this->user->getUsername();
}
This way you won't have to change the CalendarEventListener code.
Remember to remove the eventName property and it's setter method from the companyEventsentity. You should also name the entity CamelCased and in the singular, like this CompanyEvent.
For my project, I have a workspace (kind of a user) with many projects and I am wondering if there is a way to override the default Doctrine query for when I call $workspace->getProjects() to only fetch the active projects only (not the archived one). This way I won't have to filter my collection and it will reduce the size of the returned data from the database.
/**
* Acme\DemoBundle\Entity\Workspace
*
* #ORM\Table()
* #ORM\Entity
*/
class Workspace {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
private $id;
/**
* #var ArrayCollection $projects
*
* #ORM\OneToMany(targetEntity="Project", mappedBy="workspace")
*/
private $projects;
/**
* Add projects
*
* #param Project $projects
* #return Workspace
*/
public function addProject( Project $projects ) {
$this->projects[] = $projects;
return $this;
}
/**
* Remove projects
*
* #param Project $projects
*/
public function removeProject( Project $projects ) {
$this->projects->removeElement( $projects );
}
/**
* Get projects
*
* #return Collection
*/
public function getProjects() {
return $this->projects;
}
You will have to write your own method in the Entity Repository Class.
http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
To do that, you can use criteria.
Here is an exemple from the doctrine doc, to adapt to your needs
use Doctrine\Common\Collections\Criteria;
$criteria = Criteria::create()
->where(Criteria::expr()->eq("birthday", "1982-02-17"))
->orderBy(array("username" => Criteria::ASC))
->setFirstResult(0)
->setMaxResults(20)
;
$birthdayUsers = $object-getUsers()->matching($criteria);
You can create some listener, and catch doctrine events: http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/event-listeners.html
And modify your query before execute as you wish;
Example from Doctrine docs, for custom hook on delete:
<?php
class UserListener extends Doctrine_EventListener
{
/**
* Skip the normal delete options so we can override it with our own
*
* #param Doctrine_Event $event
* #return void
*/
public function preDelete( Doctrine_Event $event )
{
$event->skipOperation();
}
/**
* Implement postDelete() hook and set the deleted flag to true
*
* #param Doctrine_Event $event
* #return void
*/
public function postDelete( Doctrine_Event $event )
{
$name = $this->_options['name'];
$event->getInvoker()->$name = true;
$event->getInvoker()->save();
}
/**
* Implement preDqlDelete() hook and modify a dql delete query so it updates the deleted flag
* instead of deleting the record
*
* #param Doctrine_Event $event
* #return void
*/
public function preDqlDelete( Doctrine_Event $event )
{
$params = $event->getParams();
$field = $params['alias'] . '.deleted';
$q = $event->getQuery();
if ( ! $q->contains( $field ) )
{
$q->from('')->update( $params['component'] . ' ' . $params['alias'] );
$q->set( $field, '?', array(false) );
$q->addWhere( $field . ' = ?', array(true) );
}
}
/**
* Implement preDqlDelete() hook and add the deleted flag to all queries for which this model
* is being used in.
*
* #param Doctrine_Event $event
* #return void
*/
public function preDqlSelect( Doctrine_Event $event )
{
$params = $event->getParams();
$field = $params['alias'] . '.deleted';
$q = $event->getQuery();
if ( ! $q->contains( $field ) )
{
$q->addWhere( $field . ' = ?', array(false) );
}
}
}
I think you can put your logic inside the getter method itself
public function getProjects() {
$filtered_projects = array()
foreach($this->projects as $project)
{
// Your logic here
// e.g.
// if($project->getIsActive()){
// $filtered_projects[] = $project;
// }
}
return $filtered_projects;
}
I recently moved one of my sites to a new dedicated server running the latest version of PHP. In my php-based Knowledgebase section of the site, I am getting the following error:
Strict Standards: Declaration of API_RATING::multiDelete() should be compatible with API::multiDelete($ids = 0) in /home/givebrad/public_html/kb/lib/api/class.rating.php on line 156
Line 156 is the last closing } at the bottom of the file. Below is the code for class-rating.php. Can anyone help me out to figure out how to fix this?
<?php
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'class.api.php');
class API_RATING extends API
{
var $rateid = 0;
var $questionid = 0;
var $ip = '';
var $ratedat = '';
var $fields = array (
'rateid',
'questionid',
'ip',
'ratedat',
'ratingemail',
'ratingmessage'
);
var $pk = 'rateid';
/**
* create
* create a new rating in the database
*
* #return bool was the creation successful ?
*/
function create()
{
$_POST['ratedat'] = date('Y-m-d H:i:s');
$_POST['ip'] = $_SERVER['REMOTE_ADDR'];
return parent::create();
}
/**
* multiDelete
* Delete multiple rating ids. Update each associated question.
*
* #return bool was the delete successful?
*/
function multiDelete($ids) {
//Get the question ids
$objArray = $this->loadMultiByPK($ids);
foreach ($objArray as $rateObj) {
$questionObj = new API_QUESTION();
$questionObj->load($rateObj->questionid);
$questionObj->negvotes--;
$questionObj->score -= SCORE_MODIFIER;
$questionObj->updateField("negvotes", $questionObj->negvotes);
$questionObj->updateField("score", $questionObj->score);
}
//Delete from the main table
if (!parent::multiDelete($ids)) {
return false;
}
return true;
}
/**
* validate_rateid
*
* Ensure the rate id is a pos int
*
* #param string $var
*
* #return bool
*/
function validate_rateid($var)
{
return $this->is_positive_int($var);
}
/**
* validate_questionid
*
* Ensure the questionid is pos int
*
* #return bool
*/
function validate_questionid($var)
{
return $this->is_positive_int($var);
}
/**
* validate_ip
*
* Ensure the ip is an ipv4 address
*
* #param $var the ip to validate
*
* #return bool
*/
function validate_ip($var)
{
return $this->is_ip($var);
}
/**
* validate_ratedat
*
* Ensure the rated at date is in the standard date format
*
* #param string $var
*
* #return bool
*/
function validate_ratedat($var)
{
return $this->is_standard_date($var);
}
/**
* validate_email
*
* Ensure the email address for this rate entry is valid.
*
* #param string $var
*
* #return bool
*/
function validate_ratingemail(&$var)
{
if ((trim($var) == "") || (trim($var) == GetLang("WhyUnhelpfulEmail"))) {
$var = "";
return true;
} else {
return is_email_address($var);
}
}
/**
* validate_ratingmessage
*
* Ensure there is a message and its not blank.
*
* #param string $var
*
* #return bool
*/
function validate_ratingmessage(&$var)
{
if (strlen(trim($var)) > 250) {
$var = substr(trim($var),0,250);
return true;
} else {
return (trim($var) != "");
}
}
}
?>
This function :
function multiDelete($ids) {
Should be identic with it's parent function, find out the same function in class API, the nums, default value and type of the params should be same;
I asked this before, Strict Standards: Declaration of ' ' should be compatible with ' '