In my PHP script, I need to figure out how to retrieve all emails that are either after a specified message ID or after a specific date (Either will work, I just need to retrieve emails that are new since the last time I scraped the inbox).
This inbox is getting thousands of emails a day, and I can't delete any emails for 30 days. For the initial import I was just doing an offset from the beginning of the inbox, but obviously that won't work once we start cleaning out emails.
I think I have to set the $Restriction property of the class "EWSType_FindItemType", but I don't think the necessary classes exist in php-ews for me to do this. I've tried to add them myself, but I don't understand enough about EWS or SOAP.
So far the only thing I've come up with is this:
$Request->Restriction = new EWSType_RestrictionType();
$Request->Restriction->IsGreaterThan = new stdClass;
$Request->Restriction->IsGreaterThan->FieldURIOrConstant = new stdClass;
$Request->Restriction->IsGreaterThan->FieldURIOrConstant->Constant = '2012-01-02T07:04:00Z';
$Request->Restriction->IsGreaterThan->FieldURI = new stdClass;
$Request->Restriction->IsGreaterThan->FieldURI->FieldURI = 'item:DateTimeReceived';
And that doesn't work :(
Here's the code I am currently using to retrieve email:
<?php
require( dirname( __FILE__ ) . '/ews/ExchangeWebServicesLoader.php' );
$ews = new ExchangeWebServices( EXCHANGE_HOSTNAME, EXCHANGE_USERNAME, EXCHANGE_PASSWORD, ExchangeWebServices::VERSION_2010_SP1 );
$Request = new EWSType_FindItemType();
$Request->ItemShape = new EWSType_ItemResponseShapeType();
$Request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::ALL_PROPERTIES;
$Request->ItemShape->BodyType = EWSType_BodyTypeResponseType::TEXT;
$Request->ItemShape->BodyTypeSpecified = true;
$Request->Traversal = EWSType_ItemQueryTraversalType::SHALLOW;
$Request->IndexedPageItemView = new EWSType_IndexedPageViewType();
$Request->IndexedPageItemView->MaxEntriesReturned = 25;
$Request->IndexedPageItemView->BasePoint = 'Beginning';
$Request->IndexedPageItemView->Offset = $offset;
$Request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$Request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$Request->ParentFolderIds->DistinguishedFolderId->Id = 'inbox';
$Request->ParentFolderIds->DistinguishedFolderId->Mailbox = new EWSType_EmailAddressType();
$Request->ParentFolderIds->DistinguishedFolderId->Mailbox->EmailAddress = 'sharedmailbox#company.org';
// sort order
$Request->SortOrder = new EWSType_NonEmptyArrayOfFieldOrdersType();
$Request->SortOrder->FieldOrder = array();
$order = new EWSType_FieldOrderType();
$order->FieldURI = new stdClass;
$order->FieldURI->FieldURI = 'item:DateTimeReceived';
$order->Order = 'Ascending';
$Request->SortOrder->FieldOrder[] = $order;
$response = $ews->FindItem($Request);
$items = $response->ResponseMessages->FindItemResponseMessage->RootFolder->Items->Message;
foreach ( $items as $item ) {
// Do stuff
}
Any help would be greatly appreciated!
Restriction are tricky in EWS, true. You can take a look at haw they are used in EWSWrapper, here's example how to create AND restriction to get items in between date range:
//create AND restrction
$request->Restriction = new EWSType_RestrictionType();
$request->Restriction->And = new EWSType_AndType();
$request->Restriction->And->IsGreaterThanOrEqualTo = new EWSType_IsGreaterThanOrEqualToType();
$request->Restriction->And->IsGreaterThanOrEqualTo->ExtendedFieldURI = new EWSType_PathToExtendedFieldType;
$request->Restriction->And->IsGreaterThanOrEqualTo->ExtendedFieldURI->DistinguishedPropertySetId = "Task";
$request->Restriction->And->IsGreaterThanOrEqualTo->ExtendedFieldURI->PropertyId = "33029";
$request->Restriction->And->IsGreaterThanOrEqualTo->ExtendedFieldURI->PropertyType = "SystemTime";
$request->Restriction->And->IsGreaterThanOrEqualTo->FieldURIOrConstant->Constant->Value = date('c', $start);
$request->Restriction->And->IsLessThanOrEqualTo = new EWSType_IsLessThanOrEqualToType();
$request->Restriction->And->IsLessThanOrEqualTo->ExtendedFieldURI = new EWSType_PathToExtendedFieldType;
$request->Restriction->And->IsLessThanOrEqualTo->ExtendedFieldURI->DistinguishedPropertySetId = "Task";
$request->Restriction->And->IsLessThanOrEqualTo->ExtendedFieldURI->PropertyId = "33029";
$request->Restriction->And->IsLessThanOrEqualTo->ExtendedFieldURI->PropertyType = "SystemTime";
$request->Restriction->And->IsLessThanOrEqualTo->FieldURIOrConstant->Constant->Value = date('c', $end);
And the types used:
class EWSType_RestrictionType extends EWSType {
/**
* SearchExpression property
*
* #var EWSType_SearchExpressionType
*/
public $SearchExpression;
/**
* Constructor
*/
public function __construct() {
$this->schema = array(
array(
'name' => 'SearchExpression',
'required' => false,
'type' => 'SearchExpressionType',
),
); // end $this->schema
} // end function __construct()
} // end class RestrictionType
<?php
class EWSType_AndType extends EWSType {
/**
* SearchExpression property
*
* #var EWSType_MultipleOperandBooleanExpressionType
*/
public $SearchExpression;
/**
* Constructor
*/
public function __construct() {
$this->schema = array(
array(
'name' => 'SearchExpression',
'required' => false,
'type' => 'MultipleOperandBooleanExpressionType',
),
); // end $this->schema
} // end function __construct()
} // end class AndType
class EWSType_IsLessThanOrEqualToType extends EWSType {
/**
* SearchExpression property
*
* #var EWSType_TwoOperandExpressionType
*/
public $SearchExpression;
/**
* Constructor
*/
public function __construct() {
$this->schema = array(
array(
'name' => 'SearchExpression',
'required' => false,
'type' => 'TwoOperandExpressionType',
),
); // end $this->schema
} // end function __construct()
} // end class IsLessThanOrEqualToType
class EWSType_IsGreaterThanOrEqualToType extends EWSType {
/**
* SearchExpression property
*
* #var EWSType_TwoOperandExpressionType
*/
public $SearchExpression;
/**
* Constructor
*/
public function __construct() {
$this->schema = array(
array(
'name' => 'SearchExpression',
'required' => false,
'type' => 'TwoOperandExpressionType',
),
); // end $this->schema
} // end function __construct()
} // end class IsGreaterThanOrEqualToType
Thanks Maiiku for your code samples!
This is how I enabled filtering by date and subject field using the PHP Exchange Web Services library (php-ews).
(You will need to require_once the relevant EWSType libraries first before using this sample).
$start = new DateTime('2013-03-31');
$Request->Restriction = new EWSType_RestrictionType();
$Request->Restriction->And = new EWSType_AndType();
$Request->Restriction->And->IsGreaterThanOrEqualTo = new EWSType_IsGreaterThanOrEqualToType();
$Request->Restriction->And->IsGreaterThanOrEqualTo->FieldURI = new stdClass;
$Request->Restriction->And->IsGreaterThanOrEqualTo->FieldURI->FieldURI = 'item:DateTimeReceived';
$Request->Restriction->And->IsGreaterThanOrEqualTo->FieldURIOrConstant->Constant->Value = $start->format('c');
$Request->Restriction->And->Contains = new EWSType_ContainsExpressionType();
$Request->Restriction->And->Contains->FieldURI = new stdClass;
$Request->Restriction->And->Contains->FieldURI->FieldURI = 'item:Subject';
$Request->Restriction->And->Contains->Constant->Value = 'annual leave application';
$Request->Restriction->And->Contains->ContainmentMode = 'Substring';
$Request->Restriction->And->Contains->ContainmentComparison = 'Exact';
Hope this helps!
Related
I'm trying to import a list of 879 users (in batch) into a Mailchimp list. The library I'm using is: https://github.com/pacely/mailchimp-api-v3.
I've created a Laravel console command to do this. The code is:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Mailchimp\Mailchimp;
use Exception;
class ImportContactsIntoMailchimp extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'mailchimp:import:contacts';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Import contacts into mailchimp.';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* If an e-mail address starts with this, mailchimp won't allow it
* http://kb.mailchimp.com/lists/growth/limits-on-role-based-addresses
*
* #var array
*/
private $nomail = array(
'abuse#',
'admin#',
'billing#',
'compliance#',
'devnull#',
'dns#',
'ftp#',
'hostmaster#',
'inoc#',
'ispfeedback#',
'ispsupport#',
'list-request#',
'list#',
'maildaemon#',
'noc#',
'no-reply#',
'noreply#',
'null#',
'phish#',
'phishing#',
'postmaster#',
'privacy#',
'registrar#',
'root#',
'security#',
'spam#',
'support#',
'sysadmin#',
'tech#',
'undisclosed-recipients#',
'unsubscribe#',
'usenet#',
'uucp#',
'webmaster#',
'www#'
);
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$result = DB::table('contacts_billonline')
->select(
'email',
'firstname',
'surname',
'phone'
)
->get();
$batch_count = 250;
$email_column = 'email';
$merge_columns = array(
'EMAIL' => 'email',
'FNAME' => 'firstname',
'LNAME' => 'surname',
'PHONE' => 'phone',
);
$listId = $this->ask('What is the list id?');
// Create our mailchimp connection
$mailchimp_key = config('mailchimp.apikey');
$mc = new Mailchimp($mailchimp_key);
$contact_list = '/lists/'.$listId.'/members';
$total = count($result);
for ($i = 0; $i < $total; $i += $batch_count)
{
$batch = array();
for ($j = 0; $j < $batch_count; $j++)
{
$row_number = $i + $j;
if ($row_number === $total)
{
// If we reached the end of the list, stop trying to add operations
break;
}
// Get the email address from the result for this row
$email = &$result[$row_number]->{$email_column};
// Is this a valid email address? If so add it to the batch
if ($this->isValidEmail($email)) {
$this->info($email);
// Get our merge columns for this row and put them in the array
$merge_fields = array();
foreach ($merge_columns as $key => &$column) {
$merge_fields[$key] = &$result[$row_number]->{$column};
}
$insert_email = array(
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => $merge_fields,
'tags' => ['Contacts']
);
$batch_operation = array(
'method' => 'POST',
'path' => $contact_list,
'body' => json_encode($insert_email)
);
$batch[] = $batch_operation;
}
}
$body = array();
$body['operations'] = $batch;
$batch_result = $mc->post('/batches', $body);
$this->info($batch_result);
}
}
/**
* Is this is an email address mailchimp would see as valid?
*
* #param $email
* #return bool
*/
function IsValidEmail(&$email)
{
foreach ($this->nomail as &$bad_mail)
{
if (strpos($email, $bad_mail) === 0)
{
return false;
}
}
$validator = Validator::make(
array(
'email' => &$email
),
array(
'email' => 'required|email'
)
);
if ($validator->fails())
{
return false;
}
return true;
}
}
I'm trying to import the users from a database table in batch into Mailchimp.
The API key is set correctly. I'm also trying to set a tag "Contacts" to the subscribers.
The list id is also set correctly.
The problem is that the list isn't imported. The result in terminal is:
{"id":"c48cd17f6d","status":"pending","total_operations":0,"finished_operations":0,"errored_operations":0,"submitted_at":"2019-07-02T10:58:22+00:00","completed_at":"","response_body_url":"","_links":[{"rel":"parent","href":"https://us8.api.mailchimp.com/3.0/batches","method":"GET","targetSchema":"https://us8.api.mailchimp.com/schema/3.0/Definitions/Batches/CollectionResponse.json","schema":"https://us8.api.mailchimp.com/schema/3.0/CollectionLinks/Batches.json"},{"rel":"self","href":"https://us8.api.mailchimp.com/3.0/batches/c48cd17f6d","method":"GET","targetSchema":"https://us8.api.mailchimp.com/schema/3.0/Definitions/Batches/Response.json"},{"rel":"delete","href":"https://us8.api.mailchimp.com/3.0/batches/c48cd17f6d","method":"DELETE"}]}
What am I doing wrong?
I am creating a sponsorship system and I would like to display the names of the godchildren in a list.
I have a list of'ambassadors' whose ambassadors will have godchildren who will have other godchildren. At the moment I manage to display the number of godchildren for each ambassador, but I have trouble creating the script to display the name. Could you help me? Thank you.
public function adminAmbassadorsAction(Request $request)
{
/** #var UserManager $userManager * */
$ambassadors = $this->get('fos_user.user_manager');
$em = $this->getDoctrine()->getEntityManager(); # Getting the entity manager for future request.
/** #var UserRepository $repository * */
$repository = $em->getRepository('AppBundle:User');
// Recup all ambassadors
$ambassadors = $repository->findByRole("ROLE_AMBASSADOR");
$proprietesAmbassadeur = array();
// Iterate ambassadors
foreach ($ambassadors as $ambassador) {
// Recup all fileuls
// $ambassador = $this->getFullName(); // recup name parrain
$filleuls = $repository->findBy(array('parrain' => $ambassador->getId()));
foreach ($filleuls as $filleul) {
($filleul->getFullName());
}
$proprietesAmbassadeur[$ambassador->getId()] = count($filleuls);
}
// render the view
return $this->render('Admin/listing_sponsor.html.twig', [
'os_ambassadors' => $ambassadors,
'os_proprietes' => $proprietesAmbassadeur,
] );
}
}
You are not passing the god childs to the view.
I've rewritten your code so it passes the total of god childs and all their names.
public function adminAmbassadorsAction(Request $request)
{
/** #var UserManager $userManager * */
$ambassadors = $this->get('fos_user.user_manager');
$em = $this->getDoctrine()->getEntityManager(); # Getting the entity manager for future request.
/** #var UserRepository $repository * */
$repository = $em->getRepository('AppBundle:User');
// Recup all ambassadors
$ambassadors = $repository->findByRole("ROLE_AMBASSADOR");
$proprietesAmbassadeur = array();
// Iterate ambassadors
foreach ($ambassadors as $ambassador) {
// Recup all fileuls
// $ambassador = $this->getFullName(); // recup name parrain
$filleuls = $repository->findBy(array('parrain' => $ambassador->getId()));
$proprietesAmbassadeur[$ambassador->getId()] = array('total' => count($filleuls), 'filleulFullNames' => array());
foreach ($filleuls as $filleul) {
$proprietesAmbassadeur[$ambassador->getId()]['filleulFullNames'][] = $filleul->getFullName();
}
}
// render the view
return $this->render('Admin/listing_sponsor.html.twig', [
'os_ambassadors' => $ambassadors,
'os_proprietes' => $proprietesAmbassadeur,
] );
}
For a datatable I use in a page (webix datatable), I have to use a REST API.
My url is for example: http://localhost:8000/trial/1
In this page to make the api call I use the following:
save: "rest->{{ path('api_i_post') }}",
url: "rest->{{ path('erp_interventionapi_get', { trialid: trial.id })
With the GET method, I retrieve for a trial (/trial/1), many interventions which are loaded from a database and filled in the datatable.
With this datatable, I'm able to "add a new row". It uses the POST method (save: "rest->{{ path('api_i_post') }}")
When I add a new row, I'd like to be able to get the field trial_id filled in automatically, depending from where I add a new row in the datatable (for /trial/1, trial_id = 1) but I don't know how to retrieve this attribute (or the trial object id), in a POST and a PUT.
My postAction:
/**
* #Rest\Post("/api_i/", name="api_i_post")
*/
public function postAction(Request $request)
{
$data = new Intervention;
$id = $request->get('id');
$action = $request->get('action');
$daadala = $request->get('daadala');
$date = $request->get('date');
$week = $request->get('week');
$infopm = $request->get('info_pm');
$comment = $request->get('comment');
$location = $request->get('location');
$trial = $request->get('trialid');
$data->setAction($action);
$data->setDaadala($daadala);
$data->setDate($date);
$data->setWeek($week);
$data->setWho($infopm);
$data->setInfoPm($comment);
$data->setComment($location);
$data->setTrial($trial);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
$lastid = $data->getId();
$response=array("id" => $id, "status" => "success", "newid" => $lastid);
return new JsonResponse($response);
$view = View::create(array("newid" => $lastid, "id" => $id, "status" => "success"));
return $this->handleView($view);
}
And my putAction
/**
* #Rest\Put("/api_i/{id}")
*/
public function putAction(Request $request)
{
$data = new Intervention;
$id = $request->get('id');
$action = $request->get('action');
$daadala = $request->get('daadala');
$date = $request->get('date');
$week = $request->get('week');
$infopm = $request->get('info_pm');
$comment = $request->get('comment');
$location = $request->get('location');
$sn = $this->getDoctrine()->getManager();
$intervention = $this->getDoctrine()->getRepository('ErpBundle:Sponsor')->find($id);
if (empty($intervention)) {
return new View("Sponsor not found", Response::HTTP_NOT_FOUND);
}
$intervention->setAction($action);
$intervention->setDaadala($daadala);
$intervention->setDate($date);
$intervention->setWeek($week);
$intervention->setWho($infopm);
$intervention->setInfoPm($comment);
$intervention->setComment($location);
$sn->flush();
$response=array("id" => $id, "status" => "success");
return new JsonResponse($response);
}
Can you help me with this issue?
Thank you very much
Update of my code after the replys:
I have update this in my twig template:
save: "rest->{{ path('api_i_post', { trialid: trial.id }) }}",
If I look in the profiler of the ajax request, I see it is here:
Key Value
trialid "1"
But I still don't figure how to get it in my post request (the trial_id is still null right now)
I've tried the following:
/**
* #Rest\Post("/api_i/", name="api_i_post")
* #Rest\RequestParam(name="trialid")
*
* #param ParamFetcher $paramFetcher
* #param Request $request
*/
public function postAction(Request $request, ParamFetcher $paramFetcher)
{
$data = new Intervention;
$id = $request->get('id');
$action = $request->get('action');
$daadala = $request->get('daadala');
$date = $request->get('date');
$week = $request->get('week');
$infopm = $request->get('info_pm');
$comment = $request->get('comment');
$location = $request->get('location');
$trial = $paramFetcher->get('trialid');
$data->setAction($action);
$data->setDaadala($daadala);
$data->setDate($date);
$data->setWeek($week);
$data->setWho($infopm);
$data->setInfoPm($comment);
$data->setComment($location);
$data->setTrial($trial);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
$lastid = $data->getId();
$response=array("id" => $id, "status" => "success", "newid" => $lastid);
return new JsonResponse($response);
$view = View::create(array("newid" => $lastid, "id" => $id, "status" => "success"));
return $this->handleView($view);
}
I guess you are using the FosRestBundle, if so, you can use annotations to retrieve your url parameters :
/**
* #Rest\Put("/api_i/{id}", requirements={"id" = "\d+"})
*/
public function putAction($id)
{
// you now have access to $id
...
}
If you want to allow additionnal parameters for your route but not in the uri, you can use RequestParam with annotations :
/**
* #Rest\Put("/my-route/{id}", requirements={"id" = "\d+"})
*
* #Rest\RequestParam(name="param1")
* #Rest\RequestParam(name="param2")
*
* #param ParamFetcher $paramFetcher
* #param int $id
*/
public function putAction(ParamFetcher $paramFetcher, $id)
{
$param1 = $paramFetcher->get('param1');
....
}
Be sure to check the fosRestBundle documentation to see everything you can do (such as typing the params, making them mandatory or not, etc...)
To get post value you need to do this inside your post action:
public function postAction(Request $request)
{
$postData = $request->request->all();
Then you have an array of value like:
$id = $postData['id'];
For the PUT you need this:
public function putAction(int $id, Request $request)
{
$putData = json_decode($request->getContent(), true);
And then to treieve a value like this:
$id = $putData['id'];
I have a little problem when creating tests with PHPUnit.
Here is my setup :
protected function setUp()
{
$serviceManager = Bootstrap::getServiceManager();
$this->mockDriver = $this->getMock('Zend\Db\Adapter\Driver\DriverInterface');
$this->mockConnection = $this->getMock('Zend\Db\Adapter\Driver\ConnectionInterface');
$this->mockDriver->expects($this->any())->method('checkEnvironment')->will($this->returnValue(true));
$this->mockDriver->expects($this->any())->method('getConnection')->will($this->returnValue($this->mockConnection));
$this->mockPlatform = $this->getMock('Zend\Db\Adapter\Platform\PlatformInterface');
$this->mockStatement = $this->getMock('Zend\Db\Adapter\Driver\StatementInterface');
$this->mockDriver->expects($this->any())->method('createStatement')->will($this->returnValue($this->mockStatement));
$this->adapter = new Adapter($this->mockDriver, $this->mockPlatform);
$this->sql = new Sql($this->adapter);
$mockTableGateway = $this->getMock('Zend\Db\TableGateway\TableGateway', array(), array(), '', false);
$maiFormuleRevisionTable = $this->getMockBuilder('Maintenance\Model\BDD\PMaiFormulerevisionTable')
->setMethods(array())
->setConstructorArgs(array($mockTableGateway, $this->adapter, $this->sql))
->getMock();
$maiFormulerevisionService = $this->getMockBuilder('Maintenance\Service\Model\PMaiFormulerevisionService')
->setMethods(array())
->setConstructorArgs(array($maiFormuleRevisionTable))
->getMock();
$this->assertTrue($maiFormulerevisionService instanceof PMaiFormulerevisionService);
$this->controller = new RevisionsController($maiFormulerevisionService);
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->event = new MvcEvent();
$config = $serviceManager->get('Config');
$routerConfig = isset($config['router']) ? $config['router'] : array();
$router = HttpRouter::factory($routerConfig);
$this->event->setRouter($router);
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
$this->controller->setServiceLocator($serviceManager);
}
Here is the test for my function :
public function testEditFormuleActionCanBeAccessed()
{
$this->routeMatch->setParam('action', 'loadformule');
$this->routeMatch->setParam('idformule', '23');
$result = $this->controller->dispatch($this->request);
$response = $this->controller->getResponse();
$this->assertEquals(200, $response->getStatusCode());
}
And my Controler :
public function loadformuleAction()
{
try {
$iStatus = 0;
$iMaiFormuleRevisionId = (int) $this->params('idformule');
$oFormule = $this->maiFormulerevisionService->selectByIdOrCreate($iMaiFormuleRevisionId);
$maiFormulerevisionForm = new PMaiFormulerevisionForm($oFormule);
if ($this->getRequest()->isPost()) {
/* etc ... */
}
$viewModel = new ViewModel();
$viewModel->setTerminal(true);
$viewModel->setVariables([
'maiFormulerevisionForm' => $maiFormulerevisionForm,
'iMaiFormuleRevisionId' => $oFormule->getMaiFormuleRevisionId(),
'iStatus' => $iStatus
]);
return $viewModel;
} catch (\Exception $e) {
throw new \Exception($e);
}
}
But when I try to run my test, it shows an error, and I point that my test don't go into my service, when I call it ($this->maiFormulerevisionService) :
1) MaintenanceTest\Controller\RevisionsControllerTest::testEditFormuleActionCanBeAccessed
Exception: Argument 1 passed to Maintenance\Form\PMaiFormulerevisionForm::__construct() must be an instance of Maintenance\Model\PMaiFormulerevision, null given
I don't understand why my mock doesn't work ...
Thanks for your answers :)
Edit :
Hum ... when I try this :
$maiFormulerevisionService = new PMaiFormulerevisionService($maiFormuleRevisionTable);
Instead of this :
$maiFormulerevisionService = $this->getMockBuilder('Maintenance\Service\Model\PMaiFormulerevisionService')
->setMethods(array())
->setConstructorArgs(array($maiFormuleRevisionTable))
->getMock();
It goes into the service but not into the TableGateway specified in the constructor of the service ($maiFormuleRevisionTable) ... so it still doesn't work ...
You set a mock, but you also have to set what your mock returns when calling the method selectByIdOrCreate. Since you do:
$oFormule = $this->maiFormulerevisionService->selectByIdOrCreate($iMaiFormuleRevisionId);
$maiFormulerevisionForm = new PMaiFormulerevisionForm($oFormule);
The mock will return null for the selectByIdOrCreate method as long as you don't set a return value for this method.
Try to add a mock method like this:
$mock = $maiFormulerevisionService;
$methodName = 'selectByIdOrCreate';
$stub = $this->returnValue($maiFormuleRevisionTable);
$mock->expects($this->any())->method($methodName)->will($stub);
I am trying to delete a post from my table but the code is deleting all table data and not just the one post.
delete.php
<?php
class Form_Delete extends Zend_Form
{
public function __construct()
{
#parent::__construct($options);
$this->setName('Delete');
$id = new Zend_Form_Element_Hidden('id');
$title = new Zend_Form_Element_Hidden('Title');
$description = new Zend_Form_Element_Hidden('Description');
$submit = new Zend_Form_Element_Submit('Delete');
$submit->setAttrib('id', 'submitbutton');
$cancel = new Zend_Form_Element_Submit('cancel');
$cancel->setAttrib('id', 'cancelbutton');
$this->addElements( array( $id, $title, $description, $submit, $cancel ));
}
}
and my controller code
public function deleteAction()
{
//action body
$request = $this->getRequest();
$postid = (int)$request->getParam('id');
$post = new Model_DbTable_Posts();
$result = $post->getPost($postid);
$this->view->post = $result;
if(!Zend_Auth::getInstance()->hasIdentity()) {
$this->_redirect('posts/view/id/'.$postid);
}
$identity = Zend_Auth::getInstance()->getIdentity();
$acl = new Model_Acl();
if( $acl->isAllowed( $identity['Role'] ,'posts','edit','delete') ) {
$deleteForm = new Form_Delete();
$deleteModel = new Model_DbTable_Posts();
if ($this->getRequest()->isPost()) {
if ($deleteForm->isValid($request->getPost())) {
$deleteModel->delete($dpostid);
$this->_redirect('index/index');
}
}
$this->view->deleteForm = $deleteForm;
}
I have tried for hours to get this working but can ether get it to delete all or nothing. Any help would be great!
You need to pass delete() the where clause to evaluate. Try:
$where = $deleteModel->getAdapter()->quoteInto('id = ?', $dpostid);
$deleteModel->delete($where);
Change 'id' to whatever your primary key is.
Also #parent::__construct($options); in your form class is a little odd. Change that to parent::__construct();. No need to supress the error if you don't generate one.