How to write query to get exact details of user taking leave by summing their leave taken days as per their user id - eloquent

I am building a Laravel project for the Attendance Management System. In there I want to show the user leave details in their dashboard.
Leave Table
Leave Table
Leave Application Table
Leave Application Table
Actually, I want to show all the different type of leave that's the user take, their sum of leave taken days by the user and total leave days.
Dashboard Controller
Getting the leave id
$get_leave_id = LeaveApplication::where('user_id', Auth::user()->id)
->where('statuses_id', 2)
->pluck('leave_id');
Getting all leave details from the user
$user_leaves = LeaveApplication::with('leave')
->where('statuses_id', '=', 2)
->whereIn('leave_id', $get_leave_id)
->get();
Model
public function leave()
{
return $this->belongsTo(Leave::class, 'leave_id', 'id');
}
View Page
{{ $leave->leave->leave_name }} ==> Sick leave
{{ $leave->leave_taken_days }} / {{ $leave->leave->total_leave_days }} ==> 4/12
Result I am getting
What I want is this
Result I want
Please help to build up the query . Thank you

You can simplify the way you collect data as follows:
$application = LeaveApplication::with('leave')
->where(['user_id' => Auth::user()->id, 'statuses_id' => 2])
->first();
Then you can count the data as you like:
$leave_taken_days = $application->leave->sum('leave_taken_days');
$total_leave_days = $application->leave->sum('total_leave_days');
and in the view you can pass the variables directly to the view and call them: $leave_taken_days and $total_leave_days

Related

Adding columns to a Web2py table in a form

In my web2py application, in the controller I read from an external DB the names of students I want to take a register for. I loop through the resulting list adding the list elements to a new list.
for student in pupils_query:
attendance_list.insert(counter, [student[0], student[1], student[2], student[3]])
counter += 1
counter = 0
Then for each student I read their attendance codes for the day so far from another table, and append them to attendance_list:
for attendance_code in attendance_result:
attendance_list[counter].append(attendance_code)
Now, I'm going to want to make a form from all this, using a table which will show each students' attendance code in a text input (so they can be updated if wrong), then have a dropdown for input of the current lesson code.
I'm using a FORM and TABLE helper to create the table in the form:
form=FORM(TABLE(*[TR(*rows) for rows in attendance_list]))
but can't seem to be able to add a new 'row' form item with something like:
select = "SELECT("+ main_reg_list +")"
attendance_list[counter].append(select)
where main_reg_list is dictionary of acceptable attendance codes (or of course, any other form input element).
In summary, I'm stuck adding new TDs to a table made with a TABLE helper from a list of lists. I bet I'm not the first person to overcome this problem.
I am still not clear about what you want. I think you want table of student information and in one column you want dropdown. Something similat to following image
Above form is created from following code.
I hope following code will help you:
# controller/default.py
def index():
# Dummy attendance list, list after appending attendance code
attendance_list = [['stud_id_1', 'first_name_1', 'last_name_1', 'attendance_code_1'],
['stud_id_2', 'first_name_2', 'last_name_2', 'attendance_code_2'],
['stud_id_3', 'first_name_3', 'last_name_3', 'attendance_code_5'],
['stud_id_4', 'first_name_4', 'last_name_4', 'attendance_code_4']]
possible_att_code = ['attendance_code_1', 'attendance_code_2', 'attendance_code_3', 'attendance_code_4', 'attendance_code_5']
# initialise form_rows with Table heading
form_rows = [THEAD(TR(TH('ID'), TH('First Name'), TH('Last Name'), TH('Attendence Code')))]
for attendance in attendance_list:
attendance_code_dropdown = _get_dropdown(attendance[0], attendance[3], possible_att_code)
td_list = [TD(attendance[0]), TD(attendance[1]), TD(attendance[2]),
TD(attendance_code_dropdown)]
table_row = TR(td_list, _id='row_' + attendance[0])
form_rows.append(table_row)
# Form submit button
form_rows.append(TR(INPUT(_type='submit')))
form = FORM(TABLE(*form_rows), _name='student_attendance',
_id='student_attendance')
if form.accepts(request, session):
# Write code to update record
pass
return dict(form=form)
def _get_dropdown(stud_id, att_code, possible_att_code):
option_list = []
for pac in possible_att_code:
if pac == att_code:
option_list.append(OPTION(pac, _value=pac, _selected='selected'))
else:
option_list.append(OPTION(pac, _value=pac))
return SELECT(*option_list, _name=stud_id)
<!-- views/default/index.html -->
{{extend 'layout.html'}}
{{=form}}
Are my assumptions correct? or you want any thing else? Comment if didn't understood code.

Moodle Database API error : Get quiz marks for all sections of one course for one user

