article

Saturday, May 28, 2016

wxpython dialogs Message dialogs

wxpython dialogs Message dialogs

Message dialogs are used to show messages to the user. They are more flexible than simple message boxes that we saw in the previous example. They are customisable. We can change icons and buttons that will be shown in a dialog.




flagmeaning
wx.OKshow OK button
wx.CANCELshow Cancel button
wx.YES_NOshow Yes, No buttons
wx.YES_DEFAULTmake Yes button the default
wx.NO_DEFAULTmake No button the default
wx.ICON_EXCLAMATIONshow an alert icon
wx.ICON_ERRORshow an error icon
wx.ICON_HANDsame as wx.ICON_ERROR
wx.ICON_INFORMATIONshow an info icon
wx.ICON_QUESTIONshow a question icon
 
import wx

class Example(wx.Frame):
    
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs) 
            
        self.InitUI()
        
    def InitUI(self):    

        panel = wx.Panel(self)

        hbox = wx.BoxSizer()
        sizer = wx.GridSizer(2, 2, 2, 2)

        btn1 = wx.Button(panel, label='Info')
        btn2 = wx.Button(panel, label='Error')
        btn3 = wx.Button(panel, label='Question')
        btn4 = wx.Button(panel, label='Alert')

        sizer.AddMany([btn1, btn2, btn3, btn4])

        hbox.Add(sizer, 0, wx.ALL, 15)
        panel.SetSizer(hbox)

        btn1.Bind(wx.EVT_BUTTON, self.ShowMessage1) #Bind btn1 and ShowMessage1 function
        btn2.Bind(wx.EVT_BUTTON, self.ShowMessage2)
        btn3.Bind(wx.EVT_BUTTON, self.ShowMessage3)
        btn4.Bind(wx.EVT_BUTTON, self.ShowMessage4)

        self.SetSize((300, 200))
        self.SetTitle('Messages') #form title
        self.Centre()
        self.Show(True)

    def ShowMessage1(self, event): #show function
        dial = wx.MessageDialog(None, 'Download completed', 'Info', wx.OK)
        dial.ShowModal() #show the dialog on screen, call the ShowModal() method

    def ShowMessage2(self, event):
        dial = wx.MessageDialog(None, 'Error loading file', 'Error', 
            wx.OK | wx.ICON_ERROR)
        dial.ShowModal()

    def ShowMessage3(self, event):
        dial = wx.MessageDialog(None, 'Are you sure to quit?', 'Question', 
            wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
        dial.ShowModal()

    def ShowMessage4(self, event):
        dial = wx.MessageDialog(None, 'Unallowed operation', 'Exclamation', 
            wx.OK | wx.ICON_EXCLAMATION)
        dial.ShowModal()

def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()

wxpython dialogs wx.MessageBox

wxpython dialogs wx.MessageBox
 
import wx

class Example(wx.Frame):
    
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs) 
            
        self.InitUI()
        
    def InitUI(self):    

        wx.FutureCall(5000, self.ShowMessage) #wx.FutureCall shows a message box after 5 seconds. 5000 milliseconds, self.ShowMessage method 

        self.SetSize((300, 200))
        self.SetTitle('Message box')
        self.Centre()
        self.Show(True)

    def ShowMessage(self):
        wx.MessageBox('Download completed', 'Info', 
            wx.OK | wx.ICON_INFORMATION)


def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()   

wxpython Events KeyEvent

wxpython Events KeyEvent

When we press a key on our keyboard, a wx.KeyEvent is generated. This event is sent to the widget that has currently focus.
 
import wx

class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
                
    def InitUI(self):
        #There are three different key handlers,wx.EVT_KEY_DOWN, wx.EVT_KEY_UP, wx.EVT_CHAR
        pnl = wx.Panel(self)
        pnl.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        pnl.SetFocus()

        self.SetSize((250, 180))
        self.SetTitle('Key event')
        self.Centre()
        self.Show(True)  

    def OnKeyDown(self, e):
        
        key = e.GetKeyCode()
        
        if key == wx.WXK_ESCAPE: #  when the Esc key is pressed
            
            ret  = wx.MessageBox('Are you sure to quit?', 'Question', 
                wx.YES_NO | wx.NO_DEFAULT, self)
                
            if ret == wx.YES:
                self.Close()               
        
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()  

wxpython Events identifiers global ids

wxpython Events identifiers global ids
 
import wx

ID_MENU_NEW = wx.NewId()
ID_MENU_OPEN = wx.NewId()
ID_MENU_SAVE = wx.NewId()

class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
                
    def InitUI(self):
        
        self.CreateMenuBar()
        self.CreateStatusBar()
        
        self.SetSize((250, 180))
        self.SetTitle('Global ids')
        self.Centre()
        self.Show(True)  
        
    def CreateMenuBar(self):
        
        mb = wx.MenuBar()
        
        fMenu = wx.Menu()
        fMenu.Append(ID_MENU_NEW, 'New')
        fMenu.Append(ID_MENU_OPEN, 'Open')
        fMenu.Append(ID_MENU_SAVE, 'Save')
        
        mb.Append(fMenu, '&File')
        self.SetMenuBar(mb)
        
        self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_NEW)
        self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_OPEN)
        self.Bind(wx.EVT_MENU, self.DisplayMessage, id=ID_MENU_SAVE)        
        
    def DisplayMessage(self, e):
        
        sb = self.GetStatusBar()
                
        eid = e.GetId()
        
        if eid == ID_MENU_NEW:
            msg = 'New menu item selected'
        elif eid == ID_MENU_OPEN:
            msg = 'Open menu item selected'
        elif eid == ID_MENU_SAVE:
            msg = 'Save menu item selected'
        
        sb.SetStatusText(msg)

def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main() 

wxpython Events Vetoing events

wxpython Events Vetoing events
 
import wx

