How can i change view's suffix in Zend Framwork2..
I've tried this way but it doesn't work. I need to change suffix when i enter from mobile device.
My code as this
// Application\Module.php
public function onBootstrap(MvcEvent $e)
{
$app = $e->getApplication();
$sl = $app->getServiceManager();
$resolver = $sl->get('ViewTemplatePathStack');
$resolver->setDefaultSuffix('mobile.phtml');
}
Put this verification inside your onBootstrap function.
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))) {
$app->getEventManager()->attach('dispatch', array($this, 'isMobile'), -100);
}
Then create the function isMobile.
public function isMobile(\Zend\Mvc\MvcEvent $e){
$templateStack = $e->getApplication()->getServiceManager()->get('Zend\View\Resolver\TemplatePathStack');
$templateStack->setDefaultSuffix('mobile.phtml');
}
Related
I am using IdentityServer4 (IS4) to connect to AzureAD for authentication. I have created the app on AzureAD and used the correct ClientID and Tenant ID as well.
I am getting the following error while signing in:
[15:13:04 Information] Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler
AuthenticationScheme: OpenIdConnect was challenged.
[15:13:06 Debug] IdentityServer4.Hosting.CorsPolicyProvider
CORS request made for path: /signin-oidc from origin: https://login.microsoftonline.com but was ignored because path was not for an allowed IdentityServer CORS endpoint
[15:13:06 Information] Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler
AuthenticationScheme: Identity.External signed in.
Please, I requesting to guide me, as in what is going wrong here.
Here's how my entire Startup.cs looks like:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using IdentityServerHost.Quickstart.UI;
using System.Reflection;
using IdentityServer.Models;
using Microsoft.AspNetCore.Identity;
using IdentityServer.Data;
using IdentityServer4.Configuration;
using System;
using Microsoft.AspNetCore.Authentication;
using IdentityServer4.Services;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
namespace IdentityServer
{
public class Startup
{
public IWebHostEnvironment Environment { get; }
public IConfiguration Configuration { get; }
public Startup(IWebHostEnvironment environment, IConfiguration configuration)
{
Environment = environment;
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("DefaultConnection");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddControllersWithViews();
services.AddDbContext<IdentityServerContext>(options =>
options.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly))
);
services.AddDbContext<Data.ConfigurationDbContext>(options => options.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly)));
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedEmail = false;
//New added
options.Password.RequiredLength = 4;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireDigit = false;
options.Password.RequireNonAlphanumeric = false;
options.Lockout.AllowedForNewUsers = true;
options.Lockout.DefaultLockoutTimeSpan = new TimeSpan(0, 15, 00);
options.Lockout.MaxFailedAccessAttempts = 5;
})
.AddEntityFrameworkStores<IdentityServerContext>()
.AddDefaultTokenProviders();
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
// see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
options.EmitStaticAudienceClaim = true;
options.UserInteraction.LoginUrl = "/Account/Login";
options.UserInteraction.LogoutUrl = "/Account/Logout";
options.Authentication = new IdentityServer4.Configuration.AuthenticationOptions()
{
CookieLifetime = TimeSpan.FromHours(10), // ID server cookie timeout set to 10 hours
CookieSlidingExpiration = true
};
})
//.AddTestUsers(TestUsers.Users)
// this adds the config data from DB (clients, resources, CORS)
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder => builder.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder => builder.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
})
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<IdentityProfileService>();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
var autBuilder = services.AddAuthentication();
//Azure AD
autBuilder.AddAzureAd(options => Configuration.Bind("AzureAd", options));
// not recommended for production - you need to store your key material somewhere secure
builder.AddDeveloperSigningCredential();
/*
services.AddAuthentication()
.AddGoogle(options =>
{
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
// register your IdentityServer with Google at https://console.developers.google.com
// enable the Google+ API
// set the redirect URI to https://localhost:5001/signin-google
options.ClientId = "copy client ID from Google here";
options.ClientSecret = "copy client secret from Google here";
});
*/
}
public void Configure(IApplicationBuilder app)
{
if (Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
app.UseStaticFiles();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
}
And the Azure Extension.cs
using System;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Authentication
{
public static class AzureAdAuthenticationBuilderExtensions
{
public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder)
=> builder.AddAzureAd(_ => { });
public static AuthenticationBuilder AddAzureAd(this AuthenticationBuilder builder, Action<AzureAdOptions> configureOptions)
{
builder.Services.Configure(configureOptions);
builder.Services.AddSingleton<IConfigureOptions<OpenIdConnectOptions>, ConfigureAzureOptions>();
builder.AddOpenIdConnect();
return builder;
}
private class ConfigureAzureOptions: IConfigureNamedOptions<OpenIdConnectOptions>
{
private readonly AzureAdOptions _azureOptions;
public ConfigureAzureOptions(IOptions<AzureAdOptions> azureOptions)
{
_azureOptions = azureOptions.Value;
}
public void Configure(string name, OpenIdConnectOptions options)
{
options.ClientId = _azureOptions.ClientId;
options.Authority = $"{_azureOptions.Instance}{_azureOptions.TenantId}";
options.UseTokenLifetime = true;
options.CallbackPath = _azureOptions.CallbackPath;
options.RequireHttpsMetadata = false;
}
public void Configure(OpenIdConnectOptions options)
{
Configure(Options.DefaultName, options);
}
}
}
}
And the appsettings.json
Appsettings.json
{
"ConnectionStrings": {
//"DefaultConnection": "connectiong_string"
},
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "",
"TenantId": "xxxxxxxxxxxxxxxxxxxxxxxxxx",
"ClientId": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
"CallbackPath": "/signin-oidc"
},
"TimeSettings": {
"AbsoluteRefreshTokenLifetime": 15552000,
"SlidingRefreshTokenLifetime": 1296000,
"IdentityTokenLifetime": 300,
"AccessTokenLifetime": 300,
"AuthorizationCodeLifetime": 300
}
}
IdentityServer has its own CORS settings for requests made by its clients.
You use the AllowedCorsOrigins collection on the client configuration to set this up. Simply add the origin of the client to the collection and the default configuration in IdentityServer will consult these values to allow cross-origin calls from the origins.
new Client
{
...
AllowedCorsOrigins = new List<string>
{
"http://www.myclient.com"
}
}
Hard to tell, one thought is if the use of "CallbackPath": "/signin-oidc" should be changed to some other URL to not conflict with other things that uses /signin-oidc.
For example in the code here they use:
.AddOpenIdConnect("aad", "Sign-in with Azure AD", options =>
{
...
options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
options.SignOutScheme = IdentityServerConstants.SignoutScheme;
options.ResponseType = "id_token";
options.CallbackPath = "/signin-aad";
options.SignedOutCallbackPath = "/signout-callback-aad";
options.RemoteSignOutPath = "/signout-aad";
I used acl component but i need check permission in a view. create a component where instance acl component.
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
class AccessComponent extends Component
{
var $components = array('Acl');
function checkHelper($aro, $aco, $action = "*")
{
//Importa los componentes de ACL
App::import('Component', 'Acl');
// Instancia una clase del componente
$acl = new AclComponent();
// returna el resultado del check
return $acl->check($aro, $aco, $action);
}
}
then i need pass the function a AccessHelper
<?php
namespace App\View\Helper;
use Cake\View\Helper;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
class AccessHelper extends Helper
{
// var $helpers = array("Session");
var $Access;
//var $Auth;
// var $user;
function beforeRender(Event $event)
{
App::import('Component', 'AccessComponent');
// App::uses('AccessComponent', 'Controller/Component');
$this->Access = new AccessComponent();
// var_dump($this->Access);
// App::import('Component', 'Auth');
//$this->Auth = new AuthComponent();
//$this->Auth->Session = $this->Session;
//$user = $this->request->getSession()->read('Auth');
}
function check($user, $aco, $action='*')
{
if(empty($user)) return false;
// Returna el metodo del check definido en el componente Access
return $this->Access->checkHelper($user['User']['id'], $aco, $action);
}
}
?>
the helper dont found AccessComponent. Give me null ...
I'm Working on the following Component:
import {BudgetItem} from "../models/budget.model";
import {Injectable} from "#angular/core";
import {FirebaseListObservable, AngularFire, FirebaseObjectObservable} from "angularfire2";
#Injectable()
export class BudgetService{
public ausgaben:number;
public einnahmen:number;
public budgetArray = [];
private budget:FirebaseListObservable<any>;
private budgetItemToUpdate;
constructor(private af:AngularFire){
this.budget = af.database.list('/Budget');
this.ausgaben = this.getAusgaben();
this.einnahmen = this.getEinnahmen();
this.budget.subscribe(items => {
// items is an array
items.forEach(item => {
this.budgetArray.push(new BudgetItem(item.zweck,item.betrag,item.ausgabe));
});
});
}
//Nimmt ein BugetItem als Parameter und fügt dieses der Datenbank als neuen Datensatz bei
addToBuget(item:BudgetItem){
this.budget.push({zweck:item.zweck,betrag:item.betrag,ausgabe:item.ausgabe});
}
//Nimmt den Key eines Objekts und löscht das jewelige Objekt aus der Datenbank
removeFromInventar(key:string){
this.budget.remove(key);
}
//Synchronisiert ein bestehendes Objekt mit der Datenbank
updateBudgetItem(item){
this.budgetItemToUpdate = this.af.database.object("Budget/" + item.$key)
this.budgetItemToUpdate.update({zweck:item.zweck,betrag:item.betrag,ausgabe:item.ausgabe});
}
//berechnet die totalen Einnahmen. Als Anfangswert wird 2500(Budget) gesetzt.
getEinnahmen(){
this.einnahmen = 2500;
console.log(this.budgetArray);
for(let item of this.budgetArray){
if(item.ausgabe === "Einnahme"){
this.einnahmen = this.einnahmen + item.betrag;
}
}
console.log(this.einnahmen);
return this.einnahmen;
}
//berechnet die totalen Ausgaben. Als Anfangswert wird 0 gesetzt.
getAusgaben(){
this.ausgaben = 0;
console.log(this.budgetArray);
for(let item of (this.budgetArray)){
if(item.ausgabe === "Ausgabe"){
this.ausgaben = this.ausgaben + item.betrag;
}
}
console.log("Ausgaben: " + this.ausgaben)
return this.ausgaben;
}
}
I can suggestfully push my items in the array, but I want to add up the itempropertiy "Betrag" of the idividual Objects and display the sum of them.
Where is my Mistake or what kind of suggestions do you have to get the code working?
Here's the gist of it:
af.database.list('/Budget')
// Reduce all the items to a single value.
.map(items => items.reduce((acc, item) => acc + item.betrag, 0))
// Log the total
.do(total => console.log(total));
Hopefully you can adapt this code to your situation. Let me know if you need help.
getEinnahmen(){
this.einnahmen = 0
this.af.database.list("/Budget",{query:{
orderByChild:'ausgabe',
equalTo:'Einnahme'
}}).map(items => items.reduce((acc, item) => acc + item.betrag, 0))
// Log the total
.subscribe(total => {console.log(total);this.einnahmen = total;});
return this.einnahmen+2500;
}
I changed up the code with the reduce-method. Now I'm able to log the total to the console, but now i want to add it as the returnvalue of the method getEinnahmen.
I tried to add attachment in ics file but it not showing in outlook when open it. I am trying to add attachment like when we send meeting request and add attachment in that from outlook, that attachment can view from calendar as well. This is my ics file :
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//appform.com//NONSGML kigkonsult.se iCalcreator 2.18//
METHOD:PUBLISH
X-WR-TIMEZONE:UTC
X-MS-OLK-FORCEINSPECTOROPEN:TRUE
BEGIN:VEVENT
UID:20160719T144014-694839744#appform.com
DTSTAMP:20160719T124014Z
ATTACH;FMTTYPE="application/msword; charset=binary";FILENAME=1468827330fCrj
O.doc:/var/www/html/basearch.appform.com/application/../public/uploads/146
8827330fCrjO.doc
ATTENDEE;RSVP=TRUE;SENT-BY="MAILTO:sajal#mailinator.com";CN=satyendra#hirest
orm.com;DIR="/var/www/html/app/application/../public/uplo
ads/1468827330fCrjO.doc";LANGUAGE=us-EN;X-AGENDA=Interview;X-LENGTH=30 min
:MAILTO:satyendra#mailinator.com
DESCRIPTION:Name: Dean Nestle Jones G\nVacancy: test\nEmployer: Zend\nDate:
Wednesday\, 20thJuly 2016\nTime: 1430 to 1500\n\nSubmit Feedback : http:/
/hirestorm.com/tms/a/Mg==/appid/NDU4/vacid/MTY4/candid/MTY=\n\nCandida
te CV : https://f12b1a775b358d1fc463-637e94f874af614e321f6.ssl.
cf2.rackcdn.com/1468827330fCrjO.doc\nOther Documents : https://f12b1a775
b358d1fc463-637e94f874af614cdn.com/146297361
8PwEwE.jpeg\n
DTSTART:20160720T090000Z
DTEND:20160720T093000Z
LOCATION:1 2 Elmshorn Schleswig-Holstein Germany
SEQUENCE:0
SUMMARY:New Interview Confirmed: Dean Nestle Jones G for test
BEGIN:VALARM
ACTION:PROCEDURE
DESCRIPTION:Name: Dean Nestle Jones G\nVacancy: test\nEmployer: Zend\nDate:
Wednesday\, 20thJuly 2016\nTime: 1430 to 1500\n\nSubmit Feedback : http:/
/hirestorm.com/tms/a/Mg==/appid/NDU4/vacid/MTY4/candid/MTY=\n\nCandida
te CV : https://f12b1a775b358d1fc463-637e94f874af614ce048a5e321d7d0f6.ssl.
cf2.rackcdn.com/1468827330fCrjO.doc\nOther Documents : https://f12b1a775
b358d1fc463-637e94f874af614ce048a5e32cdn.com/146297361
8PwEwE.jpeg\n
TRIGGER:-PT0H15M0S
END:VALARM
END:VEVENT
END:VCALENDAR
Your iCalendar file contains a reference to :
/var/www/html/basearch.appform.com/application/../public/uploads/1468827330fCrjO.doc
This would obviously be something on your machine. You're not embedding any file, you're just pasting a local path. Unless you have Outlook running on linux there's no way it can find that path.
I tried to do it in a simple java
import java.io.IOException;
import java.net.URI;
import java.text.ParseException;
import java.util.HashMap;
import javax.activation.DataHandler;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import com.tba.readProps.Constants;
import com.tba.readProps.ReadProps;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.parameter.Cn;
import net.fortuna.ical4j.model.parameter.Role;
import net.fortuna.ical4j.model.property.Attendee;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Version;
import net.fortuna.ical4j.util.RandomUidGenerator;
import net.fortuna.ical4j.util.UidGenerator;
public class EmailWithCalendar{
/**
* #param emailAddr
* #param subject
* #param message
*/
public static void sendHtmlEmail(String emailAddr, String subject, String message){
HashMap propertyValues = null;
String smtpHost = "";
try {
propertyValues = ReadProps.initializeProperties();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
smtpHost = (String) propertyValues.get(Constants.SMTP_HOST);
//ManagerPropertiesBean mgrProps = new ManagerPropertiesBean();
//String smtpHost = mgrProps.getMgrProperty("smtpHost");
try {
// start a session with given properties
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
Session mailSession = Session.getDefaultInstance(props, null);
String fromAddress = null;
fromAddress = (String) propertyValues.get(Constants.FROM_ADDRESS);
if(!"undefined".equals(fromAddress)){
InternetAddress fromAddr = new InternetAddress("test#test.com");
InternetAddress toAddr = new InternetAddress(emailAddr);
MimeMessage myMessage = new MimeMessage(mailSession);
String replyToAddress = null;
replyToAddress = (String) propertyValues.get(Constants.REPLY_ADDRESS);
InternetAddress replyToAddr[] = new InternetAddress[1];
if(!"undefined".equals(replyToAddress))
replyToAddr[0] = new InternetAddress(replyToAddress);
boolean isfromValid = true;
boolean isToValid = true;
boolean emailDomainCheck = true;
MimeBodyPart messageBodyPart =new MimeBodyPart();
messageBodyPart.setContent(message ,"text/html" );
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
myMessage.setContent(multipart);
if(emailDomainCheck==true)
{
myMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddr);
myMessage.setReplyTo(replyToAddr);
}
else
{
myMessage.setFrom(fromAddr);
myMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddr);
if(!"undefined".equals(replyToAddress))
myMessage.setReplyTo(replyToAddr);
}
myMessage.setSentDate(new java.util.Date());
myMessage.setSubject(subject);
messageBodyPart.setDataHandler(new DataHandler(
new ByteArrayDataSource(createEvent().toString(), "text/calendar")));// very important
//myMessage.setText(message);
// now send the message!
if(emailDomainCheck==true)
{
if(isfromValid==true && isToValid==true)
{
Transport.send(myMessage);
}
}
else
{
Transport.send(myMessage);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error occurred in ManagerEmailBean.sendHtmlEmail()");
}
}
private static Calendar createEvent() throws ParseException {
// Create the event
String eventName = "Progress Meeting";
//DateTime start = new DateTime(startDate.getTime());
//DateTime end = new DateTime(endDate.getTime());
// Create the date range which is desired.
DateTime start = new DateTime("20100101T070000Z");
DateTime end = new DateTime("20100201T070000Z");;
Period period = new Period(start, end);
VEvent meeting = new VEvent(start, end, eventName);
// add timezone info..
//meeting.getProperties().add(tz.getTimeZoneId());
// generate unique identifier..
UidGenerator ug = new RandomUidGenerator();
Uid uid = ug.generateUid();
meeting.getProperties().add(uid);
// add attendees..
Attendee dev1 = new Attendee(URI.create("mailto:dev1#test.com"));
dev1.getParameters().add(Role.REQ_PARTICIPANT);
dev1.getParameters().add(new Cn("Developer 1"));
meeting.getProperties().add(dev1);
Attendee dev2 = new Attendee(URI.create("mailto:dev2#test.com"));
dev2.getParameters().add(Role.OPT_PARTICIPANT);
dev2.getParameters().add(new Cn("Developer 2"));
meeting.getProperties().add(dev2);
// Create a calendar
net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
icsCalendar.getProperties().add(Version.VERSION_2_0);
icsCalendar.getProperties().add(CalScale.GREGORIAN);
// Add the event and print
icsCalendar.getComponents().add(meeting);
System.out.println(icsCalendar);
return icsCalendar;
}
public static void main(String[] args) {
sendHtmlEmail("dev.test#gmail.com", "Test", "sjgsfgsf<p>dshdfsdf</p>");
}
}
I try to do a contact form with Symfony 2.4.1. My form is a simple contact one without an entity.
The following error happens in my handler :
FatalErrorException: Error: Call to undefined method Symfony\Component\Form\Form::render() in C:\Program Files\wamp\www\sf2\src\Open\OpcBundle\Form\Handler\ContactHandler.php line 75
And the form handler code :
<?php
// src/Open/OpcBundle/Form/Handler/Handler.php
namespace Open\OpcBundle\Form\Handler;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
class ContactHandler {
protected $request;
protected $form;
protected $mailer;
public function __construct(Form $form, Request $request, $mailer) {
$this->form = $form;
$this->request = $request;
$this->mailer = $mailer;
}
public function process() {
if ('POST' == $this->request->getMethod()) {
$this->form->handleRequest($this->request);
$data = $this->form->getData();
$this->onSuccess($data);
return true;
}
return false;
}
protected function onSuccess($data) {
$message = \Swift_Message::newInstance()
->setContentType('text/html')
->setSubject($data['sujet'])
->setFrom($data['courriel'])
->setTo('me#gmail.com')
->setBody($this->render('OpcOpenBundle:Opc:Mails/contact.html.twig',
array('ip' => $request->getClientIp(),
'nom' => $data['nom'],
'msg' => $data['msg'])
)
);
$this->get('mailer')->send($message);
$request->getSession()->getFlash()->add('success', 'Your email has been sent! Thanks!');
return $this->redirect($this->generateUrl('contact'));
}
}
So the problem is that I don't have an object/instance for the renderView() method to call the template mail with setBody in the function onSuccess()
Which object/instance should I use for ?
Thanks
PS: sorry for my english, i'm French!
It's Symfony\Bundle\TwigBundle\TwigEngine class. service name is 'templating'.
BTW, why is you handler is not service?