I am trying to get total marks obtained by a particular user, for a particular course for all the sections of that course.
The following query works and gives correct results with mysql, but not with Databse API calls
$sql = "SELECT d.section as section_id,d.name as section_name, sum(a.sumgrades) AS marks FROM mdl_quiz_attempts a, mdl_quiz b, mdl_course_modules c, mdl_course_sections d WHERE a.userid=6 AND b.course=4 AND a.quiz=b.id AND c.instance=a.quiz AND c.module=14 AND a.sumgrades>0 AND d.id=c.section GROUP BY d.section"
I tried different API calls, mainly I would want
$DB->get_records_sql($sql);
The results from API calls are meaningless. Any suggestion?
PS : This is moodle 2.2.
I just tried to do something similar, only without getting the sections. You only need the course and user id. I hope this helps you.
global $DB;
// get all attempts & grades from a user from every quiz of one course
$sql = "SELECT qa.id, qa.attempt, qa.quiz, qa.sumgrades AS grade, qa.timefinish, qa.timemodified, q.sumgrades, q.grade AS maxgrade
FROM {quiz} q, {quiz_attempts} qa
WHERE q.course=".$courseid."
AND qa.quiz = q.id
AND qa.userid = ".$userid."
AND state = 'finished'
ORDER BY qa.timefinish ASC";
$exams = $DB->get_records_sql($sql);
// calculate final grades from sum grades
$grades = array();
foreach($exams as $exam) {
$grade = new stdClass;
$grade->quiz = $exam->quiz;
$grade->attempt = $exam->attempt;
// sum to final
$grade->finalgrade = $exam->grade * ($exam->maxgrade / $exam->sumgrades);
$grade->grademax = $exam->maxgrade;
$grade->timemodified = $exam->timemodified;
array_push($grades, $grade);
}
This works in latest moodle version. Moodle 2.9. Although I am still open for better solution as this is really hacky way of getting deeper analytics about user's performance.

In Yii, how best to POST both search results selection & previously entered form model back to form controller?