class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
                
    def InitUI(self):
        # Bind() method
        #Bind(event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        self.SetTitle('Event veto')
        self.Centre()
        self.Show(True)

    def OnCloseWindow(self, e):

        dial = wx.MessageDialog(None, 'Are you sure to quit?', 'Question',
            wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
            
        ret = dial.ShowModal()
        
        if ret == wx.ID_YES:
            self.Destroy()
        else:
            e.Veto()

def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()  

Friday, May 27, 2016

wxpython Events wx.MoveEvent

wxpython Events wx.MoveEvent
 
import wx

class Example(wx.Frame):
           
    def __init__(self, *args, **kw):
        super(Example, self).__init__(*args, **kw) 
        
        self.InitUI()
        
        
    def InitUI(self):

        wx.StaticText(self, label='x:', pos=(10,10))
        wx.StaticText(self, label='y:', pos=(10,30))
        
        self.st1 = wx.StaticText(self, label='', pos=(30, 10))
        self.st2 = wx.StaticText(self, label='', pos=(30, 30))

        self.Bind(wx.EVT_MOVE, self.OnMove) #bind the wx.EVT_MOVE event binder to the OnMove() method

        self.SetSize((250, 180))
        self.SetTitle('Move event')
        self.Centre()
        self.Show(True)  

    def OnMove(self, e):
        
        x, y = e.GetPosition() #call GetPosition() method
        self.st1.SetLabel(str(x))
        self.st2.SetLabel(str(y))


def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()  

wxpython layout wx.GridBagSizer

wxpython layout wx.GridBagSizer

 
import wx

class Example(wx.Frame):

    def __init__(self, parent, title):    
        super(Example, self).__init__(parent, title=title, 
            size=(450, 350))

        self.InitUI()
        self.Centre()
        self.Show()     

    def InitUI(self):
      
        panel = wx.Panel(self)
        
        sizer = wx.GridBagSizer(5, 5)

        text1 = wx.StaticText(panel, label="Java Class")
        sizer.Add(text1, pos=(0, 0), flag=wx.TOP|wx.LEFT|wx.BOTTOM, 
            border=15)

        icon = wx.StaticBitmap(panel, bitmap=wx.Bitmap('open.png'))
        sizer.Add(icon, pos=(0, 4), flag=wx.TOP|wx.RIGHT|wx.ALIGN_RIGHT, 
            border=5)

        line = wx.StaticLine(panel)
        sizer.Add(line, pos=(1, 0), span=(1, 5), 
            flag=wx.EXPAND|wx.BOTTOM, border=10)

        text2 = wx.StaticText(panel, label="Name")
        sizer.Add(text2, pos=(2, 0), flag=wx.LEFT, border=10)

        tc1 = wx.TextCtrl(panel)
        sizer.Add(tc1, pos=(2, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND)

        text3 = wx.StaticText(panel, label="Package")
        sizer.Add(text3, pos=(3, 0), flag=wx.LEFT|wx.TOP, border=10)

        tc2 = wx.TextCtrl(panel)
        sizer.Add(tc2, pos=(3, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND, 
            border=5)

        button1 = wx.Button(panel, label="Browse...")
        sizer.Add(button1, pos=(3, 4), flag=wx.TOP|wx.RIGHT, border=5)

        text4 = wx.StaticText(panel, label="Extends")
        sizer.Add(text4, pos=(4, 0), flag=wx.TOP|wx.LEFT, border=10)

        combo = wx.ComboBox(panel)
        sizer.Add(combo, pos=(4, 1), span=(1, 3), 
            flag=wx.TOP|wx.EXPAND, border=5)

        button2 = wx.Button(panel, label="Browse...")
        sizer.Add(button2, pos=(4, 4), flag=wx.TOP|wx.RIGHT, border=5)

        sb = wx.StaticBox(panel, label="Optional Attributes")

        boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)
        boxsizer.Add(wx.CheckBox(panel, label="Public"), 
            flag=wx.LEFT|wx.TOP, border=5)
        boxsizer.Add(wx.CheckBox(panel, label="Generate Default Constructor"),
            flag=wx.LEFT, border=5)
        boxsizer.Add(wx.CheckBox(panel, label="Generate Main Method"), 
            flag=wx.LEFT|wx.BOTTOM, border=5)
        sizer.Add(boxsizer, pos=(5, 0), span=(1, 5), 
            flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT , border=10)

        button3 = wx.Button(panel, label='Help')
        sizer.Add(button3, pos=(7, 0), flag=wx.LEFT, border=10)

        button4 = wx.Button(panel, label="Ok")
        sizer.Add(button4, pos=(7, 3))

        button5 = wx.Button(panel, label="Cancel")
        sizer.Add(button5, pos=(7, 4), span=(1, 1),  
            flag=wx.BOTTOM|wx.RIGHT, border=5)

        sizer.AddGrowableCol(2)
        
        panel.SetSizer(sizer)


if __name__ == '__main__':
  
    app = wx.App()
    Example(None, title="Create Java Class")
    app.MainLoop()

wxpython layout wx.FlexGridSizer

wxpython layout wx.FlexGridSizer

wx.GridSizer cells are of the same size

 
import wx

class Example(wx.Frame):
  
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title, 
            size=(300, 250))
            
        self.InitUI()
        self.Centre()
        self.Show()     
        
    def InitUI(self):
    
        panel = wx.Panel(self)

        hbox = wx.BoxSizer(wx.HORIZONTAL)

        fgs = wx.FlexGridSizer(3, 2, 9, 25)
        #wx.FlexGridSizer(int rows=1, int cols=0, int vgap=0, int hgap=0)
        title = wx.StaticText(panel, label="Title")
        author = wx.StaticText(panel, label="Author")
        review = wx.StaticText(panel, label="Review")

        tc1 = wx.TextCtrl(panel)
        tc2 = wx.TextCtrl(panel)
        tc3 = wx.TextCtrl(panel, style=wx.TE_MULTILINE)

        fgs.AddMany([(title), (tc1, 1, wx.EXPAND), (author), 
            (tc2, 1, wx.EXPAND), (review, 1, wx.EXPAND), (tc3, 1, wx.EXPAND)])

        fgs.AddGrowableRow(2, 1)
        fgs.AddGrowableCol(1, 1)

        hbox.Add(fgs, proportion=1, flag=wx.ALL|wx.EXPAND, border=15)
        panel.SetSizer(hbox)


if __name__ == '__main__':
  
    app = wx.App()
    Example(None, title='Review')
    app.MainLoop()

wxpython layout GoToClass

wxpython layout GoToClass
 
import wx

class Example(wx.Frame):
  
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title, 
            size=(390, 350))
            
        self.InitUI()
        self.Centre()
        self.Show()     
        
    def InitUI(self):
    
        panel = wx.Panel(self)

        font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT)
        font.SetPointSize(9)

        vbox = wx.BoxSizer(wx.VERTICAL)

        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        st1 = wx.StaticText(panel, label='Class Name')
        st1.SetFont(font)
        hbox1.Add(st1, flag=wx.RIGHT, border=8)
        tc = wx.TextCtrl(panel)
        hbox1.Add(tc, proportion=1)
        vbox.Add(hbox1, flag=wx.EXPAND|wx.LEFT|wx.RIGHT|wx.TOP, border=10)

        vbox.Add((-1, 10))

        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        st2 = wx.StaticText(panel, label='Matching Classes')
        st2.SetFont(font)
        hbox2.Add(st2)
        vbox.Add(hbox2, flag=wx.LEFT | wx.TOP, border=10)

        vbox.Add((-1, 10))

        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        tc2 = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
        hbox3.Add(tc2, proportion=1, flag=wx.EXPAND)
        vbox.Add(hbox3, proportion=1, flag=wx.LEFT|wx.RIGHT|wx.EXPAND, 
            border=10)

        vbox.Add((-1, 25))

        hbox4 = wx.BoxSizer(wx.HORIZONTAL)
        cb1 = wx.CheckBox(panel, label='Case Sensitive')
        cb1.SetFont(font)
        hbox4.Add(cb1)
        cb2 = wx.CheckBox(panel, label='Nested Classes')
        cb2.SetFont(font)
        hbox4.Add(cb2, flag=wx.LEFT, border=10)
        cb3 = wx.CheckBox(panel, label='Non-Project classes')
        cb3.SetFont(font)
        hbox4.Add(cb3, flag=wx.LEFT, border=10)
        vbox.Add(hbox4, flag=wx.LEFT, border=10)

        vbox.Add((-1, 25))

        hbox5 = wx.BoxSizer(wx.HORIZONTAL)
        btn1 = wx.Button(panel, label='Ok', size=(70, 30))
        hbox5.Add(btn1)
        btn2 = wx.Button(panel, label='Close', size=(70, 30))
        hbox5.Add(btn2, flag=wx.LEFT|wx.BOTTOM, border=5)
        vbox.Add(hbox5, flag=wx.ALIGN_RIGHT|wx.RIGHT, border=10)

        panel.SetSizer(vbox)


