How can I make a custom dynamic footer in TCPDF with data taken from a database? - tcpdf

I would like to make a dynamic footer containing data taken from a database.
How to extend TCPDF class to put those data in?
// my DB stuff here
$datafromdb = getDataFromDB();
class MYPDF extends TCPDF {
// Page footer
public function Footer() {
// Position at 10 mm from bottom
$this->SetY(-10);
// Set font
$this->SetFont('dejavusans', 'I', 8);
$foot = $datafromdb.'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages();
$this->MultiCell(0, 10, $foot, 0, 'C');
}
}

you can add a __construct method to pass your data.
try this :
// my DB stuff here
$datafromdb = getDataFromDB();
class MYPDF extends TCPDF {
private $datafromdb ;//<-- to save your data
function __construct( $datafromdb , $orientation, $unit, $format )
{
parent::__construct( $orientation, $unit, $format, true, 'UTF-8', false );
$this->datafromdb = $datafromdb ;
//...
}
// Page footer
public function Footer() {
// Position at 10 mm from bottom
$this->SetY(-10);
// Set font
$this->SetFont('dejavusans', 'I', 8);
$foot = $this->datafromdb.'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages();
$this->MultiCell(0, 10, $foot, 0, 'C');
}
}

Related

Vaadin: open calendar on field focus for datefield

