Moodle block visibility per role on quiz attempt page - plugins

I have been following this tutorial successfully and created a small custom block.
I need this block to display on maths quiz/attempt.php pages but I have two problems.
The block displays for the admin user but does not display for students
How do I display the block only on selected quizes i:e maths and not english quizes
CODE:
class block_customfeedback extends block_base {
public function init() {
$this->title = get_string('customfeedback', 'block_customfeedback');
}
public function get_content() {
if ($this->content !== null) {
return $this->content;
}
$form .= "<form action='http://www.remoteserver.com/response.php' method='post'>";
$form .= "<label>Question ID</label> <input name='QuestionID' id='questionid' type='text' />";
$form .= "<label>Quiz Name</label> <input name='QuizName' id='quizname' type='text' />";
$form .= "<label>Your Feedback</label> <textarea name='Feedback' id='feedback' type='text' ></textarea>";
$form .= "<input type='submit' value='Submit' />";
$form .= "</form>";
$this->content = new stdClass;
$this->content->text = $form;
// $this->content->footer = 'Footer here...';
return $this->content;
}
public function applicable_formats() {
return array(
'all' => true
);
}
} // close class

You can make your block visible on quiz attempt page.
Steps:
Go to your quiz settings page.
Click on appearance
Click on show more
Change the value of "Show blocks during quiz attempts" to Yes.
Now login with student and check.

Related

codeigniter, form validation false verse first time visit