if __name__ == '__main__':
  
    app = wx.App()
    Example(None, title='Go To Class')
    app.MainLoop()

wxpython simple Toolbars example

wxpython simple Toolbars example
 
import wx

class Example(wx.Frame):
    
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs) 
            
        self.InitUI()
        
    def InitUI(self):    

        toolbar = self.CreateToolBar() #call CreateToolBar() method
        qtool = toolbar.AddLabelTool(wx.ID_ANY, 'Quit', wx.Bitmap('img/close.jpg'))
        toolbar.Realize()

        self.Bind(wx.EVT_TOOL, self.OnQuit, qtool) #To handle toolbar events, use the wx.EVT_TOOL event binder

        self.SetSize((250, 200))
        self.SetTitle('Simple toolbar')
        self.Centre()
        self.Show(True)
        
    def OnQuit(self, e):
        self.Close()

def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()

wxpython Context menu right click example

wxpython Context menu right click example
 
import wx

class MyPopupMenu(wx.Menu):
    
    def __init__(self, parent):
        super(MyPopupMenu, self).__init__()
        
        self.parent = parent

        mmi = wx.MenuItem(self, wx.NewId(), 'Minimize')
        self.AppendItem(mmi)
        self.Bind(wx.EVT_MENU, self.OnMinimize, mmi)

        cmi = wx.MenuItem(self, wx.NewId(), 'Close')
        self.AppendItem(cmi)
        self.Bind(wx.EVT_MENU, self.OnClose, cmi)


    def OnMinimize(self, e):
        self.parent.Iconize()

    def OnClose(self, e):
        self.parent.Close()
        

class Example(wx.Frame):
    
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs) 
            
        self.InitUI()
        
    def InitUI(self):
        #If right click on the frame, call the OnRightDown() method
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)

        self.SetSize((250, 200))
        self.SetTitle('Context menu')
        self.Centre()
        self.Show(True)
        
    def OnRightDown(self, e):
        self.PopupMenu(MyPopupMenu(self), e.GetPosition()) #call MyPopupMenu class
        # PopupMenu() method  shows the context menu, GetPosition() The context menus appear at the point of the mouse cursor
def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()

wxpython Check menu item Example

wxpython Check menu item Example
 
import wx


