I'm trying to save the display name of a user account using ZfcUser as a base to create my own API, but unfortunately I couldn't. This is my code:
$service = $this->getUserService();
$form = $this->getPostData();
$post = array(
"email" => $form->{'email'},
"password" => $form->{'password'},
"passwordVerify" => $form->{'password'},
"display_name" => $form->{'name'},
"submit" => ""
);
$service->register($post);
return new JsonModel($this->postToArray($form));
Related
I want to connect -any- customer Google AdWords Account with Google Login. (Like Wordstream)
I prepared a code, but there is a problem somewhere, I can't run it.
When the customer press the connect button, the screen appears. It says "XXX wants to acces your Google Account", it is approved but I cannot receive data.
How can i get datas from customer's account?
Code:
require 'google-api/vendor/autoload.php';
use Google\Auth\OAuth2;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\CampaignService;
use Google\AdsApi\Common\OAuth2TokenBuilder;
session_start();
$oauth2 = new OAuth2([
'authorizationUri' => 'https://accounts.google.com/o/oauth2/v2/auth',
'tokenCredentialUri' => 'https://www.googleapis.com/oauth2/v4/token',
'redirectUri' => 'https://xxxxx.xxxxxx',
'clientId' => 'xxxxxxxxx.apps.googleusercontent.com',
'clientSecret' => 'xxxxxxxxxxx',
'scope' => 'https://www.googleapis.com/auth/adwords',
'refresh_token' => 'xxxxxxxxxx'
]);
if(!isset($_GET['code'])){
$oauth2->setState(sha1(openssl_random_pseudo_bytes(1024)));
$_SESSION['oauth2state'] = $oauth2->getState();
$config = [
'access_type' => 'offline',
'prompt' => 'consent',
];
header('Location: ' . $oauth2->buildFullAuthorizationUri($config));
exit;
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])){
unset($_SESSION['oauth2state']);
exit('Invalid state.');
} else {
$oauth2->setCode($_GET['code']);
$authToken = $oauth2->fetchAuthToken();
$refreshToken = $authToken['refresh_token'];
$path = "xxxxx/google-api/vendor/adsapi_php.ini";
$session = (new AdWordsSessionBuilder())
->fromFile($path)
->withOAuth2Credential($oauth2)
->build();
$adWordsServices = new AdWordsServices();
$campaignService = $adWordsServices->get($session, CampaignService::class);
print_r($campaignService);
}
i'm try to write dailymotion api upload php code
i'm use example code from https://developer.dailymotion.com/guides
it's work great
and i want add Geoblocking only allow Japan
this is my code
require_once 'Dailymotion.php';
// Account settings
$apiKey = 'xxxxxxxxxxxxxxxxxx';
$apiSecret = 'xxxxxxxxxxxxxxxxxx';
$testUser = 'xxxxxxxxxxxxxxxxxx#xxxx.com';
$testPassword = 'xxxxxxxxxxxxxxxxxx';
$videoTestFile = 'C:/output.mp4';
// Scopes you need to run your tests
$scopes = array(
'userinfo',
'feed',
'manage_videos',
);
// Dailymotion object instanciation
$api = new Dailymotion();
$api->setGrantType(
Dailymotion::GRANT_TYPE_PASSWORD,
$apiKey,
$apiSecret,
$scopes,
array(
'username' => $testUser,
'password' => $testPassword,
)
);
$url = $api->uploadFile($videoTestFile);
$result = $api->post(
'/videos',
array(
'url' => $url,
'title' => 'Dailymotion PHP SDK upload test 2',
'tags' => 'dailymotion,api,sdk,test',
'channel' => 'videogames',
'published' => true,
'geoblocking' => 'JP', // i'm add this line
)
);
var_dump($result);
but i got this error
Fatal error: Uncaught exception 'DailymotionAuthRequiredException' with message 'Insufficient rights for the `geoblocking' parameter of route `POST /videos'. Required scopes: manage_videos'
anyone can tell me
what i'm doing wrong and help me fix this problem
thank you
'geoblocking' => 'JP'
change to 'geoblocking' => 'jp'
your code will be
require_once 'Dailymotion.php';
// Account settings
$apiKey = 'xxxxxxxxxxxxxxxxxx';
$apiSecret = 'xxxxxxxxxxxxxxxxxx';
$testUser = 'xxxxxxxxxxxxxxxxxx#xxxx.com';
$testPassword = 'xxxxxxxxxxxxxxxxxx';
$videoTestFile = 'C:/output.mp4';
// Scopes you need to run your tests
$scopes = array(
'userinfo',
'feed',
'manage_videos',
);
// Dailymotion object instanciation
$api = new Dailymotion();
$api->setGrantType(
Dailymotion::GRANT_TYPE_PASSWORD,
$apiKey,
$apiSecret,
$scopes,
array(
'username' => $testUser,
'password' => $testPassword,
)
);
$url = $api->uploadFile($videoTestFile);
$result = $api->post(
'/videos',
array(
'url' => $url,
'title' => 'Dailymotion PHP SDK upload test 2',
'tags' => 'dailymotion,api,sdk,test',
'channel' => 'videogames',
'published' => true,
'geoblocking' => 'jp' // NO , in last line
)
);
var_dump($result);
I'm trying to add new users to sfDoctrineGuard table using my own register form. This is the configure function I made:
public function configure() {
// Remove all widgets we don't want to show
unset(
$this['is_super_admin'], $this['updated_at'], $this['groups_list'], $this['permissions_list'], $this['last_login'], $this['created_at'], $this['salt'], $this['algorithm']
);
$id_empresa = sfContext::getInstance()->getUser()->getGuardUser()->getSfGuardUserProfile()->getIdempresa();
$this->setDefault('idempresa', $id_empresa);
$this->validatorSchema['idempresa'] = new sfValidatorPass();
$this->widgetSchema['first_name'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
$this->widgetSchema['last_name'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
$this->widgetSchema['username'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
$this->widgetSchema['email_address'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
$this->widgetSchema['password'] = new sfWidgetFormInputPassword(array(), array('class' => 'input-block-level'));
$this->widgetSchema['password_confirmation'] = new sfWidgetFormInputPassword(array(), array('class' => 'input-block-level'));
// Setup proper password validation with confirmation
$this->validatorSchema['password']->setOption('required', true);
$this->validatorSchema['password_confirmation'] = clone $this->validatorSchema['password'];
$this->widgetSchema->moveField('password_confirmation', 'after', 'password');
$this->mergePostValidator(new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::EQUAL, 'password_confirmation', array(), array('invalid' => 'The two passwords must be the same.')));
}
Now I need to create those new users with the same group(s) that the user logged in but I don't know how. I read this post but don't know if using getGroups() will do the job I mean setting groups_list default, any advice? What's the best way to do this?
there are several way you could do this... I'd recommend adding the groups once validation for the other fields has taken place, and the user object has been saved; so you can override the save() function of the form and add them there:
<?php
class YourUserForm extends PluginsfGuardUserForm
{
/**
* A class variable to store the current user
* #var sfGuardUser
*/
protected $current_user;
public function configure()
{
// Remove all widgets we don't want to show
unset(
$this['is_super_admin'],
$this['updated_at'],
$this['groups_list'],
$this['permissions_list'],
$this['last_login'],
$this['created_at'],
$this['salt'],
$this['algorithm']
);
// save the currrent user for use later in the save function
$this->current_user = sfContext::getInstance()->getUser()->getGuardUser();
$id_empresa = $this->current_user->getSfGuardUserProfile()->getIdempresa();;
$this->setDefault('idempresa', $id_empresa);
$this->validatorSchema['idempresa'] = new sfValidatorPass();
$this->widgetSchema['first_name'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
$this->widgetSchema['last_name'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
$this->widgetSchema['username'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
$this->widgetSchema['email_address'] = new sfWidgetFormInputText(array(), array('class' => 'input-block-level'));
$this->widgetSchema['password'] = new sfWidgetFormInputPassword(array(), array('class' => 'input-block-level'));
$this->widgetSchema['password_confirmation'] = new sfWidgetFormInputPassword(array(), array('class' => 'input-block-level'));
// Setup proper password validation with confirmation
$this->validatorSchema['password']->setOption('required', true);
$this->validatorSchema['password_confirmation'] = clone $this->validatorSchema['password'];
$this->widgetSchema->moveField('password_confirmation', 'after', 'password');
$this->mergePostValidator(new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::EQUAL, 'password_confirmation', array(), array('invalid' => 'The two passwords must be the same.')));
}
public function save($con = null)
{
// call the parent function to perform the save and get the new user object
$new_user = parent::save($con); /* #var $user sfGuardUser */
// add our groups here by looping the current user's group collection
foreach($this->current_user->getGroups() as $group) /* #var $group sfGuardGroup */
{
// we could use $user->addGroupByName($group->name); here, but it would mean
// an extra db lookup for each group as it validates the name. we know the
// group must exist, so can just add directly
// create and save new user group
$ug = new sfGuardUserGroup();
$ug->setsfGuardUser($new_user);
$ug->setsfGuardGroup($group);
$ug->save($con);
}
// make sure we return the user object
return $new_user;
}
}
You can see I set up a class variable to store the current user, this isn't necessary, but it save having to keep calling sfContext::getInstance()->getUser()->getGuardUser(), and is good practice as your forms get more complex.
Hopefully this helps! :)
I want to put a dropdown in my project which is made in zf2... I wasted all day but I only got a static dropdown, not dynamic. Can anyone help me with this problem??
UserForm.php
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
'options' => array('1=>php','2'=>'java'),
),
'options' => array(
'label' => '',
),
));
Thanks in advance for your valuabe answer.
Try this:
$this->add(array(
'name' => 'group_name',
'type' => 'select',
'attributes' => array(
'id'=>'group_name',
'class'=>'large',
),
'options' => array(
'label' => '',
'value_options' => array(
'1' => 'php',
'2' => 'java'
),
),
));
This is what i did:
In my constructor for my form
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'color',
'options' => array(
'empty_option' => 'Select a Color',
'value_options' => self::getColors(),
'label' => 'Color',
),
));
In the form class yet, i created this method:
public static function getColors() {
// access database here
//example return
return array(
'blue' => 'Blue',
'red' => 'Red',
);
}
In my view script:
<div class="form_element">
<?php $element = $form->get('color'); ?>
<label>
<?php echo $element->getOption('label'); ?>
</label>
<?php echo $this->formSelect($element); ?>
</div>
Think about it from a abstract level.
You have one Form
The Form needs Data from the outside
So ultimately your Form has a Dependency. Since we've learned from the official docs, there's two types of Dependency-Injection aka DI. Setter-Injection and Constructor-Injection. Personally(!) i use one or the other in those cases:
Constructor-Injection if the dependency is an absolute requirement for the functionality to work
Setter-Injection if the dependencies are more or less optional to extend already working stuff
In the case of your Form, it is a required dependency (because without it there is no populated Select-Element) hence i'll be giving you an example for Constructor-Injection.
Some action of your controller:
$sl = $this->getServiceLocator();
$dbA = $sl->get('Zend\Db\Adapter\Adapter');
$form = new SomeForm($dbA);
That's all for the form. The population now happens inside your Form. This is only an example and may need some fine-tuning, but you'll get the idea:
class SomeForm extends \Zend\Form
{
public function __construct(\Zend\Db\Adapter\Adapter $dbA)
{
parent::__construct('my-form-name');
// Create all the form elements and stuff
// Get Population data
$popData = array();
$result = $dbA->query('SELECT id, title FROM Categories', $dbA::QUERY_MODE_EXECUTE)->toArray();
foreach ($result as $cat) {
$popData[$cat['id'] = $cat['title'];
}
$selectElement = $this->getElement('select-element-name');
$selectElement->setValueOptions($popData);
}
}
Important: I HAVE NO CLUE ABOUT Zend\Db the above code is only for how i think it would work going by the docs! This is the part that would need some optimization probably. But all in all you'll get the idea of how it's done.
In your controller you can do something like below;
On my first example assuming that you have a Group Table. Then we're going to fetchAll the data in group table;
We need the id and name to be display in select options;
public function indexAction()
{
$groupTable = new GroupTable();
$groupList = $groupTable->fetchAll();
$groups = array();
foreach ($groupList as $list) {
$groups[$list->getId()] = $list->getName();
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
OR
in this example the grouplist is hardcoded;
public function indexAction()
{
$groupList = array('1' => 'PHP', '2' => 'JAVA', '3' => 'C#');
$groups = array();
foreach ($groupList as $id => $list) {
$groups[$id] = $list;
}
$form = new UserForm();
$form->get('group_name')->setAttributes(array(
'options' => $groups,
));
}
Then in your view script;
<?php
$form = $this->form;
echo $this->formRow($form->get('group_name'));
?>
Or you can right a controller helper, you may check this link http://www.resourcemode.com/me/?p=327
Just came across the same problem and had to take a look into zf2 source.
Here's a more OOP solution:
Inside the form constructor:
$this->add(array(
'name' => 'customer',
'type' => 'Zend\Form\Element\Select',
'attributes' => array(
'options' => array(
0 => 'Kunde',
)
),
'options' => array(
'label' => 'Kunde'
)));
inside the controller:
$view->form = new SearchForm();
$customers = $view->form->get('customer')->getValueOptions();
$customers[] = 'Kunde1';
$customers[] = 'Kunde2';
$customers[] = 'Kunde3';
$customers[] = 'Kunde4';
$view->form->get('customer')->setValueOptions($customers);
I'm building a simple form mailer in symfony using sfExtraForm plugin captcha. Everything works except sfValidator is not redirecting the user and showing an error when any field is invalid. The only thing I can think of is I did not generate the module. I built it from scratch.
I have to do the redirect manually. Is this because this is a sfForm and not an sfDoctrine Form? It is if the line if ($form->isValid()) returns false but without the associated redirect and error codes. Here is the program. Thanks:
Form:
<?php
class AdsForm extends sfForm
{
public function configure()
{
$this->setWidgets(array(
'name' => new sfWidgetFormInputText(),
'email' => new sfWidgetFormInputText(),
'phone' => new sfWidgetFormInputText(),
'fax' => new sfWidgetFormInputText(),
'attention' => new sfWidgetFormInputText(),
'message' => new sfWidgetFormInputText(),
'captcha' => new sfWidgetFormReCaptcha( array('public_key'=>self::PUBLIC_KEY)),
));
$this->widgetSchema->setNameFormat('ads[%s]');
$this->setValidators(array(
'name' => new sfValidatorString(array('max_length' => 50)),
'email' => new sfValidatorString(array('max_length' => 50)),
'phone' => new sfValidatorString(array('max_length' => 50)),
'fax' => new sfValidatorString(array('max_length' => 50)),
'attention' => new sfValidatorString(array('max_length' => 50)),
'message' => new sfValidatorString(array('max_length' => 255)),
'captcha' => new sfValidatorReCaptcha(array('private_key' => self::PRIVATE_KEY))
));
$this->widgetSchema->setLabels(array(
'name' => 'Your Name:*',
'email' => 'Your Email:*',
'phone' => 'Your Phone:*',
'fax' => 'Your Fax',
'attention' => 'Attention:*',
'message' => 'Mail Message:*',
'captcha' => 'Image Verification:*',
));
}
}
Action:
class adsActions extends sfActions
{
public function executeIndex(sfWebRequest $request)
{
$this->form=new adsForm();
}
public function executeSend(sfWebRequest $request){
$this->forward404Unless($request->isMethod(sfRequest::POST));
$form=new adsForm();
$captcha = array('recaptcha_challenge_field' => $request->getParameter('recaptcha_challenge_field'),'recaptcha_response_field' => $request->getParameter('recaptcha_response_field'),);
$form->bind(array_merge($request->getParameter('ads'), array('captcha' => $captcha)));
if ($form->isValid())
{
print_r($_REQUEST);
$ads=$this->getRequestParameter('ads');
print_r($ads);
$headers = 'From: '."\r\n" .
'Reply-To: no-reply#yellowexplorer.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
//mail(' ******#yahoo.com','Yellow Explorer','An account has been created for you at yellowexplorer.com with a username of '.$this->username.'. Please click here to finish creating your account.',$headers);
}
else{
$this->redirect('/ads');
}
}
}
You're not seeing any errors because you're redirecting! To render form fields with their errors, you need to be rendering the actual form instance that you called bind on. Try changing $this->redirect('/ads') to $this->setTemplate('index').
Other potential changes (outside the scope of the question):
You can enforce the request method requirements of the send action at the routing level. Make the send route an sfRequestRoute and add the requirement { sf_method: post }.
Symfony has a built in mailer, sfMailer. Any reason you've decided not to use it?