How to fix my "Notice: Undefined offset: 4" error - php

I have a problem with my code, when a User have all "stations" the code work but if he dont have one i have the (undefined offset *) error,
my code look like that ( in my controller )
public function index()
{
$entityManager = $this->getDoctrine()->getManager();
$stations = $this->getListOfStations();
$stationsJson = [];
$events = $entityManager->getRepository('App:User')
->getEventInRealTime($this->getUser());
foreach ($stations as $station) {
$stationsJson[] = [
'typeEvents' => $events[$station->getId()],
];
}
return new JsonResponse(array('stations' => $stationsJson));
}
private function getListOfStations()
{
/** #var UserInterface $user */
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
if (!$this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
$stations = $user->getStations();
} else {
$stations = $entityManager->getRepository('App:Station')->findAll();
}
return $stations;
}
and my repository
public function getEventInRealTime($user)
{
$qb = $this->createQueryBuilder('u');
$events = $qb
->select('s.id as stationId, COUNT(e) as number, e.label as type')
->innerJoin('u.stations', 's')
->innerJoin('s.events', 'e')
->where('u = :user')
->setParameter('user', $user)
->andWhere('DAY(e.currentTime) =:day')
->setParameter('day', date('d'))
->andWhere('MONTH(e.currentTime) =:month')
->setParameter('month', date('m'))
->andWhere('YEAR(e.currentTime) =:year')
->setParameter('year', date('Y'))
->groupBy('s.id, type');
$data = $events->getQuery()->getArrayResult();
$result = [];
foreach ($data as $row) {
$result[$row['stationId']][] =
[
'number' => $row['number'],
'type' => $row['type']
];
}
return $result;
}
i think its a problem its like, he dont find the "stations" when i do a findAll(), but i dont know how to fix it, when the user is super_admin he can have see all the stations but if is not super admin he can see only his stations

Related

How Can I specified the object of my precedent form?

In my project I want to use the object created by my precedent form:
Here is the schema of my database:
My QuizController
public function creation(Request $request){
$quiz = new Quiz();
$user = $this->getUser();
$formQuiz = $this->createForm(QuizType::class, $quiz);
$formQuiz->handleRequest($request);
if ($formQuiz->isSubmitted() && $formQuiz->isValid() ) {
$quiz->setCreatedAt(new DateTimeImmutable());
$quiz->setCreatedBy($user);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($quiz);
$entityManager->flush();
return $this->redirectToRoute('creation_questions');
}
return $this->render('quiz/creation.html.twig', [
'formQuiz' => $formQuiz->createView(),
]);
}
And my QuestionController that must be connected with the quiz form
public function creation_questions(Request $request){
$quiz = ?
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid() ) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
What do I have to write in place of the '?'?
You don't show your routing but you could use paramConverte "magic" from SensioFrameworkExtraBundle and do something like this.
/**
* #Route("/some-route/{id}", name="some_route_name")
*/
public function creation_questions(Request $request, Quiz $quiz)
{
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid()) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
Where the {id} part of /someRoute/{id} is the Quiz Id. Symfony should automagically fetch the Quiz matching that id. Or you can be more explicit about how the param converter should interpret such a value. More info here https://symfony.com/bundles/SensioFrameworkExtraBundle/current/annotations/converters.html
Alternatively, you could pass the quiz id and fetch the quiz manually (less magic but totally legit).
/**
* #Route("/some-route/{id}", name="some_route_name")
*/
public function creation_questions(Request $request, int $id)
{
$entityManager = $this->getDoctrine()->getManager();
$quiz = $entityManager->getRepository(Quiz::class)->find($id);
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid()) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}

how to change OctoberCms rainlabs blogpost plugin from sending automatic email with public function afterSave() to isPublished?