class Example(wx.Frame):
    
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs) 
            
        self.InitUI()
        
    def InitUI(self):    

        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        viewMenu = wx.Menu()
        #hide a statusbar and a toolbar
        self.shst = viewMenu.Append(wx.ID_ANY, 'Show statubar', 
            'Show Statusbar', kind=wx.ITEM_CHECK)
        self.shtl = viewMenu.Append(wx.ID_ANY, 'Show toolbar', 
            'Show Toolbar', kind=wx.ITEM_CHECK)
            
        viewMenu.Check(self.shst.GetId(), True) #check menu item true 
        viewMenu.Check(self.shtl.GetId(), True) # both statusbar and toolbar are visible

        self.Bind(wx.EVT_MENU, self.ToggleStatusBar, self.shst)
        self.Bind(wx.EVT_MENU, self.ToggleToolBar, self.shtl)

        menubar.Append(fileMenu, '&File')
        menubar.Append(viewMenu, '&View')
        self.SetMenuBar(menubar)

        self.toolbar = self.CreateToolBar()
        self.toolbar.AddLabelTool(1, '', wx.Bitmap('img/buttonforward.jpg'))
        self.toolbar.AddLabelTool(1, '', wx.Bitmap('img/buttonnext.jpg'))
        self.toolbar.Realize()

        self.statusbar = self.CreateStatusBar()
        self.statusbar.SetStatusText('Ready')

        self.SetSize((350, 250))
        self.SetTitle('Check menu item')
        self.Centre()
        self.Show(True)
        
        
    def ToggleStatusBar(self, e): 
        
        if self.shst.IsChecked():
            self.statusbar.Show() #if check is true the show status bar
        else:
            self.statusbar.Hide()

    def ToggleToolBar(self, e):
        
        if self.shtl.IsChecked():
            self.toolbar.Show() #if check is true the show toolbar
        else:
            self.toolbar.Hide()        

def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()

wxPython Submenus and separators Example

wxPython Submenus and separators Example
import wx


class Example(wx.Frame):
    
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs) 
            
        self.InitUI()
        
    def InitUI(self):

        menubar = wx.MenuBar()

        fileMenu = wx.Menu()
        fileMenu.Append(wx.ID_NEW, '&New')
        fileMenu.Append(wx.ID_OPEN, '&Open')
        fileMenu.Append(wx.ID_SAVE, '&Save')
        fileMenu.AppendSeparator() #separator

        imp = wx.Menu()
        imp.Append(wx.ID_ANY, 'Import newsfeed list...')
        imp.Append(wx.ID_ANY, 'Import bookmarks...')
        imp.Append(wx.ID_ANY, 'Import mail...')

        fileMenu.AppendMenu(wx.ID_ANY, 'I&mport', imp)

        qmi = wx.MenuItem(fileMenu, wx.ID_EXIT, '&Quit\tCtrl+W')
        fileMenu.AppendItem(qmi)

        self.Bind(wx.EVT_MENU, self.OnQuit, qmi)

        menubar.Append(fileMenu, '&File')
        self.SetMenuBar(menubar)

        self.SetSize((350, 250))
        self.SetTitle('Submenus and separators')
        self.Centre()
        self.Show(True)
        
    def OnQuit(self, e):
        self.Close()

def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()

wxPython Icons and shortcuts Example

wxPython Icons and shortcuts Example
import wx

APP_EXIT = 1

class myframe(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, -1, title="Hello")
        self.InitUI()

    def InitUI(self):

        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        qmi = wx.MenuItem(fileMenu, 100, '&Quit\tCtrl+Q')
        qmi.SetBitmap(wx.Image('quit.png', wx.BITMAP_TYPE_ANY).ConvertToBitmap()) #quit.png root folder
        fileMenu.AppendItem(qmi)

        self.Bind(wx.EVT_MENU, self.OnQuit, id=100)

        menubar.Append(fileMenu, '&File')
        self.SetMenuBar(menubar)

        self.SetSize((250, 200))
        self.SetTitle('Icons and shortcuts')
        self.Centre()
        self.Show(True)

    def OnQuit(self, e):
        self.Close()

def main():
    ex = wx.App()
    ex.locale = wx.Locale(wx.LANGUAGE_ENGLISH)
    myframe()
    ex.MainLoop()

if __name__ == '__main__':
    main()

wxPython simple menu example

wxPython simple menu example
import wx
class Example(wx.Frame):
    def __init__(self, *args, **kwargs):
        super(Example, self).__init__(*args, **kwargs) 
        self.InitUI()
    def InitUI(self):    
        menubar = wx.MenuBar() #menubar functionality
        fileMenu = wx.Menu() #menubar object
        fitem = fileMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application') #menu object
        menubar.Append(fileMenu, '&File')
        self.SetMenuBar(menubar)
        
        self.Bind(wx.EVT_MENU, self.OnQuit, fitem) #bind the wx.EVT_MENU

        self.SetSize((300, 200))
        self.SetTitle('Simple menu')
        self.Centre()
        self.Show(True)
        
    def OnQuit(self, e):
        self.Close()

def main():
    
    ex = wx.App()
    Example(None)
    ex.MainLoop()    


if __name__ == '__main__':
    main()

wxPython frame example

wxPython frame example
import wx
class Example(wx.Frame):
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title, 
            size=(300, 200))
        #self.Move((800, 250)) 
        #self.Centre()  #center window on our screen
        self.Show()
if __name__ == '__main__':
    app = wx.App()
    Example(None, title='Size and position')
    app.MainLoop()

Thursday, May 19, 2016

wxPython Phone Book using data grid view and sqlite3 database

wxPython Phone Book using data grid view and sqlite3 database 

Create database table

CREATE TABLE Phone (
ID INTEGER (11) PRIMARY KEY,
name VARCHAR (255),
surname VARCHAR (255),
telephone VARCHAR (255)
);
save the sqlite3 file as wx_gui_database.db in a folder called Data and place it in the same directory as your python script
import wx
import wx.grid
import os
import sqlite3
import re
import string
import gettext

cwd = os.path.abspath(os.curdir)

def connect():#this is the sqlite3 connection
    con_str=cwd + '/Data/wx_gui_database.db'
    cnn = sqlite3.connect(con_str)
    return cnn
    cnn.close()