Vaadin widgets are simple and awesome! But they are also poorly configurable.
I need my DateField widget to open calendar on focus event. I didn't find that functionality in official Vaadin documentation. I found some 3rd party widget here, but it's compiled for Vaadin 7.7 and I use latest Vaadin (8.0.6). Also it has Joda-time 2.1 dependency which is highly undesirable in my project. So, is there any simple way to tune stock vaadin DateField widget to open it's calendar on field focus, or do I need to write my own component for that? Any help is appreciated.
As I was saying in my comment, as far as I know, currently the framework does not offer an implicit way to programmatically open the calendar popup. The same thing goes for some other components such as the grid editor, or the combo item list.
One quick workaround I can think of, is to add a javascript extension that registers focus listeners for all date fields, and clicks the button when a date field is focused. Please find below a sample.
P.S. If you only need to apply this to only some date fields, you can add IDs and pass them to the JS, where you'll do something like document.getElementById('myDateFieldId') instead of document.getElementsByClassName("v-datefield").
1) Layout with components
public class MyDateFieldComponent extends HorizontalLayout {
public MyDateFieldComponent() {
// basic setup
DateField fromDateField = new DateField("From", LocalDate.of(2011, Month.FEBRUARY, 6));
DateField toDateField = new DateField("To", LocalDate.of(2018, Month.FEBRUARY, 6));
setSpacing(true);
addComponents(fromDateField, toDateField);
// add the extension
addExtension(new CalendarFocusPopupOpenerExtension());
}
}
2) Extension - java/server side
import com.vaadin.annotations.JavaScript;
import com.vaadin.server.AbstractJavaScriptExtension;
#JavaScript("calendar-focus-popup-opener-extension.js")
public class CalendarFocusPopupOpenerExtension extends AbstractJavaScriptExtension {
public CalendarFocusPopupOpenerExtension() {
// call the bind function defined in the associated JS
callFunction("bind");
}
}
3) Extension - js/client side
window.com_example_calendar_CalendarFocusPopupOpenerExtension = function () {
this.bind = function () {
if (document.readyState === "complete") {
// if executed when document already loaded, just bind
console.log("Doc already loaded, binding");
bindToAllDateFields();
} else {
// otherwise, bind when finished loading
console.log("Doc nod loaded, binding later");
window.onload = function () {
console.log("Doc finally loaded, binding");
bindToAllDateFields();
}
}
};
function bindToAllDateFields() {
// get all the date fields to assign focus handlers to
var dateFields = document.getElementsByClassName("v-datefield");
for (var i = 0; i < dateFields.length; i++) {
addFocusListeners(dateFields[i]);
}
}
function addFocusListeners(dateField) {
// when focusing the date field, click the button
dateField.onfocus = function () {
dateField.getElementsByTagName("button")[0].click();
};
// or when focusing the date field input, click the button
dateField.getElementsByTagName("input")[0].onfocus = function () {
dateField.getElementsByTagName("button")[0].click();
};
}
};
4) Result
LATER UPDATE
A second approach could be to assign some IDs to your fields, and then check periodically to see when all are visible, and as soon as they are, bind the focus listeners.
1) Layout with components
public class MyDateFieldComponent extends HorizontalLayout {
public MyDateFieldComponent() {
// basic setup
DateField fromDateField = new DateField("From", LocalDate.of(2011, Month.FEBRUARY, 6));
fromDateField.setId("fromDateField"); // use id to bind
fromDateField.setVisible(false); // initially hide it
DateField toDateField = new DateField("To", LocalDate.of(2018, Month.FEBRUARY, 6));
toDateField.setId("toDateField"); // use id to bind
toDateField.setVisible(false); // initially hide it
// simulate a delay until the fields are available
Button showFieldsButton = new Button("Show fields", e -> {
fromDateField.setVisible(true);
toDateField.setVisible(true);
});
setSpacing(true);
addComponents(showFieldsButton, fromDateField, toDateField);
// add the extension
addExtension(new CalendarFocusPopupOpenerExtension(fromDateField.getId(), toDateField.getId()));
}
}
2) Extension - java/server side
#JavaScript("calendar-focus-popup-opener-extension.js")
public class CalendarFocusPopupOpenerExtension extends AbstractJavaScriptExtension {
public CalendarFocusPopupOpenerExtension(String... idsToBindTo) {
// send the arguments as an array of strings
JsonArray arguments = Json.createArray();
for (int i = 0; i < idsToBindTo.length; i++) {
arguments.set(i, idsToBindTo[i]);
}
// call the bind defined in the associated JS
callFunction("bind", arguments);
}
}
3) Extension - js/client side
window.com_example_calendar_CalendarFocusPopupOpenerExtension = function () {
var timer;
this.bind = function (idsToBindTo) {
// check every second to see if the fields are available. interval can be tweaked as required
timer = setInterval(function () {
bindWhenFieldsAreAvailable(idsToBindTo);
}, 1000);
};
function bindWhenFieldsAreAvailable(idsToBindTo) {
console.log("Looking for the following date field ids: [" + idsToBindTo + "]");
var dateFields = [];
for (var i = 0; i < idsToBindTo.length; i++) {
var dateFieldId = idsToBindTo[i];
var dateField = document.getElementById(dateFieldId);
if (!dateField) {
// field not present, wait
console.log("Date field with id [" + dateFieldId + "] not found, sleeping");
return;
} else {
// field present, add it to the list
console.log("Date field with id [" + dateFieldId + "] found, adding to binding list");
dateFields.push(dateField);
}
}
// all fields present and accounted for, bind the listeners!
clearInterval(timer);
console.log("All fields available, binding focus listeners");
bindTo(dateFields);
}
function bindTo(dateFields) {
// assign focus handlers to all date fields
for (var i = 0; i < dateFields.length; i++) {
addFocusListeners(dateFields[i]);
}
}
function addFocusListeners(dateField) {
// when focusing the date field, click the button
dateField.onfocus = function () {
dateField.getElementsByTagName("button")[0].click();
};
// or when focusing the date field input, click the button
dateField.getElementsByTagName("input")[0].onfocus = function () {
dateField.getElementsByTagName("button")[0].click();
};
}
};
4) Result

GridLayout - fill all available space in content