To complete a Yii form field, users often need to search for a referenced model record (like searching for a friend's profile in a social app). I'm sure other Yii apps are doing this elegantly. But in my dirty approach, in the search results page, I use a CHtml::submitButton to POST two models back to the form containing:
the "found" record (a user id associated with one of the profiles from the search results)
the previously entered form field contents (relationship characterization fields)
Alternatively, the autocomplete widget works well, but doesn't do the detailed search that I need (e.g. search based on a partial name and city or state or other user profile content).
Alternatively, you'd think that within the search results view I might be able to modify the form member to contain the found record (new friend's user id) and just POST/submit the modified model from the search results page . But for that to work each of the search results in the list needs a unique user id populated in that form field, and I can't figure out how to duplicate the form model before modifying that one member server-side for each of the search results' "submit" or "select" buttons, and it just doesn't seem right to create all those form models.
So what seems to work is to submit two separate models using subforms (within the search results view) , with the submitButton POSTing a model and the extra parameter (user id) separately.
Is there a better way? ...to link to and from a search results page and a form field, retaining already-entered data and populating the searched for field with a selected record from the search results.
Here's controllers/SiteController:
public function actionBefriend() {
$model=new BefriendForm;
if(isset($_POST['BefriendForm'])) {
$model->attributes=$_POST['BefriendForm'];
if ($model->validate()) {
$model->createFriendship();
$this->redirect('Index'); }
else
$er=$model->getErrors(); }
if(isset($_POST['idfriend'])) {
$model->idfriend=$_POST['idfriend']; }
if(isset($model->idfriend)) {
$model->friend_name=Bio::model()->findByPk($model->idfriend)->name; }
$this->render('newFrienship', array('model' =>$model)); // newFriendship is the form view }
Here's controllers/Bio.php (Profile)
public function actionIndex() {
$criteria = new CDbCriteria();
$model=new BefriendForm;
if(isset($_GET['q']))
$q = $_GET['q'];
elseif (isset($_POST['BefriendForm'])) {
$model->attributes=$_POST['BefriendForm'];
$q = $model['friend_name']; }
if(isset($q)) {
$criteria->compare('name', $q, true, 'OR');
$criteria->compare('city', $q, true, 'OR');
$criteria->compare('state', $q, true, 'OR');
$criteria->compare('bio_text', $q, true, 'OR'); }
else
$q = '';
$dataProvider=new CActiveDataProvider('Bio', array('criteria'=>$criteria));
$this->render('index',array('dataProvider'=>$dataProvider, 'q'=>$q, 'model'=>$model )); }
Here's the start of views/site/newFriendship (form view)
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'newFriendship-BefriendForm',
'enableAjaxValidation'=>true,)); ?>
Here's the core of views/bio/index.php (search results index page):
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'viewData'=>array('model'=>$model) )); ?>
Here's the search result row in views/bio/_view.php that links back to BefriendForm (SiteController) that sends the id of the user to populate the friend field in the form (which gets a name from the id):
<form method="POST">
<input type="hidden" name="idfriend" value="<?php echo $data->idfriend ?>" />
// Here's that submit button that I can't get to send both the model
//and the idfriend back to the form to repopulate it
// without manually writing HTML to submit all the fields individually
// or creating 2 subforms to submit together with a signle submitButton.
<?php echo CHtml::submitButton('Befriend', array('submit' => array('site/Befriend'),'model'=$model);
</form>
The best alternative I can see is to imbibe the searcher widget within the form.
Turns out you can just replace the form field containing the primary key with the appropriate value before POSTing back to the NewFriendship form when the user clicks the "Select" or "Befriend" button. So only one model is posted back to the original form from the search results page.
Replace the section from views/bio/_view.php in the question with...
<?php
foreach($model->attributeNames() as $name)
if($name != 'friend_id')
echo CHtml::activeHiddenField($model,$name);
else
echo CHtml::activeHiddenField($model,$name,array('value'=>$data->getPrimaryKey()));
echo CHtml::submitButton('Befriend', array('submit' => array('site/Befriend')));
?>

Help needed formatting Doctrine Query in Zend Framework

Can anyone tell me how to format the query below correctly in my controller.
Currently it gives me nothing in my FilteringSelect. However if I change it to >= I get back all the kennelIDs which is incorrect also but at least I'm getting something.
I've tested that the session variable is set and can confirm that there are kennels with the matching capacity.
// Create autocomplete selection for the service of this booking
public function servkennelAction()
{
$sessionKennelBooking = new Zend_Session_Namespace('sessionKennelBooking');
// disable layout and view rendering
$this->_helper->layout->disableLayout();
$this->getHelper('viewRenderer')->setNoRender(true);
// get list of grooming services for dogs from the table
$qry= Doctrine_Query::create()
->from('PetManager_Model_Kennels k');
//This should be set by default and narrows down the search criteria
if(isset($sessionKennelBooking->numPets)){
$b=(int)$sessionKennelBooking->numPets;
$qry->addWhere('k.capacity = ?','$b');
}
$result=$qry->fetchArray();
//generate and return JSON string using the primary key of the table
$data = new Zend_Dojo_Data('kennelID',$result);
echo $data->toJson();
}
Many thanks in Advance.
Graham
I think that addWhere condition is wrong. It has to be:
$qry->addWhere('k.capacity = ?', $b);
i.e. $b without quotes.

How to populate zend form field using session?

I am using sessions to populate a multi select box with options in my Zend application.
The user selects one or more options and fills in other fields on the form and then submits. If the user didn't select all of the options in the multi select then the form is displayed again but the multi select only has the options that the user did not select the last time. This process goes on until there are no more options from the multi select left to process.
Here is the code I use to get rid of the options that have already been processed so that they are not used to populate the multi select box:
if($form_successful){
// TODO remove $post['keyword_names'] (i.e. already processed) from $keyword_names (that come from $_SESSION)
$keyword_names = array_diff($keyword_names, $post['keyword_names']);
print_r($keyword_names);
if(is_array($keyword_names) && !empty($keyword_names)){
// save updated $keyword_names into $_SESSION['workflow1']
$session = new Zend_Session_Namespace('workflow1');
$session->keyword_names = $keyword_names;
// set flag to false so that we display form again
$form_successful = false;
}else{ // all keywords have been assigned
// go to next step
$this->_redirect('/workflow-1/step-'.($step+1).'/');
}
}
print_r($keyword_names); displays the correct options, however when the form is loaded when the user submits, the multi select displays the options that were there from the begining ie the options the user has just selected and submitted are not being taken out of the multi select, it is only when the user submits the form again then the multi select box updates.
Appreciate the help.
Solved the issue by making use of URL parameters. Here is the code (might differ a lot from what I posted first because some big changes were made):
// after successful form submission
if($form_successful){
// remove $post['keyword_names'] (i.e. already processed) from $keyword_names (that come from $_SESSION)
$keyword_names = array_diff($keyword_names, $post['keyword_names']);
// save remaining $keyword_names into $_SESSION['workflow1']
$session = new Zend_Session_Namespace('workflow1');
$session->keyword_names = $keyword_names;
if(is_array($keyword_names) && !empty($keyword_names)){
// redirect to the same step again - to ensure that the form will reflect (in select lists) newly created AdGroup and/or Campaign
// GET parameteres ($params_array) provide a way to remember user's choice
$params_array = array();
if(!empty($post['match_type_id'])){
$params_array['match_type_id'] = $post['match_type_id'];
}
if(!empty($post['with_permutations'])){
$params_array['with_permutations'] = $post['with_permutations'];
}
if(!empty($ad_group_id)){
$params_array['ad_group_id'] = $ad_group_id;
}
$this_step_url = UrlUtils::assemble('', $this->getRequest()->getActionName(), $this->getRequest()->getControllerName(), $this->getRequest()->getModuleName(), $params_array);
$this->_redirect($this_step_url);
}else{ // all keywords have been assigned
// go to next step
$this->_redirect('/workflow-1/step-'.($step+1).'/');
}
}
So you don't have any code about Zend_Form object here. How do you populate the form element? If you post your class code which extends Zend_Form (or any other code dials with your form) then I may help. But in any case you can populate your multiselectbox with setMultiOptions() method or addMultiOption() for each item in multiselectbox.