def data_rows_count():# to count the rows in the database
    con = connect()
    cur=con.cursor()
    cur.execute("SELECT * FROM Phone")
    rows=cur.fetchall()
    i=0
    for r in rows:
        i+=1
    return i

def fmtstr(fmt, strr):# to format some string!!!
    res = []
    i = 0
    s=re.sub(r'[^\w]','',strr)
    for c in fmt:
        if c == '#':
            res.append(s[i:i+1])
            i = i+1
        else:
            res.append(c)
    res.append(s[i:])
    return string.join(res)

def titling(name):# to display the names and surnames in uppercase for 1st letter
    return name.title()

def single_quote_remover(text):# to remove single quotes from entry to prevent SQL crash
    return text.replace ("'","/")

def single_quote_returner(text):# to display the single quote for the user ex: cote d'or as chocolat:)))
    return text.replace("/","'")

class MyFrame(wx.Frame):# this is the parent frame
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.frame_1_menubar = wx.MenuBar()
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(1, _("Index"), "", wx.ITEM_NORMAL)
        self.frame_1_menubar.Append(wxglade_tmp_menu,_("Phone Book"))
        wxglade_tmp_menu = wx.Menu()
        wxglade_tmp_menu.Append(2, _("Message"), "", wx.ITEM_NORMAL)
        self.frame_1_menubar.Append(wxglade_tmp_menu,_("About"))
        self.SetMenuBar(self.frame_1_menubar)
        self.__set_properties()
        self.__do_layout()
        self.Bind(wx.EVT_MENU, self.open_dialog, id=1)
        self.Bind(wx.EVT_MENU,self.open_dialog1,id =2)

    def __set_properties(self):
        self.SetTitle(_("MyPhoneBook"))
        self.SetSize((555, 444))
        self.SetBackgroundColour(wx.Colour(255, 255, 255))

    def __do_layout(self):
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer_1)
        self.Layout()

    def open_dialog(self, event):
        MyDialog1(self).Show()

    def open_dialog1(self,event):
        wx.MessageBox("A simple wxpython PhoneBook that resumes basic graphical sqlite3 database configuration\n\n ")