I'm developing a web application in Vaadin framework which has home page and few sub pages. What I want to achieve is to have fixed header and footer and in the center have content, that is being changed and fill all the space between header and footer. This is my MainUI class:
// HEADER
final VerticalLayout headerLayout = new VerticalLayout();
final Panel headerPanel = new Panel();
headerPanel.addStyleName("header");
final ActiveLink header = new ActiveLink(provider.getText(getLocale(), "application.title.name"), new ExternalResource(""));
header.addStyleName("header");
header.addListener((ActiveLink.LinkActivatedListener) (ActiveLink.LinkActivatedEvent event) -> {
getUI().getNavigator().navigateTo(Constant.View.MAIN);
});
headerPanel.setContent(header);
headerLayout.addComponent(headerPanel);
// FOOTER
final VerticalLayout footerLayout = new VerticalLayout(new Label("« FOOTER »"));
// CONTENT
final VerticalLayout contentLayout = new VerticalLayout();
final Panel contentPanel = new Panel(contentLayout);
contentPanel.addStyleName("content transparent no-border");
// MAIN = all together
final VerticalLayout mainLayout = new VerticalLayout(headerLayout, contentPanel, footerLayout);
mainLayout.setSizeFull();
mainLayout.setExpandRatio(contentPanel, 1);
setContent(mainLayout);
// Register Views in navigator
navigator = new Navigator(this, contentPanel);
navigator.addView("", new MainView(provider));
navigator.addView(Constant.View.DICT_ADMIN, new DictAdminView(provider));
For changing the view in content I'm using Navigator like this in MainView class:
final ActiveLink link11 = new ActiveLink(provider.getText(getLocale(), "menu.links.dict.admin"), new ExternalResource(""));
link11.addStyleName("menulinks");
link11.addListener((LinkActivatedListener) (LinkActivatedEvent event1) -> {
getUI().getNavigator().navigateTo(Constant.View.DICT_ADMIN);
});
And finally this is my DictAdminView class:
public class DictAdminView extends GridLayout implements View {
private static final Logger LOGGER = LoggerFactory.getLogger(DictAdminView.class);
I18NProvider provider;
private final DictionaryDao dictionaryDao = new DictionaryDao();
private final TermDao termDao = new TermDao();
private final JPAContainer dictionaries = dictionaryDao.getContainer();
private final JPAContainer terms = termDao.getContainer();
public DictAdminView(I18NProvider provider) {
super(4, 6);
this.provider = provider;
}
#Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
removeAllComponents();
this.addStyleName("dictAdminLayout");
this.setSizeFull();
this.setSpacing(true);
// Table with Dictionaries
Grid grid = new Grid(dictionaries);
grid.setId("dictList");
grid.setWidth("100%");
grid.setColumns(
grid.getColumns().get(1).getPropertyId(),
grid.getColumns().get(0).getPropertyId());
grid.getColumns().get(1).setWidth(80).setHeaderCaption("POS");
this.addComponent(grid, 0, 0, 0, 5);
dictionaries.sort(new Object[]{grid.getColumns().get(0).getPropertyId()}, new boolean[]{true});
// Table with Terms
Grid grid1 = new Grid(terms);
grid1.setId("termList");
grid1.setWidth("100%");
grid1.setColumns(
grid1.getColumns().get(5).getPropertyId(),
grid1.getColumns().get(0).getPropertyId());
this.addComponent(grid1, 1, 0, 3, 3);
terms.sort(new Object[]{grid1.getColumns().get(0).getPropertyId()}, new boolean[]{true});
terms.addContainerFilter(new IsNull("dictionaryId")); // show items w/o dict by default
this.addComponent(new Button("lol button"), 1, 5, 3, 5);
// Handle dictionary selection
grid.addSelectionListener(selectionEvent -> {
// Get selection from the selection model
Integer selectedDictionaryId = (Integer) ((SingleSelectionModel) grid.getSelectionModel()).getSelectedRow();
terms.removeAllContainerFilters();
if (selectedDictionaryId != null) {
terms.addContainerFilter(new Compare.Equal("dictionaryId.id", selectedDictionaryId));
Utils.showInfoMessage(provider.getText(getLocale(), "msg.info.title.dictionary.selected"),
grid.getContainerDataSource().getItem(selectedDictionaryId).getItemProperty("name").toString());
}
else {
terms.addContainerFilter(new IsNull("dictionaryId")); // show items w/o dict by default
Utils.showInfoMessage(provider.getText(getLocale(), "msg.info.title.nothing.selected"), "");
}
});
}
}
My problem here is that I can't stretch the Grid to fill all space between header and footer. I've tried combination of setSizeFull() and setRowExtendRatio() but no success. Also I've tried to do it in CSS.
Is there a way how to stretch the grid either in Java or CSS?
Is the Navigator and changing View a good approach or is there a better way how to switch between content?
The solution is to use Vaadin add-on BorderLayout or built-in CustomLayout with own HTML and CSS.

storing data in persistence store