In Codeigniter, the following code is typically used for a page that has a form. But the first time a user lands on the page and a form validation fails gets routed through the same path.
As this example shows, the flash data will trigger. even if the user just land on the page and have not submit any form yet.
I am trying to echo a new class name to some input field to highlight them if validation fails. but currently it highlights the field on first load as well.
I am aware I can echo a validation_error or form_error. is there a way to echo a generic message that is not tied to a field-name and only after submission fails
// rules and other stuff above
if ($this->form_validation->run() == FALSE){
$this->session->set_flashdata('errorClass',"is-invalid");
$this->load->view('defaultOrFalse');
}else{
$this->load->view('success');
}
//view file
<input class=" <?php $this->session->flashdata('errorClass') ; ?>">
Basically I am trying to get bootstrap 4's input validation to show up
https://getbootstrap.com/docs/4.0/components/forms/#server-side
I don't know your exact setup but you can do logic like the following:
<?php
class Some_controller extends CI_Controller {
// controller/search/{$term}
public function some_method($term = null) {
// where some_field is some field in your form
// that gets posted on submit
if ($this->input->post('some_field')) {
// or if (isset($_POST)) {
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('errorClass', "is-invalid");
$this->load->view('defaultOrFalse');
} else {
$this->load->view('success');
}
} else {
// default view
}
}
}
?>
For your second question:
<h5>Username</h5>
<?php echo form_error('username'); ?>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" <?php if (!empty(form_error('username'))) { echo "class='error'"; } ?> />
Can also make a helper and use instead of form_error to check if field has error for your class (haven't verified this works but it should).
/**
* Checks if form validation field by name
* has error
*
* #param string $field Name of field
* #return boolean
*/
function field_has_error($field) {
$CI = &get_instance();
$CI->load->library('form_validation');
$arr = $CI->form_validation->error_array();
if (isset($arr[$field])) {
return true;
}
return false;
}
Usage:
<?php if (field_has_error('username')) { echo "class='error'"; } ?> />

Laravel 5.4 how to exclude empty field in url when GET form?

I built form with GET method but when i submit form empty field also pass to url, can i exclude empty field from passing to url ?
For example > when i submit my form url changed to :
?jobTitle=Title&jobCompany=CompanyName&jobGovernorate=&jobLocation=&postingDate=ad
Here in this example jobGovernorate and jobLocation is empty so i want form skip those when i submit the form.
If there's a way to get url like this
?jobTitle=Title&jobCompany=CompanyName&postingDate=ad
Because jobGovernorate and jobLocation is empty
Sorry for poor english, Thank you.
You can use middleware for your problem
class StripEmptyParams
{
public function handle($request, Closure $next)
{
$query = request()->query();
$querycount = count($query);
foreach ($query as $key => $value) {
if ($value == '') {
unset($query[$key]);
}
}
if ($querycount > count($query)) {
$path = url()->current() . (!empty($query) ? '/?' . http_build_query($query) : '');
return redirect()->to($path);
}
return $next($request);
}
}
then call for specific route like code below
Route::get('/search','YourController#search')->middleware(StripEmptyParams::class);
Assuming you have a form as below
<form>
<input type="text" class="url_params" name="jobTitle" value="">
<input type="text" class="url_params" name="jobCompany" value="">
<input type="text" class="url_params" name="jobGovernorate" value="">
<input type="text" class="url_params" name="jobLocation" value="">
<input type="text" class="url_params" name="postingDate" value="">
<input type="submit" name="submit" id="submit">
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#submit").on("click", function(e) {
e.preventDefault();
var url = '{{ url('/') }}?';
var total = $(".url_params").length;
$(".url_params").each(function (index) {
if ($(this).val().trim().length) {
if (index === total - 1) {
url += $(this).attr('name') + '=' + $(this).val();
} else {
url += $(this).attr('name') + '=' + $(this).val() + "&";
}
}
});
window.location.href = url;
});
});
</script>
The above code will generate an URL based on the field value and redirect to the url. So it won't generate a url with the empty field value key.
And having an empty field value shouldn't make a difference as you could check for the url values in the controller using $request->input('key')
Hope this helps!
Go through array like this, you will just check if your array has empty, will not add the key.
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data) . "\n";
//echo http_build_query($data, '', '&'); // only for use &amp instead & if needed
I have applied the next middleware on a Laravel 8.x project to solve a related problem. This may be helpful to other ones...
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class StripEmptyParamsFromQueryString
{
/**
* Remove parameters with empty value from a query string.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
// Get the current query and the number of query parameters.
$query = request()->query();
$queryCount = count($query);
// Strip empty query parameters.
foreach ($query as $param => $value) {
if (! isset($value) || $value == '') {
unset($query[$param]);
}
}
// If there were empty query parameters, redirect to a new url with the
// non empty query parameters. Otherwise keep going with the current
// request.
if ($queryCount > count($query)) {
return redirect()->route($request->route()->getName(), $query);
}
return $next($request);
}
}
Note the middleware should only be applied to specific routes, not to all request. In my particular case I have a resource controller and to apply the middleware only to the index route I have used the next approach inside the resource controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Middleware\StripEmptyParamsFromQueryString;
class MyController extends Controller
{
/**
* Instantiate a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(StripEmptyParamsFromQueryString::class)
->only('index');
}
...
}

Zend Framework addaction with success or failure message

public function addAction()
{
$form = new ApplicationForm();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$name = $form->getvalue('name');
$class = $form->getvalue('class');
$file = new Application_Model_DbTable_Records();
$file->addRecord($name,$class);
$this->_helper->redirector('index');
}
}
}
Above addAction controller part, here when i am clicking AddAction my form is waiting for user inputs when i click submit my inputs recorded in database.
Now my question is i want add some message after the submit form data whether it success or failure.
Could you please help me on this ?
Many Thanks,
viswa
The docs for the action-helper describe an example. But standard usage goes something like this:
After you add the record, before you redirect, set the desired message in your controller:
public function addAction()
{
$form = new ApplicationForm();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$name = $form->getValue('name');
$class = $form->getValue('class');
$file = new Application_Model_DbTable_Records();
$file->addRecord($name,$class);
// Add the message here
$this->_helper->getHelper('FlashMessenger')->addMessage('Record added');
$this->_helper->redirector('index');
}
}
}
Then in your indexAction - the controller to which you are redirecting after successful record addition - get the messages and add them to your view:
public function indexAction()
{
// All your existing processing
// Blah, blah..
// Get the messages from the FlashMessenger
$messenger = $this->_helper->getHelper('FlashMessenger');
$messages = $messenger->hasMessages() ? $messenger->getMessages() : [];
// Add the messages into the view
$this->view->messages = $messages;
}
Finally, somewhere in the index view-script where you want the messages to appear, check for the messages and render, something like:
<?php if ($this->messages): ?>
<div id="refresh-messages">
<ul>
<?php foreach ($this->messages as $message): ?>
<li><?= $message ?></li>
<?php endforeach ?>
</ul>
</div>
<?php endif ?>
The wrapping div is just to assist with styling by providing a DOM element id to which you can target your CSS.
Disclaimer: Not tested directly, just coding from memory.

cakephp multiple forms with same action

I've got on my page several News, to every News we can add comment via form.
So actually I've got 3 News on my index.ctp, and under every News is a Form to comment this particular News. Problem is, when i add comment, data is taken from the last Form on the page.
I don;t really know how to diverse them.
i've red multirecord forms and Multiple Forms per page ( last one is connected to different actions), and i don't figure it out how to manage it.
Second problem is, i can't send $id variable through the form to controller ( $id has true value, i displayed it on index.ctp just to see )
This is my Form
<?php $id = $info['Info']['id']; echo $this->Form->create('Com', array('action'=>'add',$id)); ?>
<?php echo $this->Form->input(__('Com.mail',true),array('class'=>'form-control','field'=>'mail')); ?>
<?php echo $this->Form->input(__('Com.body',true),array('class'=>'form-control')); ?>
<?php echo $this->Form->submit(__('Dodaj komentarz',true),array('class'=>'btn btn-info')); ?>
<?php $this->Form->end(); ?>
and there is my controller ComsController.php
class ComsController extends AppController
{
public $helpers = array('Html','Form','Session');
public $components = array('Session');
public function index()
{
$this->set('com', $this->Com->find('all'));
}
public function add($idd = NULL)
{
if($this->request->is('post'))
{
$this->Com->create();
$this->request->data['Com']['ip'] = $this->request->clientIp();
$this->request->data['Com']['info_id'] = $idd;
if($this->Com->save($this->request->data))
{
$this->Session->setFlash(__('Comment added with success',true),array('class'=>'alert alert-info'));
return $this->redirect(array('controller'=>'Infos','action'=>'index'));
}
$this->Session->setFlash(__('Unable to addd comment',true),array('class'=>'alert alert-info'));
return false;
}
return true;
}
}
you are not closing your forms
<?php echo $this->Form->end(); ?>
instead of
<?php $this->Form->end(); ?>
for the id problem you should write
echo $this->Form->create(
'Com',
array('action'=>'add/'.$id
)
);
or
echo $this->Form->create(
'Com',
array(
'url' => array('action'=>'add', $id)
)
);

Joomla 2.5 - component development - using form

I am trying to add some form to my component, but I am not shure what naming conventions must be applied to work it correctly.
Currently I have a working form - it displays fields stored in XML file and loads data from database to it. However, when i try to submit this form (edit or add new records), it doesn't work. After pressing submit (save() method) it just redirects me and displays that record was edited successfuly but it wasn't. When I try to edit existing record, after pressing submit nothing happens and when I try to add new record, it just adds empty/blank record.
So I was doing a little debug and discovered, that problem is in the JController::checkEditId() method. It always returns false which means that JControllerForm::save() returns false as well and that's why it doesn't save it correctly. HTML code of form is correct and I can access the data by using global array $_POST.
I suspect that this problem is because of naming conventions in methods loadFormData, getForm of JModelAdmin class. I am not sure how to name that form.
So here is my code related to this problem:
Subcontroller for displaying the form - controllers/slideshowform.php
class SlideshowModelSlideshowForm extends JModelAdmin{
public function getForm($data = array(), $loadData = true){
return $this->loadForm('com_slideshow.slideshowform', 'editform', array('load_data' => $loadData, 'control' => 'jform'));
}
protected function loadFormData(){
$data = JFactory::getApplication()->getUserState('com_slideshow.edit.slideshowform.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
public function getTable($table = "biometricslideshow"){
return parent::getTable($table);
}
}
views/slideshowform/view.html.php
class SlideshowViewSlideshowForm extends JView{
public function display($tmpl = null){
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
$this->form = $this->get('form');
$this->item = $this->get('item');
JToolBarHelper::save('slideshowform.save');
parent::display();
}
}
views/slideshowform/tmpl/default.php
<?php
defined('_JEXEC') or die('Restricted access');
JHtml::_('behavior.tooltip');
?>
<form method="post" action="<?php echo JRoute::_("index.php?option=com_slideshow&id=".(int) $this->item->id)?>" name="adminForm" id="slideshow-form">
<fieldset class="adminform">
<legend>Edit slide</legend>
<table>
<input type="hidden" name="task" value="">
<?php echo JHtml::_('form.token'); ?>
<?php
foreach($this->form->getFieldset() as $field){
?>
<tr><td><?php echo $field->label ?></td><td><?php echo $field->input ?></td></tr>
<?php
}
?>
</table>
</fieldset>
</form>
Can someone take o look, please?
you have to add controller SlideshowControllerSlideshowForm and code save method. In there you have to validate the form data and call SlideshowModelSlideshowForm->save event, then redirect with success/failure message.