class MyDialog1(wx.Dialog):# this is the PhoneBook dialog box...
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE
        wx.Dialog.__init__(self, *args, **kwds)
        self.label_10 = wx.StaticText(self, -1, _(" ID"))
        self.txtID = wx.TextCtrl(self, -1, "")
        self.label_11 = wx.StaticText(self, -1, _(" Name"))
        self.txtNAME = wx.TextCtrl(self, -1, "")
        self.label_12 = wx.StaticText(self, -1, _(" Surname"))
        self.txtSURNAME = wx.TextCtrl(self, -1, "")
        self.label_13 = wx.StaticText(self, -1, _(" Number"))
        self.txtNUMBER = wx.TextCtrl(self, -1, "")
        self.button_6 = wx.Button(self, -1, _("UPDATE"))
        self.button_5 = wx.Button(self, -1, _("ADD"))
        self.button_7 = wx.Button(self, -1, _("DELETE"))
        self.button_8 = wx.Button(self, -1, _("LOAD"))
        self.grid_1 = wx.grid.Grid(self, -1, size=(1, 1))
        self.label_14 = wx.StaticText(self, -1, _("  Search Name:"))
        self.txtSearch = wx.TextCtrl(self, -1, "")
        self.button_9 = wx.Button(self, -1, _(" Go"))
        self.button_10 = wx.Button(self, -1, _("Renumber"))
        self.txtNAME.SetFocus()
        self.button_6.Enabled=False
        self.txtID.Enabled=False
        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_BUTTON, self.clk_add, self.button_5)
        self.Bind(wx.EVT_BUTTON, self.clk_update, self.button_6)
        self.Bind(wx.EVT_BUTTON, self.clk_delete, self.button_7)
        self.Bind(wx.EVT_BUTTON, self.clk_load, self.button_8)
        self.Bind(wx.EVT_BUTTON, self.clk_go, self.button_9)
        self.Bind(wx.EVT_BUTTON, self.clk_renumber, self.button_10)
        
    def refresh_data(self):
        cnn =connect()
        cur = cnn.cursor()
        cur.execute("SELECT * FROM Phone")
        rows=cur.fetchall()
        for i in range (0,len(rows)):
            for j in range(0,4):
                cell = rows[i]
                self.grid_1.SetCellValue(i,j,str(cell[j]))

    def __set_properties(self):
        self.SetTitle(_("PyPhone"))
        self.SetSize((600, 550))
        self.txtID.SetMinSize((120, 27))
        self.txtNAME.SetMinSize((120, 27))
        self.txtSURNAME.SetMinSize((120, 27))
        self.txtNUMBER.SetMinSize((120, 27))
        r=data_rows_count()
        self.grid_1.CreateGrid(r, 4)#this is to create the grid with same rows as database
        self.grid_1.SetColLabelValue(0, _("ID"))
        self.grid_1.SetColSize(0, 12)
        self.grid_1.SetColLabelValue(1, _("NAME"))
        self.grid_1.SetColSize(1, 150)
        self.grid_1.SetColLabelValue(2, _("SURNAME"))
        self.grid_1.SetColSize(2, 150)
        self.grid_1.SetColLabelValue(3, _("NUMBER"))
        self.grid_1.SetColSize(3, 150)
        self.txtSearch.SetMinSize((100, 27))
        self.refresh_data()

    def __do_layout(self):
        sizer_4 = wx.BoxSizer(wx.VERTICAL)
        grid_sizer_4 = wx.GridSizer(1, 4, 0, 0)
        grid_sizer_3 = wx.GridSizer(4, 3, 0, 0)
        sizer_4.Add((20, 20), 0, 0, 0)
        grid_sizer_3.Add(self.label_10, 0, 0, 0)
        grid_sizer_3.Add(self.txtID, 0, 0, 0)
        grid_sizer_3.Add(self.button_5, 0, 0, 0)
        grid_sizer_3.Add(self.label_11, 0, 0, 0)
        grid_sizer_3.Add(self.txtNAME, 0, 0, 0)
        grid_sizer_3.Add(self.button_6, 0, 0, 0)
        grid_sizer_3.Add(self.label_12, 0, 0, 0)
        grid_sizer_3.Add(self.txtSURNAME, 0, 0, 0)
        grid_sizer_3.Add(self.button_7, 0, 0, 0)
        grid_sizer_3.Add(self.label_13, 0, 0, 0)
        grid_sizer_3.Add(self.txtNUMBER, 0, 0, 0)
        grid_sizer_3.Add(self.button_8, 0, 0, 0)
        sizer_4.Add(grid_sizer_3, 1, wx.EXPAND, 0)
        sizer_4.Add(self.grid_1, 1, wx.EXPAND, 0)
        sizer_4.Add((20, 20), 0, 0, 0)
        grid_sizer_4.Add(self.label_14, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_4.Add(self.txtSearch, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_4.Add(self.button_9, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        grid_sizer_4.Add(self.button_10, 0, wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_4.Add(grid_sizer_4, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_4)
        self.Layout()

    def clear_grid(self):
        self.txtID.Value=""
        self.txtNAME.Value=""
        self.txtSURNAME.Value=""
        self.txtNUMBER.Value=""

    def auto_number(self):
        j=data_rows_count()
        return j+1  

    def clk_add(self, event):
        if self.txtNAME.Value == "" or self.txtSURNAME.Value == "" or self.txtNUMBER.Value == "":
            wx.MessageBox("Some Fields Are Empty!")
        else:
            the_id=str(self.auto_number())
            the_name=single_quote_remover(str(self.txtNAME.Value))
            the_surname=single_quote_remover(str(self.txtSURNAME.Value))
            num=fmtstr('##-######',(str(self.txtNUMBER.Value)))#set the format here to the country u want
            name=titling(the_name)
            surname=titling(the_surname)
            self.grid_1.AppendRows(1)
            cnn = connect()
            cursor = cnn.cursor()
            add_many = "INSERT INTO Phone(ID,name,surname,telephone) VALUES("+(the_id)+",'"+(name)+"','"+(surname)+"','"+(num)+"')"
            cursor.execute(add_many)
            cnn.commit()
            cnn.close()
            self.refresh_data()
            self.clear_grid()
            self.txtNAME.SetFocus()
        event.Skip()

    def clk_update(self, event):
        try:
            num=fmtstr('##-######',str(self.txtNUMBER.Value))
            the_name=single_quote_remover(str(self.txtNAME.Value))
            the_surname=single_quote_remover(str(self.txtSURNAME.Value))
            name=titling(the_name)
            surname=titling(the_surname)
            row_index = self.grid_1. GetSelectedRows()[0]
            c=self.grid_1.GetCellValue(row_index,0)
            cnn=connect()
            cur=cnn.cursor()
            cur.execute("UPDATE Phone SET name = "+ "'"+(name)+"'" + " ,surname="+ "'"+(surname)+"'" +",telephone=" + "'" +(num) + "'" + "WHERE ID="+"'" + str(c) + "'")
            cnn.commit()
            cnn.close()
            self.refresh_data()
            cnn.close()
            self.clear_grid()
            self.button_6.Enabled=False
            self.button_5.Enabled=True
            self.txtNAME.SetFocus()
            event.Skip()
        except IndexError:
            wx.MessageBox("you have lost focus on the row you wanted to edit")

    def clk_delete(self, event):
        try:
            lst = self.grid_1. GetSelectedRows()[0]
            c=self.grid_1.GetCellValue(lst,0)
            cnn=connect()
            cur=cnn.cursor()
            cur.execute("DELETE FROM Phone WHERE ID="+"'" + str(c) + "'")
            cnn.commit()
            cnn.close()
            self.grid_1.DeleteRows(lst,1)
            self.refresh_data()
            self.txtNAME.SetFocus()
        except IndexError:
            wx.MessageBox("You Did Not Select Any Row To Delete!")
        event.Skip()

    def clk_load(self, event):
        try:
            row_index = self.grid_1.GetSelectedRows()[0]
            cell_value=[]
            for i in range(0,4):
                cell_value.append(self.grid_1.GetCellValue(row_index,i))
            self.txtID.Value= str(cell_value[0])
            self.txtNAME.Value=str(cell_value[1])
            self.txtSURNAME.Value=str(cell_value[2])
            self.txtNUMBER.Value=str(cell_value[3])
            self.button_6.Enabled=True
            self.button_5.Enabled=False
            self.txtNAME.SetFocus()
            event.Skip()
        except IndexError:
            wx.MessageBox("You Did Not Select Any Row To Load")
            

    def clk_go(self, event):
        r=data_rows_count()
        for e in range(0,r):
            for f in range(0,4):
                self.grid_1.SetCellValue(e,f,"")
        cnn=connect()
        cursor=cnn.cursor()
        cursor.execute("SELECT * FROM Phone WHERE name LIKE '%"+self.txtSearch.Value+"%'") 
        cnn.commit()
        rows=cursor.fetchall()
        for i in range(len(rows)):
            for j in range(0,4):
                cell=rows[i]
                self.grid_1.SetCellValue(i,j,str(cell[j]))
        cnn.close()
        self.txtSearch.SetFocus()
        event.Skip()

    def clk_renumber(self, event):
        Backup_Messasse=wx.MessageDialog(None, "It Is Preferable To Backup Your Database Before You Continue! Do You Wish To Proceed?",'Caution!',wx.YES_NO | wx.ICON_QUESTION)
        Response=Backup_Messasse.ShowModal()
        if(Response==wx.ID_NO):
            Backup_Messasse.Destroy()
        if(Response==wx.ID_YES):
            cnn = connect()
            cur = cnn.cursor()
            cur.execute("SELECT * FROM Phone")
            rows=cur.fetchall()
            i=0
            m=()
            for r in rows:
                i+=1
                s=str(r).replace(str(r[0]),str(i))
                t=s.replace ("u'","'")
                x=eval(t)
                m+=(x,)
                cur.execute("DELETE FROM Phone")
                add_many="INSERT INTO Phone VALUES(?,?,?,?)"
                cur.executemany(add_many,m)
            wx.MessageBox("Renumbering Successful!")
            cur.execute("SELECT * FROM Phone")
            TheRows = cur.fetchall()
            for i in range(len(TheRows)):
                for j in range(0,4):
                    cell=TheRows[i]
                    self.grid_1.SetCellValue(i,j,str(cell[j]))
            cnn.commit()
            cnn.close()
            self.txtNAME.SetFocus()
            event.Skip()

if __name__ == "__main__":
    gettext.install("app")
    app = wx.App(False)
    #wx.InitAllImageHandlers()
    frame_1 = MyFrame(None, wx.ID_ANY, "")
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()

Saturday, May 14, 2016

Custom Authentication Sign In Sign Up in Laravel

Custom Authentication Sign In Sign Up in Laravel

Create dabase Table 

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `remember_token` varchar(255) NOT NULL,
  `updated_at` varchar(255) NOT NULL,
  `created_at` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Assign routes URL http://localhost/laravel/login
laravel\app\Http\routes.php

Route::get('login',function(){
   return view('login');
});
Route::post ( '/login', 'MainController@login' );
Route::post ( '/register', 'MainController@register' );
Route::get ( '/logout', 'MainController@logout' );
Create Login template
laravel\resources\views\login.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Custom Authentication in Laravel</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{{ asset('/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet" type="text/css" />   
<script src="{{ asset('/bootstrap/js/modernizr.min.js') }}"></script>
<script src="{{ asset('/bootstrap/js/bootstrap.min.j') }}"></script>
<script src="{{ asset('/bootstrap/js/jquery.min.js') }}"></script>
</head>
<body id="page-top" class="index">
 <!-- Navigation -->
    <nav class="navbar navbar-default navbar-fixed-top">
        <div class="container">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header page-scroll">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#page-top">Start Bootstrap</a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav navbar-right">
                    <li class="hidden">
                        <a href="#page-top"></a>
                    </li>
                    <li class="page-scroll">
                        <a href="#home">Home</a>
                    </li>
                    @if (session()->get('name'))
     <li class="laravel-right">Welcome {{session()->get('name') }} , <a class="laravel-right" href="/laravel/logout">Logout</a> </li> @else
     <li class="laravel-right"><a class="laravel-green" href="#" id="auth" onclick="document.getElementById('authentication').style.display='block'">Login / SignUp</a></li>
     @endif
                </ul>
            </div>
            <!-- /.navbar-collapse -->
        </div>
        <!-- /.container-fluid -->
    </nav>
    <section class="content">
        <div class="container">
            <div class="row">
                <div id="authentication" class="laravel-modal">
  <span onclick="document.getElementById('authentication').style.display='none'" class="laravel-closebtn laravel-grey laravel-hover-red laravel-container laravel-padding-16 laravel-display-topright">X</span>

  <div class="laravel-modal-content laravel-card-8 laravel-animate-zoom" style="max-width: 600px">
   <div class="col-md-6 laravel-card-8 laravel-teal" onclick="openForm('Login')">
    <h3>Sign In</h3>
   </div>
   <div class="col-md-6 laravel-card-8 laravel-teal"
    onclick="openForm('Register')">
    <h3>Sign Up</h3>
   </div>
   <div style="margin-top: 25px !important;">
    <div id="Login" class="laravel-container form">
     <div class="laravel-container ">
      <div class="laravel-section">
       <br> <br>@if (count($errors->login) > 0)
       <div class="alert alert-danger">
        <ul>
         @foreach ($errors->login->all() as $error)
         <P>{{ $error }}</p>
         @endforeach
        </ul>
       </div>
       @endif 
       @if (Session::has('message'))
       <div class="alert alert-warning">{{ Session::get('message') }}</div>
       @endif
       <form action="/laravel/login" method="POST">
        {{ csrf_field() }} <input type="hidden" class="form-control" name="redirurl" value="{{ $_SERVER['REQUEST_URI'] }}"> 
        <div class="form-group">
        <label><b>Username</b></label>
        <input name="username" class="form-control" type="text" placeholder="Enter Username" required> 
        </div>
        <div class="form-group">
        <label><b>Password</b></label>
        <input class="form-control" name="password" type="password" placeholder="Enter Password" required> 
        </div>
        <div class="form-group"><input type="submit" class="btn btn-success" value="Login" style="width:100%;"></div> 
        <div class="checkbox"><label><input  type="checkbox" checked="checked"> Remember me</label>
       </form>
      </div>
     </div>
     <div class="laravel-container laravel-border-top laravel-padding-16 ">
      <button onclick="document.getElementById('authentication').style.display='none'" type="button" class="btn btn-danger">Cancel</button>
      <span class="laravel-right laravel-padding laravel-hide-small">Forgot <a href="#">password?</a></span>
     </div>
    </div>
   </div>
   <div id="Register" class="laravel-container form ">
    <div class="laravel-container">
     <div class="laravel-section">

      <br> <br> 
      @if (count($errors->register) > 0)
      <div class="alert alert-danger">
       <ul>
        @foreach ($errors->register->all() as $error)
        <P>{{ $error }}</p>
        @endforeach
       </ul>
      </div>
      @endif
      <form action="/laravel/register" method="POST" id="regForm">
       {{ csrf_field() }} <input type="hidden" name="redirurl"
        value="{{ $_SERVER['REQUEST_URI'] }}"> 
       <div class="form-group">
       <label><b>Email</b></label>
       <input class="form-control" type="text" name="email" placeholder="Enter Email" value="{{ old('email') }}" required> 
       </div>
       <div class="form-group">
       <label><b>Username</b></label>
       <input class="form-control" type="text" name="name" placeholder="Enter username" required value="{{ old('name') }}"> 
       </div>
       <div class="form-group">
       <label><b>Password</b></label> 
       <input class="form-control" type="password" name="password" required placeholder="Enter Password"> 
       </div> 
       <div class="form-group">
       <label><b>Confirm Password</b></label> 
       <input class="form-control" required type="password" name="password_confirmation" placeholder="Enter Password">
       </div>
       <div class="form-group"><input type="submit" class="btn btn-success" value="SignUp" style="width:100%;"></div> 
      </form>
     </div>
    </div>
    <div class="laravel-container laravel-border-top laravel-padding-16 ">
     <button onclick="document.getElementById('authentication').style.display='none'" type="button" class="btn btn-danger">Cancel</button>
    </div>
   </div>
  </div>
 </div>
 <div class="fluid-container"></div>
            </div>
        </div>
    </section>
 <script> 
openForm("Login");
function openForm(formName) {
    
    var x = document.getElementsByClassName("form");
    for (i = 0; i < x.length; i++) {
       x[i].style.display = "none";  
    }
    document.getElementById(formName).style.display = "block";  
}
</script>
@if (Session::has('message'))
 <script>  $('#auth').click(); </script>
 @endif @if($errors->login->any())
 <script>  $('#auth').click();</script>
 @endif @if($errors->register->any())
 <script>  $('#auth').click(); openForm('Register');</script>
 @endif
<style>
.navbar {
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700;
}
.navbar a:focus {
  outline: none;
}
.navbar .navbar-nav {
  letter-spacing: 1px;
}
.navbar .navbar-nav li a:focus {
  outline: none;
}
.navbar-default,
.navbar-inverse {
  border: none;
}

.laravel-modal {
    z-index: 3;
    display: none;
    padding-top: 100px;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgb(0,0,0);
    background-color: rgba(0,0,0,0.4);
}
.laravel-grey, .laravel-hover-grey:hover {
    color: #000!important;
    background-color: #9e9e9e!important;
}
.laravel-container {
    padding: 0.01em 16px;
}
.laravel-padding-16, .laravel-padding-hor-16 {
    padding-top: 16px!important;
    padding-bottom: 16px!important;
}
.laravel-display-topright {
    position: absolute;
    right: 0;
    top: 0;
}
.laravel-closebtn {
    text-decoration: none;
    float: right;
    font-size: 24px;
    font-weight: bold;
    color: inherit;
}
.laravel-animate-zoom {
    -webkit-animation: animatezoom 0.6s;
    animation: animatezoom 0.6s;
}
.laravel-card-8 {
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19)!important;
}
.laravel-modal-content {
    margin: auto;
    background-color: #fff;
    position: relative;
    padding: 0;
    outline: 0;
    width: 600px;
}
.laravel-teal, .laravel-hover-teal:hover {
    color: #fff!important;
    background-color: #009688!important;
}
.laravel-card-8 {
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19)!important;
}
.laravel-section {
    margin-top: 36px!important;
    margin-bottom: 16px!important;
}
.laravel-green, .laravel-hover-green:hover {
    color: #fff!important;
    background-color: #4CAF50!important;
}
.laravel-right {
    float: right!important;
}
</style> 
</body>
</html>

Create Controller

laravel\app\Http\Controllers\MainController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Hash;
use Auth;
use Redirect;
use Session;
use Validator;
use Illuminate\Support\Facades\Input;

class MainController extends Controller {
public function login(Request $request) {
  $rules = array (
    
    'username' => 'required',
    'password' => 'required' 
  );
  $validator = Validator::make ( Input::all (), $rules );
  if ($validator->fails ()) {
   return Redirect::back ()->withErrors ( $validator, 'login' )->withInput ();
  } else {
   if (Auth::attempt ( array (
     
     'name' => $request->get ( 'username' ),
     'password' => $request->get ( 'password' ) 
   ) )) {
    session ( [ 
      
      'name' => $request->get ( 'username' ) 
    ] );
    return Redirect::back ();
   } else {
    Session::flash ( 'message', "Invalid Credentials , Please try again." );
    return Redirect::back ();
   }
  }
 }
 public function register(Request $request) {
  $rules = array (
    'email' => 'required|unique:users|email',
    'name' => 'required|unique:users|alpha_num|min:4',
    'password' => 'required|min:6|confirmed' 
  );
  $validator = Validator::make ( Input::all (), $rules );
  if ($validator->fails ()) {
   return Redirect::back ()->withErrors ( $validator, 'register' )->withInput ();
  } else {
   $user = new User ();
   $user->name = $request->get ( 'name' );
   $user->email = $request->get ( 'email' );
   $user->password = Hash::make ( $request->get ( 'password' ) );
   $user->remember_token = $request->get ( '_token' );
   
   $user->save ();
   return Redirect::back ();
  }
 }
 public function logout() {
  Session::flush ();
  Auth::logout ();
  return Redirect::back ();
 }
}

localhost url http://localhost/laravel/login

Sunday, April 10, 2016

Nette Framework

Nette Framework

A popular tool for creating web applications in PHP. Powerful and understandable tool that satisfies the programmers. It eliminates security risks, honors for AJAX, DRY, KISS, MVC and code reuse.

Nette Framework comes with a whole array of technical innovations – you will create perfectly secured applications, which will be easily extensible. It has an active community of PHP developers and many companies have put it to good use.

Download : https://nette.org/en/download


Laravel 5 - Remove public from URL

Laravel 5 - Remove public from URL

From url http://localhost/laravel/public

To http://localhost/laravel/

1. Rename the server.php in the your Laravel root folder to index.php
2. copy the .htaccess file from /public directory to your Laravel root folder. Thats it !!

Related Post