I am facing an issue in storing data in persistence store,i am trying to store events for different dates in persistence store but the data is getting overridden the code is :
public ListEventScreen(Vector v,String timezone) {
for(int i=0;i<v.size();i++){
EventBean bean=(EventBean)v.elementAt(i);
//a normal label in the app, just to display text, anchored left
LabelField label = new LabelField(bean.getSummary(),LabelField.FIELD_LEFT);
//add the label to the screen
add(label);
saveUserInfo(v);
}
}
public void saveUserInfo(Vector vectorData){
// static{
store = PersistentStore.getPersistentObject( 0x1dfc10ec9447eb14L );
synchronized(store) {
store.setContents(vectorData);
store.commit();
}
//}
}
Please let me know what has to be changed.
Every time you call store.setContents(), the current contents of the persistentStore are overwritten with the Vector you are passing in. You need to make sure you are loading the previous events that were already in the persistentStore into your Vector before then adding new events into that Vector that you are then saving.
You are also calling saveUserInfo() on every iteration of your loop in ListEventScreen(). You should be calling it outside of the loop instead.
I would do something like this:
public ListEventScreen(Vector v,String timezone) {
Enumeration e = v.elements();;
while (e.hasMoreElements()){
EventBean bean = (EventBean) e.nextElement();
//a normal label in the app, just to display text, anchored left
LabelField label = new LabelField(bean.getSummary(),LabelField.FIELD_LEFT);
//add the label to the screen
add(label);
}
}
public void loadUserInfo(Vector vectorData){
// static{
store = PersistentStore.getPersistentObject( 0x1dfc10ec9447eb14L );
synchronized(store) {
Vector v = (Vector) store.getContents();
Enumeration e = v.elements();
while (e.hasMoreElemens){
vectorData.add(e.nextElement());
}
}
//}
}
public void saveUserInfo(Vector vectorData){
// static{
store = PersistentStore.getPersistentObject( 0x1dfc10ec9447eb14L );
synchronized(store) {
store.setContents(vectorData);
store.commit();
}
//}
}
.
{
Vector v = new Vector();
loadUserInfo(v);
ListEventScreen(v, ...);
... modify v contents as needed ...
saveUserInfo(v);
}
If you do not mind changing the format of your persistent store contents, I would wrap the store in a singleton class instead:
public class EventBeans extends Vector implements Persistable
{
private static final long persistKey = 0x1dfc10ec9447eb14L;
private static EventBeans _instance = null;
private static PersistentObject _persist = null;
static{
_persist = PersistentStore.getPersistentObject(persistKey);
_instance = (EventBeans) _persist.getContents();
if (_instance == null){
_instance = new EventBeans();
_persist.setContents(_instance);
_persist.commit();
}
}
private EventBeans(){
super();
}
public static EventBeans getInstance(){
return _instance;
}
public static synchronized void save(){
_persist.commit();
}
}
.
{
Vector v = EventBeans.getInstance();
ListEventScreen(v, ...);
... modify v contents as needed ...
EventBeans.save();
}

How can I enable/disable cells using Vaadin table component?

I have a table with 2 columns: a checkbox and a textfield. I want to disable the textfield depending of the respective (same row) checkbox status. If the checkbox is checked then the textfield will be cleared and be read only. Is this possible ? Here is my code:
#SuppressWarnings("serial")
private Table filtersTable() {
final Table table = new Table();
table.setPageLength(10);
table.setSelectable(false);
table.setImmediate(true);
table.setSizeFull();
// table.setMultiSelectMode(MultiSelectMode.SIMPLE) ;
table.addContainerProperty("Tipo filtro", CheckBox.class, null);
table.addContainerProperty("Valor", String.class, null);
table.setEditable(true);
for (int i = 0; i < 15; i++) {
TextField t = new TextField();
t.setData(i);
t.setMaxLength(50);
t.setValue("valor " + i);
t.setImmediate(true);
t.setWidth(30, UNITS_PERCENTAGE);
CheckBox c = new CheckBox(" filtro " + i);
c.setWidth(30, UNITS_PERCENTAGE);
c.setData(i);
c.setImmediate(true);
c.addListener(new ValueChangeListener() {
#Override
public void valueChange(ValueChangeEvent event) {
// within this, could I access the respective row ID
// (i) then enable/disable TextField t on second column ?
System.out.println("event.getProperty().getValue()="
+ event.getProperty().getValue());
}
});
table.addItem(new Object[] { c, t }, i);
}
return table;
}
Thanks
Few changes to your code made it possible.
Not the finiest way, but te simpliest.
First,you have to set your second column (Valor) to TextField.class not String.class.
Here the change :
table.addContainerProperty("Valor", TextField.class, null);
Instead of keepin the variable i in the CheckBox.setData(), I suggest you to link your checkBox to the TextField of the same row, like this :
c.setData(t);
Finally I made little change to your listener :
c.addListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
CheckBox checkBox = (CheckBox)event.getProperty();
if((Boolean) checkBox.getValue())
{
TextField associatedTextField = (TextField)checkBox.getData();
//Do all your stuff with the TextField
associatedTextField.setReadOnly(true);
}
}
});
Hope it's work for you!
Regards, Éric
public class MyCheckBox extends CheckBox {
private TextBox t;
public MyCheckBox(TextBox t) {
this.t = t;
attachLsnr();
}
private void attachLsnr()
{
addListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
CheckBox checkBox = (CheckBox)event.getProperty();
if((Boolean) checkBox.getValue())
{
t.setReadOnly(true);
}
}
});
}
}

