Jump to content

Need help for my first admin module


Recommended Posts

Hi All,

 

Today I'm trying to create my first admin module. The goal is to show a small form with the weeks of the year. When the administrator selects a week and post the form, A list displays with products sold in the week. This module has no relation at all with the front.

Then I created a module named "clark" with a subfolder "controller", "admin" and the file AdminClarkController.php.

The module is installed and a new link appears in the menu. OK.

 

So in my controller:

class AdminClarkController extends ModuleAdminController
{
	public $date_debut = '2016-01-04';
	
	
	public function __construct() {
		$this->context = Context::getContext();
		parent::__construct();
	}
	
	
	public function renderForm()
    {
		$debut_sem = $this->dateFromWeek($this->date_debut);
		//echo $debut_sem;
		$year = date('Y');
		$sem = date('W');
		for($i=$debut_sem;$i<=date('W');$i++){
			$sem_liste = $this->get_lundi_samedi_from_week($i,$year);
			($sem == $i) ? $this->fields_value['invoice'] = $i : $this->fields_value['invoice'] = ''; ; 
			//$ligne .= '<option value="'.$i.'" '.$sel.'>Week N° '.$i.' (from '.$sem_liste[0].' to '.$sem_liste[1].')</option>';
			$options[] = array('id_option'=>$i, 'name'=>'Week N° '.$i.' (from '.$sem_liste[0].' to '.$sem_liste[1].')');
		}
		
		$this->fields_form = array(
		  'legend' => array(       
			'title' => $this->l('Choose a week to see the sales'),       
			/*'image' => ''  */
		  ),   
		  'input' => array(       
			array(           
			  'type' => 'select',  
			  'label' => $this->l('Select a week:'),
			  'name' => 'invoice',
			  'required' => true,
			  'options' => array(
				'query' => $options,                           
				'id' => 'id_option',                         
				'name' => 'name',                            
			  ),	
			 ),
		  ),
		  'submit' => array(
			'title' => $this->l('See the results'),       
			'class' => 'btn btn-default pull-right'   
		  )
		);		
		return parent::renderForm();
    }

	public function get_lundi_samedi_from_week($week,$year,$format="d-m-Y") {
	
		$firstDayInYear=date("N",mktime(0,0,0,1,1,$year));
		if ($firstDayInYear<5)
		$shift=-($firstDayInYear-1)*86400;
		else
		$shift=(8-$firstDayInYear)*86400;
		if ($week>1) $weekInSeconds=($week-1)*604800; else $weekInSeconds=0;
		$timestamp=mktime(0,0,0,1,1,$year)+$weekInSeconds+$shift;
		$timestamp_vendredi=mktime(0,0,0,1,5,$year)+$weekInSeconds+$shift;
		
		return array(date($format,$timestamp),date($format,$timestamp_vendredi));
	}
	
	public function dateFromWeek($date){
  		
		list($year, $month, $day) = explode('-', $date);
  		$weekNum = (date('W', mktime(0, 0, 0, $month, $day, $year)) * 1);
  		return $weekNum;
	}




}

This code displays my select with weeks and a button to post the form.

But from there, I don't know what to do anymore.

 

I read tutos, examples etc...but I'm lost between the methods postProcess, displayForm etc...and I don't know if I must use a template in the folder modules/clark/views/templates/admin/helpers/form or maybe in modules/clark/views/templates/admin/content.tpl.

 

Which method to use after posting to build the SQL request and display the result as a HTML table ?

Thanking you in advance for your help.

Edited by renaud2263 (see edit history)
Link to comment
Share on other sites

After hundreds tests, I am here :

	public function renderForm()
    {
		$debut_sem = $this->dateFromWeek($this->date_debut);
		//echo $debut_sem;
		$year = date('Y');
		$sem = date('W');
		for($i=$debut_sem;$i<=date('W');$i++){
			$sem_liste = $this->get_lundi_samedi_from_week($i,$year);
			($sem == $i) ? $this->fields_value['invoice'] = $i : $this->fields_value['invoice'] = ''; ; 
			//$ligne .= '<option value="'.$i.'" '.$sel.'>Week N° '.$i.' (from '.$sem_liste[0].' to '.$sem_liste[1].')</option>';
			$options[] = array('id_option'=>$i, 'name'=>'Week N° '.$i.' (from '.$sem_liste[0].' to '.$sem_liste[1].')');
		}
		
		$this->fields_form = array(
		  	'legend' => array(       
			'title' => $this->l('Choose a week to see the sales'),       
			/*'image' => ''  */
		  ),   
		  'input' => array(       
			array(           
			  'type' => 'select',  
			  'label' => $this->l('Select a week:'),
			  'name' => 'invoice',
			  'required' => true,
			  'options' => array(
				'query' => $options,                           
				'id' => 'id_option',                         
				'name' => 'name',                            
			  ),	
			),
		  ),
		  'submit' => array(
			'title' => $this->l('See the results'),       
			'class' => 'btn btn-default pull-right'   
		  )
		);		
		return parent::renderForm();
    }