This piece of code shows a smll part of the models post.php from October Rainlab Blog plugin. The AfterSave() function is modified, it sends an e-mail when a new blogPost in the backend is saved by the administrator, however, I would like to send it when it is actually Published and make sure it is not sending multiple times. How could I accomplish this?
public function filterFields($fields, $context = null)
{
if (!isset($fields->published, $fields->published_at)) {
return;
}
$user = BackendAuth::getUser();
if (!$user->hasAnyAccess(['rainlab.blog.access_publish'])) {
$fields->published->hidden = true;
$fields->published_at->hidden = true;
}
else {
$fields->published->hidden = false;
$fields->published_at->hidden = false;
}
}
public function afterValidate()
{
if ($this->published && !$this->published_at) {
throw new ValidationException([
'published_at' => Lang::get('rainlab.blog::lang.post.published_validation')
]);
}
}
public function beforeSave()
{
if (empty($this->user)) {
$user = BackendAuth::getUser();
if (!is_null($user)) {
$this->user = $user->id;
}
}
$this->content_html = self::formatHtml($this->content);
}
public function afterSave()
{
$user = BackendAuth::getUser();
if ($user && $user->hasAnyAccess(['rainlab.blog.access_publish'])) {
$susers = Db::select('select * from users where is_activated = ?', [1]);
foreach ($susers as $suser) {
$currentPath = $_SERVER['PHP_SELF'];
$pathInfo = pathinfo($currentPath);
$hostName = $_SERVER['HTTP_HOST'];
$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
$protocol.'://'.$hostName.$pathInfo['dirname']."/";
$spost_url = $protocol.'://'.$hostName.$pathInfo['dirname']."/"."nieuws/".$this->attributes['slug'] ;
$stitle = $this->attributes['title'] ;
$body = '<div> Hallo '.$suser->name.'</br> Er is zojuist een nieuws bericht gepubliceerd voor alle leden van mycompany.nl , je kunt hier het bericht lezen aangaande: '.$stitle.' </div>' ;
//$from = $user->email ;
$from = 'noreply#mycompany.nl';
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n";
mail($suser->email,'Nieuws van mycompany', $body,$headers);
}
}
}
/**
* Sets the "url" attribute with a URL to this object.
* #param string $pageName
* #param Controller $controller
* #param array $params Override request URL parameters
*
* #return string
*/
public function setUrl($pageName, $controller, $params = [])
{
$params = array_merge([
'id' => $this->id,
'slug' => $this->slug,
], $params);
if (empty($params['category'])) {
$params['category'] = $this->categories->count() ? $this->categories->first()->slug : null;
}
// Expose published year, month and day as URL parameters.
if ($this->published) {
$params['year'] = $this->published_at->format('Y');
$params['month'] = $this->published_at->format('m');
$params['day'] = $this->published_at->format('d');
}
return $this->url = $controller->pageUrl($pageName, $params);
}
/**
* Used to test if a certain user has permission to edit post,
* returns TRUE if the user is the owner or has other posts access.
* #param User $user
* #return bool
*/
public function canEdit(User $user)
{
return ($this->user_id == $user->id) || $user->hasAnyAccess(['rainlab.blog.access_other_posts']);
}
public static function formatHtml($input, $preview = false)
{
$result = Markdown::parse(trim($input));
// Check to see if the HTML should be cleaned from potential XSS
$user = BackendAuth::getUser();
if (!$user || !$user->hasAccess('backend.allow_unsafe_markdown')) {
$result = Html::clean($result);
}
if ($preview) {
$result = str_replace('<pre>', '<pre class="prettyprint">', $result);
}
$result = TagProcessor::instance()->processTags($result, $preview);
return $result;
}
//
// Scopes
//
public function scopeIsPublished($query)
{
return $query
->whereNotNull('published')
->where('published', true)
->whereNotNull('published_at')
->where('published_at', '<', Carbon::now())
;
}
/**
* Lists posts for the frontend
*
* #param $query
* #param array $options Display options
* #return Post
*/
public function scopeListFrontEnd($query, $options)
{
/*
* Default options
*/
extract(array_merge([
'page' => 1,
'perPage' => 30,
'sort' => 'created_at',
'categories' => null,
'exceptCategories' => null,
'category' => null,
'search' => '',
'published' => true,
'exceptPost' => null
], $options));
$searchableFields = ['title', 'slug', 'excerpt', 'content'];
if ($published) {
$query->isPublished();
}
One way to accomplish this would be to extend the Post model.
As an example, you create a new plugin and model with an is_notified field.
You would then add something like this to the boot() method of your new plugin:
PostModel::extend(function ($model) {
$model->hasOne['your_model'] = ['Author\PluginName\Models\YourModel'];
});
PostsController::extendFormFields(function ($form, $model, $context) {
// Checking for Post instance
if (!$model instanceof PostModel) {
return;
}
// without this code you can get an error saying "Call to a member function hasRelation() on null"
if (!$model->your_model) {
$model->your_model = new YourModel;
}
}
You can then use that new model in the afterSave method
public function afterSave()
{
$user = BackendAuth::getUser();
if ($user && $user->hasAnyAccess(['rainlab.blog.access_publish'])) {
$susers = Db::select('select * from users where is_activated = ?', [1]);
foreach ($susers as $suser) {
...
if ($this->your_model->is_notified != true) {
mail($suser->email,'Nieuws van mycompany', $body,$headers);
$this->your_model->is_notified = true;
}
}
}
}
You should also consider using the extend method instead of modifying 3rd party plugin code. This will allow you to update the plugin without losing your edits. Something like this:
PostModel::extend(function ($model) {
$model->hasOne['your_model'] = ['Author\PluginName\Models\YourModel'];
// You can transfer your afterSave code here!
$model->bindEvent('model.afterSave', function () use ($model) {
$user = BackendAuth::getUser();
if ($user && $user->hasAnyAccess(['rainlab.blog.access_publish'])) {
..
}
});
});
Let me know if you have any questions!

Replace Having Cause with Where Clause

Please i have some trouble in my project in symfony
How can i replace having clause wuĆ­th where clause in this code above cause having clause dont work white paginator in symfony
...
...
public function getAllClients($all = true, $user = null)
{
$qb = $this->_em->createQueryBuilder();
//
$qb->select('u, count(ls.id) as nbr')
->from($this->_entityName, 'u')
->join(Client::class, 'c', Join::WITH, 'c.user = u.id')
->join(LicenceShop::class, 'ls', Join::WITH, 'ls.client = c.id')
->groupBy('u.id')
->having('nbr > 1');
$qb->andWhere('u.roles LIKE :roles');
$qb->setParameter('roles', '%"ROLE_CLIENT"%');
return $qb->getQuery();
}
Thanks you
When i use having clause symfony response like that
Cannot count query that uses a HAVING clause. Use the output walkers for pagination
And this the function
enter code public function show($id = null, UserRepository $userRepository, Request $request, PaginatorInterface $paginator)
{
if($id)
$user = $userRepository->find($id);
else
$user = $this->getUser();
$client = $user->getClientInfo();
$myClients = $userRepository->getAllClients(false, $user);
$myClients = $paginator->paginate(
$myClients,
$request->query->getInt('page_c', 100)
);
$referal = null;
$licences = null;
if ($client) {
$referal = $client->getReferal();
$licences = $client->getLicences();
}
//$licences = $module->getLicences();
return $this->render('resellers/show.html.twig', [
'controller_name' => 'ResellersController',
'user' => $user,
'client' => $client,
'referal' => $referal,
'licences' => $licences,
'my_clients' => $myClients,
]);
}

How should I prophesy the sort method?

I am using the DoctrineMongoDBBundle and I am not sure how to prophesy the sort method.
Source
$qb = $dm->createQueryBuilder('Article')
->sort('createdAt', 'desc');
My code is:
UserRepository - Method All
public function all(array $input = null)
{
$user = UserEntity::class;
$all = $this->dm->createQueryBuilder($user);
$search = $all->sort(['name' => 'asc'])
->getQuery();
return $search;
}
UserRepositoryTest - prophecy
public function testSortingResults()
{
$output = [
'name' => 'John',
'email' => 'john#email.com',
'phone' => '89564789547',
];
$document = $this->prophesize(DocumentManager::class);
$queryBuilder = $this->prophesize(QueryBuilder::class);
$queryBuilder->sort()->willReturn($output)->shouldBeCalled();
$queryBuilder->getQuery()->willReturn($output)->shouldBeCalled();
$document->createQueryBuilder(UsuarioEntidade::class)->willReturn($queryBuilder)->shouldBeCalled();
$repository = new UserRepository($document->reveal());
$all = $repository->all();
$this->assertNotNull($all);
$this->assertEquals($output, $all);
}
The error is always this
Prophecy\Exception\Doubler\MethodNotFoundException: Method Double\Doctrine\ORM\QueryBuilder\P2::sort() is not defined.
I do not understand how to test SORT, because it is not found in QueryBuilder.

Why is Zend DB Update not posting?

Other modules in the application are updating, besides this one.
Here, I am using a model mapper in attempts to update a row set, as found in http://framework.zend.com/manual/en/learning.quickstart.create-model.html
public function SomeAction()
{
$mapper = new Application_Model_SomeMapper();
$model = new Application_Model_SomeModel(); //getters and setters
// action body
$request = $this->getRequest();
$data = $this->_request->getParams();
$someId = $data['someid'];
$get = $mapper->find($someId, new Application_Model_SomeModel, true); //find the row by id, and return array
/*
instantiating a form object and adding "submit"
*/
$form = new Module_Form_FormName();
$form->setAction("/module/controller/action/params/$someId");
$form->setMethod('post');
$form->setName('some_edit');
$submit = $form->createElement('button', 'submit');
$submit->setAttrib('ignore',true);
$submit->setLabel('Edit Something');
$form->addElement($submit);
if ($this->_request->isPost())
{
if($form->isValid($request->getPost()))
{
$data = $this->_request->getPost();
if(empty($data['some_id' ]))
{
$data['tier_models_id'] = NULL;
}
unset($data['submit']);
$setters = $model->setId($data['id'])
->setField1($data['field_1']);
if ($mapper->save($someId, $setters))
{
$this->_redirect("/index/");
}
}
}
$form->populate($tier);
$this->view->form = $get;
}
Here is an example of the save mapper function, except I've included an additional $id parameter
public function save(Application_Model_Guestbook $guestbook)
{
$data = array(
'email' => $guestbook->getEmail(),
'comment' => $guestbook->getComment(),
'created' => date('Y-m-d H:i:s'),
);
if (null === ($id = $guestbook->getId())) {
unset($data['id']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('id = ?' => $id)); //not happening, although the 'id' is passed as a param
}
}
Is there something missing?
Try this instead
$where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
$this->getDbTable()->update($data, $where);

Categories