In my SilverStripe project I have a controller which I call by a cronjob. But in this controller I want to use the translations from the yaml language files. So I want to set the locale to use the right translations. I tried to do something like this, but this doesn't work:
class CronController extends Controller {
public function opendataform() {
i18n::set_locale('it_IT');
$Params = $this->getURLParams();
self::$ad = $Params['ID'];
$selectMemberSelectionField = new DropdownField('SelectionName', _t('General.CHOOSE_SELECTION', "Choose selection"), MemberSelection::get()->map('ID', 'Name'));
$fields = new FieldList($selectMemberSelectionField);
$actions = new FieldList(
FormAction::create("doOpen")->setTitle(_t('General.Open', "Open"))
);
$form = new Form($this, 'OpenForm', $fields, $actions);
return $form;
}
}
Also tried with: Translatable::set_current_locale('it_IT');
Any suggestions? Thanks in advance!
Related
I'd like to use a view as an email body.
I tried this one:
$renderer = new PhpRenderer();
$bodyHtml = $renderer->render(
'/user/email/reset-password-email',
[
'passwordResetUrl' => $passwordResetUrl,
]);
$html = new MimePart($bodyHtml);
I get the following error:
Unable to render template "/user/email/reset-password-email"; resolver could not resolve to a file
My view-template is located in:
Any help appreciated.
To render view as string, you need a renderer "ViewRenderer".
If you can get ServiceManager,
then,
$renderer = $serviceManager->get('ViewRenderer');
Now,
$bodyHtml = $renderer->render(
'/user/email/reset-password-email',
[
'passwordResetUrl' => $passwordResetUrl,
]);
$html = new MimePart($bodyHtml);
You need to retrieve the renderer from the service locator in the factory, and not instantiating it directly in the class where you are using it.
Email sender class factory
class EmailSenderFactory {
public function __invoke($services) {
$viewRenderer = $services->get('ViewRenderer');
return new EmailSender($viewRenderer);
}
}
Email sender class
class EmailSender {
private $viewRenderer;
public function __construct($viewRenderer) {
$this->viewRenderer = $viewRenderer;
}
public function createEmail() {
$template = '/user/email/reset-password-email';
$variables = ['passwordResetUrl' => $passwordResetUrl];
$bodyHtml = $renderer->render($template, $variables);
$html = new MimePart($bodyHtml);
}
}
I had the same problem (sending an email for password reset) and I solved this way. Hope this will help you :)
I want to change my date before to save in sonata admin bundle :
in fact try to change request in preCreate Method but I got nothing ...
here is my code (on my custom controller called eventAdminController.php):
protected function preCreate(Request $request, $object)
{
$jalali = $this->get('jalali');
$all = $request->request->all();
if(isset($request->request->get('s587f71334d196')['start_date'])){
$start_date = explode('/',$request->request->get('s587f71334d196')['start_date']);
$start_date_day = $start_date[0];
$start_date_mon = $start_date[1];
$start_date_yer = $start_date[2];
$start_date = $jalali->to_miladi($start_date_yer,$start_date_mon,$start_date_day);
$all['s587f71334d196']['start_date'] = $start_date[0].'-'.$start_date[1].'-'.$start_date[2];
}
if(isset($request->request->get('s587f71334d196')['end_date'])){
$end_date = explode('/',$request->request->get('s587f71334d196')['end_date']);
$end_date_day = $end_date[0];
$end_date_mon = $end_date[1];
$end_date_yer = $end_date[2];
$end_date = $jalali->to_miladi($end_date_yer,$end_date_mon,$end_date_day);
$all['s587f71334d196']['end_date'] = $end_date[0].'-'.$end_date[1].'-'.$end_date[2];
}
$request->request->replace($all);
}
You can do this in your Admin Class you need to add prePersist and preUpdate method for that. For example
public function prePersist($object)
{
$this->changeDate($object);
}
public function preUpdate($object)
{
$this->changeDate($object);
}
public function changeDate($object)
{
//Set your entity date.
}
I'm working on getting some google analytics api stats and am able to get metrics just fine using this...
$results = getResults($analytics, $profile->getId(), $value);
$rows = $results->getRows();
$myvalue = $rows[0][0];
echo "<b>$value:</b> ". round($myvalue, 0) ."</br>";
but the below code throws an error (see post title) when I call batchGet using same analytics object that works in above code. Unsure why or if there is an alternative way to get the dimension data I'm after.
$device = new Google_Service_AnalyticsReporting_Dimension();
$device->setName("ga:deviceCategory");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setDimensions(array($device));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
Here is how I instantiate the $analytics object
function getService()
{
// service account email, and relative location of your key file.
$service_account_email = 'email#gserviceaccount.com';
$key_file_location = 'pathto/file.p12';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Analytics");
$analytics = new Google_Service_Analytics($client);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_email,
array(Google_Service_Analytics::ANALYTICS_READONLY),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
return $analytics;
}
Still don't know why batchGet throws an error, but the code below works and will return the deviceCategories.
$optParams = array(
'dimensions' => 'ga:deviceCategory',
'filters' => 'ga:medium==organic');
$devices = $analytics->data_ga->get(
'ga:'.$profile->getId(),
'2015-05-01',
'2015-05-15',
'ga:sessions',
$optParams);
print_r($devices);
How do I return a response in Symfony to output a pdf? I'm currently using FPDF as I don't want to use any bundles. Here is my controller action:
public function pdfAction(Request $request) {
//grab from database
$pdf = new \FPDF;
for($i = 0; $i < count($entities); $i++) {
//manipulate data
$pdf->AddPage();
$pdf->SetFont("Helvetica","","14");
$pdf->SetTextColor(255, 255, 255);
}
$pdf->Output();
return new Response($pdf, 200, array(
'Content-Type' => 'pdf'));
}
With this all I'm getting is a page with gibberish characters. I'm quite new to I/O manipulations so any help would be great. Thank you..
You need to set proper Content-Type of your response. Also, don't send your FPDF object as a content of your response, but rather the PDF output. Try this:
public function pdfAction(Request $request) {
//................//
return new Response($pdf->Output(), 200, array(
'Content-Type' => 'application/pdf'));
}
UPDATE:
To get your generated PDF file downloaded instead of displayed, you need to set disposition to attachment:
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
public function pdfAction(Request $request) {
//................//
$response = new Response(
$pdf->Output(),
Response::HTTP_OK,
array('content-type' => 'application/pdf')
);
$d = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
'foo.pdf'
);
$response->headers->set('Content-Disposition', $d);
return $response;
}
http://symfony.com/doc/current/components/http_foundation/introduction.html#serving-files
In symfony 2.7, I'm having a "Corrupted content" while trying to set the Content-Disposition. My fix is:
public function pdfAction(Request $request) {
//................//
$response = new Response(
$pdf->Output(),
Response::HTTP_OK,
array('content-type' => 'application/pdf')
);
return $response;
}
is there a way to group a GridField (for example, by ID)? The following Query (many_many) returns some dataobjects twice or more, if they havent the same SortOrder. Here is some code. I hope that somebody can help ;-)
private static $many_many = array(
'Mitarbeiter' => 'Mitarbeiter',
);
private static $many_many_extraFields = array(
'Mitarbeiter' => array(
'SortOrder' => "Int"
)
)
// Start Mitarbeiterzuordnung
$MitarbeiterFieldConfig = GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
//new GridFieldSortableHeader(),
new GridFieldDataColumns(),
new GridFieldDeleteAction('unlinkrelation'),
new GridFieldSortableRows('SortOrder'),
new GridFieldManyRelationHandler(), 'GridFieldPaginator',
new GridFieldPaginator(20)
);
$MitarbeiterField = new GridField("Mitarbeiter", "Mitarbeiter", $this->Mitarbeiter()->sort('SortOrder'), $MitarbeiterFieldConfig);
$fields->addFieldToTab('Root.Mitarbeiter', $MitarbeiterField);
There is an issue with GridFieldManyRelationHandler.php and having a private static $many_many_extraFields as sorting field.
The query runs with the SortOrder being different and because it uses distinct, the ones having a different values are seen as extra, this is why the ones that have an order set show up twice.
You need to create a copy of GridFieldManyRelationHandler.php (I called it GridFieldManyManyRelationHandler.php) and edit the following function:
public function getManipulatedData(GridField $gridField, SS_List $list) {
if(!$list instanceof RelationList) {
user_error('GridFieldManyRelationHandler requires the GridField to have a RelationList. Got a ' . get_class($list) . ' instead.', E_USER_WARNING);
}
$state = $this->getState($gridField);
// We don't use setupState() as we need the list
if($state->FirstTime) {
$state->RelationVal = array_values($list->getIdList()) ?: array();
}
if(!$state->ShowingRelation && $this->useToggle) {
return $list;
}
$baseClass = $list->dataClass();
return $baseClass::get();
}
Then call that new class from your code, ie
private static $many_many = array(
'Mitarbeiter' => 'Mitarbeiter',
);
private static $many_many_extraFields = array(
'Mitarbeiter' => array(
'SortOrder' => "Int"
)
)
// Start Mitarbeiterzuordnung
$MitarbeiterFieldConfig = GridFieldConfig::create()->addComponents(
new GridFieldToolbarHeader(),
//new GridFieldSortableHeader(),
new GridFieldDataColumns(),
new GridFieldDeleteAction('unlinkrelation'),
new GridFieldSortableRows('SortOrder'),
new GridFieldManyManyRelationHandler(), 'GridFieldPaginator',
new GridFieldPaginator(20)
);
$MitarbeiterField = new GridField("Mitarbeiter", "Mitarbeiter", $this->Mitarbeiter()->sort('SortOrder'), $MitarbeiterFieldConfig);
$fields->addFieldToTab('Root.Mitarbeiter', $MitarbeiterField);
This probably should be refactored and the two classes should be separated (one class handling many_many and the other has_many).