Ok with the form as I want.

Now trying to display results

	public function postProcess()
	{
        //$output = '';
        if (Tools::isSubmit('invoice')) {
        $sem = Tools::getValue("invoice");
		
		$output = '';
		$sql = "SELECT ca.product_id, ca.product_name, ca.product_supplier_reference, SUM(ca.product_quantity) as qte
		FROM "._DB_PREFIX_."order_detail ca LEFT JOIN "._DB_PREFIX_."orders c ON ca.id_order = c.id_order
		
		WHERE (YEAR(DATE(c.delivery_date)) = '".$this->year."' AND WEEK(DATE(c.delivery_date)) = '".$sem."') 
		GROUP BY ca.product_id ORDER BY ca.product_supplier_reference";
		
		if ($res = Db::getInstance()->ExecuteS($sql)){
			foreach ($res as $row){
				$output .= $row['product_name'].' :: '.$row['qte'].'<br />';	
			}
		}
		//echo $output; this output is OK
		$sm = new Smarty();
		$tpl = $sm->createTemplate($this->getTemplatePath().'content.tpl')->fetch();
		
        $this->context->smarty->assign('resultat', $output);
        
	   return parent::postProcess();
	}
     public function getTemplatePath()
    {
        return _PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/';
    }   


and my simple template content.tpl

<div class="row">
    <div>{$resultat|default:' '}</div>
</div>

But no display at all. No mistake, nothing. Where is my error ?

Edited by renaud2263 (see edit history)
Link to comment
Share on other sites

what is the purpose of this code?

        $sm = new Smarty();
        $tpl = $sm->createTemplate($this->getTemplatePath().'content.tpl')->fetch();

You see the expected results in the browser when you echo $output?

        //echo $output; this output is OK

try adding more content to content.tpl, this way you know for sure that your template is being displayed...

<div class="row">
<div>  
    These are my results:<br>
    {$resultat|default:' '}
</div>
</div>
Link to comment
Share on other sites

Hi,

 

At the beginning, my template was called like that :

$tpl = $this->createTemplate('content.tpl')->fetch();

and the function:

	public function createTemplate($tpl_name) {
        if (file_exists($this->getTemplatePath() . $tpl_name) && $this->viewAccess())
            return $this->context->smarty->createTemplate($this->getTemplatePath() . $tpl_name, $this->context->smarty);
			
        return parent::createTemplate($tpl_name);
    }

And if I use this function, the form is not displayed at all on the loading page. I also tried to use it after the post is submitted: the results are displayed !

 

Regarding the output: yes if I do an echo it displayed but before the header of the page so error of output before header.

 

I placed your code on my template file: so when I call the page, the words "These are my results:" are shown instead of the form.

Conclusion: when page is loading, the function createTemplate is called before the renderForm

Link to comment
Share on other sites

public function renderView()
{

 

$custom_html = "<a> HI IM A CUSTOM VIEW</a>";

 

return $this->renderForm().$custom_html; // OR SIMILAR method, here we add the form you want and other html after the form

}

 

I dont know that if this that you want, i understand that yes it is.

 

Regards.

Link to comment
Share on other sites

Hi,

 

No, in fact renderForm is called

    public function renderList()
    {
       return $this->renderForm();
	
    }

Then my form is displayed when the page is loaded. So I select a week and post the form.

 

After that, the method postProcess contains a SQL request which returns an array with result. I want to display these results in my view/template/admin/content.tpl like that :

		$tpl = $this->createTemplate('content.tpl')->fetch();
                $tab_data = '';
		if ($res = Db::getInstance()->ExecuteS($sql)){
			foreach ($res as $row){
				//$output .= $row['product_name'].' :: '.$row['qte'].'<br />';	
				$tab_data .= '<tr><td>'.$row['product_id'].'</td><td>'.$row['product_supplier_reference'].'</td><td>'.$row['product_name'].'</td>
				<td>'.$row['qte'].'</td><td>'.$row['purchase_supplier_price'].'</td><td>'.$row['tot_line'].'</td></tr>'; 
			}
		}
		
        $this->context->smarty->assign('tabData', $tab_data);

But nothing happens. No display, no error (even with debug_mode true).

I think the problem comes from this function :

	public function createTemplate($tpl_name) {
        if (file_exists($this->getTemplatePath() . $tpl_name) && $this->viewAccess())
            return $this->context->smarty->createTemplate($this->getTemplatePath() . $tpl_name, $this->context->smarty);
			
        return parent::createTemplate($tpl_name);
    }

Or I let this function and the content of the template is displayed on the loading page instead of the form,

Or I delete this function, my form is displayed but nothing happens when I post it - I suppose because no template is loaded to display the results.

Link to comment
Share on other sites

Why dont use ajax to get response and add dinamycally with javascript to your form?.

 

You want to do it dynamycally with php, is so hard this. 

 

Because my request is very simple ! The only problem is to display the result. My form is a select with all the weeks of the year by number.

 

In postProcess function the SQL request :

$sql = "SELECT ca.product_id, ca.product_name, ca.product_supplier_reference, SUM(ca.product_quantity) AS qte, purchase_supplier_price,
		(ca.purchase_supplier_price * SUM(ca.product_quantity)) AS tot_line
		FROM "._DB_PREFIX_."order_detail ca LEFT JOIN "._DB_PREFIX_."orders c ON ca.id_order = c.id_order
		
		WHERE (YEAR(DATE(c.delivery_date)) = '".$this->year."' AND WEEK(DATE(c.delivery_date)) = '".$sem."') 
		GROUP BY ca.product_id ORDER BY ca.product_supplier_reference";
		$tab_data = '';
		if ($res = Db::getInstance()->ExecuteS($sql)){
			foreach ($res as $row){
				$tab_data .= '<tr><td>'.$row['product_id'].'</td><td>'.$row['product_supplier_reference'].'</td><td>'.$row['product_name'].'</td>
				<td>'.$row['qte'].'</td><td>'.$row['purchase_supplier_price'].'</td><td>'.$row['tot_line'].'</td></tr>'; 
			}
		}

The var $tab_data contains all the results I need, it's perfect. I just want to replace {$tabData} by the datas in the template (or by other way) and display in the page !

Link to comment
Share on other sites

In fact, no need to formProcess function, all can be done in renderForm:

	public function renderForm()
    {
		$debut_sem = $this->dateFromWeek($this->date_debut);
		
		$year = date('Y');
		$sem = date('W');
		for($i=$debut_sem;$i<=date('W');$i++){
			$sem_liste = $this->get_lundi_samedi_from_week($i,$year);
			($sem == $i) ? $this->fields_value['invoice'] = $i : $this->fields_value['invoice'] = ''; ; 
			
			$options[] = array('id_option'=>$i, 'name'=>'Week N° '.$i.' (from '.$sem_liste[0].' to '.$sem_liste[1].')');
		}
		
		$this->fields_form = array(
		  	'legend' => array(       
			'title' => $this->l('Choose a week to see the sales'),       
			/*'image' => ''  */
		  ),   
		  'input' => array(       
			array(           
			  'type' => 'select',  
			  'label' => $this->l('Select a week:'),
			  'name' => 'invoice_week',
			  'required' => true,
			  'options' => array(
				'query' => $options,                           
				'id' => 'id_option',                         
				'name' => 'name',                            
			  ),	
			),
		  ),
		  'submit' => array(
			'title' => $this->l('See the results'),       
			'class' => 'btn btn-default pull-right'   
		  )
		);		
		
		 if (Tools::isSubmit('invoice_week')) {
			 //$text = "La var select vaut ".Tools::getValue("invoice_week");
			$sem = Tools::getValue("invoice_week");
			$this->context->smarty->assign('sem', $sem);
			 
			$sql = "SELECT ca.product_id, ca.product_name, ca.product_supplier_reference, SUM(ca.product_quantity) AS qte, purchase_supplier_price,
			(ca.purchase_supplier_price * SUM(ca.product_quantity)) AS tot_line
			FROM "._DB_PREFIX_."order_detail ca LEFT JOIN "._DB_PREFIX_."orders c ON ca.id_order = c.id_order
			
			WHERE (YEAR(DATE(c.delivery_date)) = '".$this->year."' AND WEEK(DATE(c.delivery_date)) = '".$sem."') 
			GROUP BY ca.product_id ORDER BY ca.product_supplier_reference";
			$tab_data = '';
			if ($res = Db::getInstance()->ExecuteS($sql)){
				foreach ($res as $row){
					//$output .= $row['product_name'].' :: '.$row['qte'].'<br />';	
					$tab_data .= '<tr><td>'.$row['product_id'].'</td><td>'.$row['product_supplier_reference'].'</td><td>'.$row['product_name'].'</td>
					<td>'.$row['qte'].'</td><td>'.$row['purchase_supplier_price'].'</td><td>'.$row['tot_line'].'</td></tr>'; 
				}
			}
			 $this->context->smarty->assign('tabData', $tab_data);
			 return parent::renderForm().$this->context->smarty->createTemplate($this->getTemplatePath() . 'content.tpl', $this->context->smarty)->fetch();
			 
		}
		return parent::renderForm();
    }

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...