Outputting required field indicator for symfony forms

I have a few forms configured in symfony. One things I need is to have an asterisk (*) or other indicator next to fields that are required. The fields are all set to required int he form framework, and return a "this field is required" error when the form is submitted, but I want an indicator before the form is submitted.
If there any way to do this without overriding the labels for each field manually?
Here's an automatic solution found in Kris Wallsmith's blog:
lib/formatter/RequiredLabelsFormatterTable.class.php, this will add a 'required' class to the labels of required fields
<?php
class RequiredLabelsFormatterTable extends sfWidgetFormSchemaFormatterTable
{
protected
$requiredLabelClass = 'required';
public function generateLabel($name, $attributes = array())
{
// loop up to find the "required_fields" option
$widget = $this->widgetSchema;
do {
$requiredFields = (array) $widget->getOption('required_fields');
} while ($widget = $widget->getParent());
// add a class (non-destructively) if the field is required
if (in_array($this->widgetSchema->generateName($name), $requiredFields)) {
$attributes['class'] = isset($attributes['class']) ?
$attributes['class'].' '.$this->requiredLabelClass :
$this->requiredLabelClass;
}
return parent::generateLabel($name, $attributes);
}
}
lib/form/BaseForm.class.php, this is the common base class for all the forms in your project:
protected function getRequiredFields(sfValidatorSchema $validatorSchema = null, $format = null)
{
if (is_null($validatorSchema)) {
$validatorSchema = $this->validatorSchema;
}
if (is_null($format)) {
$format = $this->widgetSchema->getNameFormat();
}
$fields = array();
foreach ($validatorSchema->getFields() as $name => $validator) {
$field = sprintf($format, $name);
if ($validator instanceof sfValidatorSchema) {
// recur
$fields = array_merge(
$fields,
$this->getRequiredFields($validator, $field.'[%s]')
);
} else if ($validator->getOption('required')) {
// this field is required
$fields[] = $field;
}
}
return $fields;
}
add the following few lines to BaseForm as well, in the __construct() method:
$this->widgetSchema->addOption("required_fields", $this->getRequiredFields());
$this->widgetSchema->addFormFormatter('table',
new RequiredLabelsFormatterTable($this->widgetSchema)
);
After all this, all your labels will have the required class, use whatever css you need to mark it to the user.
What about the simpler solution from the original cookbook - just a few lines in twig:
http://symfony.com/doc/2.1/cookbook/form/form_customization.html#adding-a-required-asterisk-to-field-labels
you can set the field's class as part of the constructor of the sfWidget
i.e.
$this->widgetSchema['form_field'] = new sfWidgetFormInput(array(), array('class' => 'required_field'));
Note: this is assuming you're not on the ancient sfForms (ala 1.0)
UPDATE
here is some CSS code from techchorus.net to show the required asterisk
.required
{
background-image:url(/path/to/your/images/dir/required-field.png);
background-position:top right;
background-repeat:no-repeat;
padding-right:10px;
}
I did it using Javascript:
$('form').find('select, input, textarea').each(function(){
if($(this).attr('required') == 'required'){
$label = $('label[for='+ $(this).attr('id') +']');
if($label.find('.required-field').length == 0){
$label.append('<span class="required-field">*</span>');
}
}
});

Resources