PHPExcel to bold text in between HTML markups <B> and <strong> - javascript

HI folks ive been trying to figure out a problem that's been haunting me for some time now and original started this thread thread PHPExcel - How to replace text using preg_replace. I was going about this all the wrong way and Mark gave me some tips on where to start. I gave up this project as I was very clueless of how to even start a script for this.
What I am currently attempting is to bold text that are within HTML marker <B> and <Strong>. After spending some time studying Jquery and some javascript to help me with this. I am understanding that ill nee to write a script to find text with HTML markups <b></b> and <strong></strong>,and tell the javascript to bold that text using the following method:
$objRichText = new PHPExcel_RichText();
$objRichText->createText('This text is ');
$objBoldTextRun = $objRichText->createTextRun('bold');
$objBoldTextRun->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getCell('B1')->setValue($objRichText);
I would imagine that with Jquery I would use something like the event .find but not quite sure what the best way to approach something like this. This is honestly way beyond my level of comprehension but willing to give it a shot with some help.
Update updated code:
<?php
/** Error reporting */
/** PHPExcel */
require_once '../js/PHPExcel/Classes/PHPExcel.php';
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$rows=2;
$sheet=$objPHPExcel->getActiveSheet();
$wizard = new PHPExcel_Helper_HTML();
//Font Setting for the Support group title.
$Support_team = array('font'=> array('bold'=> true,'color' => array('rgb' => '4D4D4D'),'size' => 22,'name' => 'Arial'),'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER),);
//Font settings for the header cells only.
$headers = array('font'=> array('bold'=> true,'color' => array('rgb' => '4D4D4D'),'size' => 12,'name' => 'Arial'),'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER),);
//Border settings
$borders = array('borders' => array('inside'=> array('style' => PHPExcel_Style_Border::BORDER_THIN,'color' => array('argb' => '717171')),'outline' => array('style' => PHPExcel_Style_Border::BORDER_THIN,'color' => array('argb' => '717171'))));
// SQl database connections
$db = mysql_connect("localhost", "IMC_Admin", "IMCisgreat2014");
mysql_select_db("imc_directory_tool",$db);
$sql="select client,team_name,support_team_prime,prime_comments,support_team_backup,backup_comments,escalation1,escalation1_comments,escalation2,escalation2_comments,escalation3,escalation3_comments,escalation4,escalation4_comments,note from tbl_address ORDER BY team_name";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
if ($numrows>0)
{
while($data=mysql_fetch_array($result))
{
//Cell Wraptext
$sheet->getStyle('C'.($rows+1).':D'.($rows+1))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+3).':D'.($rows+3))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+4).':D'.($rows+4))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+6).':D'.($rows+6))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+7).':D'.($rows+7))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+8).':D'.($rows+8))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+9).':D'.($rows+9))->getAlignment()->setWrapText(true);
$sheet->getStyle('B'.($rows+11).':D'.($rows+11))->getAlignment()->setWrapText(true);
$richTextClient = $wizard->toRichTextObject($data['client']);
$richTextteam_name = $wizard->toRichTextObject($data['team_name']);
$richTextsupport_team_prime = $wizard->toRichTextObject($data['support_team_prime']);
$richTextprime_comments = $wizard->toRichTextObject($data['prime_comments']);
$richTextsupport_team_backup = $wizard->toRichTextObject($data['support_team_backup']);
$richTextbackup_comments = $wizard->toRichTextObject($data['backup_comments']);
$richTextescalation1 = $wizard->toRichTextObject($data['escalation1']);
$richTextescalation1_comments = $wizard->toRichTextObject($data['escalation1_comments']);
$richTextescalation2 = $wizard->toRichTextObject($data['escalation2']);
$richTextescalation2_comments = $wizard->toRichTextObject($data['escalation2_comments']);
$richTextescalation3 = $wizard->toRichTextObject($data['escalation3']);
$richTextescalation3_comments = $wizard->toRichTextObject($data['escalation3_comments']);
$richTextescalation4 = $wizard->toRichTextObject($data['escalation4']);
$richTextescalation4_comments = $wizard->toRichTextObject($data['escalation4_comments']);
$richTextNote = $wizard->toRichTextObject($data['note']);
//This section is the actual data imported from the SQL database *don't touch*
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('C'.($rows+1),$richTextClient) //this will give cell C2.
->setCellValue('B'.$rows,$richTextteam_name) // this will give cell B2
->setCellValue('C'.($rows+3),$richTextsupport_team_prime) //this will give C5
->setCellValue('D'.($rows+3),$richTextprime_comments) // This will give D5
->setCellValue('C'.($rows+4),$richTextsupport_team_backup) //This will give C6
->setCellValue('D'.($rows+4),$richTextbackup_comments) //This will give D6
->setCellValue('C'.($rows+6),$richTextescalation1)//THis will give you C8
->setCellValue('D'.($rows+6),$richTextescalation1_comments)//This will give you D8
->setCellValue('C'.($rows+7),$richTextescalation2)//This will give you C9
->setCellValue('D'.($rows+7),$richTextescalation2_comments)//This will give you D9
->setCellValue('C'.($rows+8),$richTextescalation3)//This will give you C10
->setCellValue('D'.($rows+8),$richTextescalation3_comments)//This will give you D10
->setCellValue('C'.($rows+9),$richTextescalation4)//This will give you C11
->setCellValue('D'.($rows+9),$richTextescalation4_comments)//This will give you D11
->setCellValue('B'.($rows+11),$richTextNote); //This will give you B13
//Cell Merging
$sheet
->mergeCells('B'.$rows.':D'.$rows)
->mergeCells('B'.($rows+2).':D'.($rows+2))
->mergeCells('B'.($rows+5).':D'.($rows+5))
->mergeCells('B'.($rows+10).':D'.($rows+10))
->mergeCells('C'.($rows+1).':D'.($rows+1))
->mergeCells('B'.($rows+11).':D'.($rows+11));
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('B'.($rows+1), 'Client:')
->setCellValue('B'.($rows+2), 'Support group contacts')
->setCellValue('B'.($rows+3), 'Prime:')
->setCellValue('B'.($rows+4), 'Backup:')
->setCellValue('B'.($rows+5), 'Escalations')
->setCellValue('B'.($rows+6), 'Escalation 1:')
->setCellValue('B'.($rows+7), 'Escalation 2:')
->setCellValue('B'.($rows+8), 'Escalation 3:')
->setCellValue('B'.($rows+9), 'Escalation 4:')
->setCellValue('B'.($rows+10), 'Notes');
//Format the hardcoded text
$sheet->getStyle('B'.$rows)->applyFromArray($Support_team);
$sheet->getStyle('B'.($rows+2))->applyFromArray($headers);
$sheet->getStyle('B'.($rows+5))->applyFromArray($headers);
$sheet->getStyle('B'.($rows+10))->applyFromArray($headers);
//Row height adjustments
$sheet->getRowDimension($rows+3)->setRowHeight(60);
$sheet->getRowDimension($rows+4)->setRowHeight(60);
$sheet->getRowDimension($rows+6)->setRowHeight(60);
$sheet->getRowDimension($rows+7)->setRowHeight(60);
$sheet->getRowDimension($rows+8)->setRowHeight(60);
$sheet->getRowDimension($rows+9)->setRowHeight(60);
$sheet->getRowDimension($rows+11)->setRowHeight(100);
//Background color on cells
$sheet->getStyle('B'.$rows.':D'.$rows)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+2).':D'.($rows+2))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+5).':D'.($rows+5))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+10).':D'.($rows+10))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+1))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+3))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+4))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+6))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+7))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+8))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+9))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
//Border range
$sheet->getStyle('B'.$rows.':D'.($rows+11))->applyFromArray($borders);
$rows+=14;
}
}
//This is the hard coded *non dynamic* cell formatting
$sheet->getColumnDimension('A')->setWidth(5);
$sheet->getColumnDimension('B')->setWidth(15);
$sheet->getColumnDimension('C')->setWidth(50);
$sheet->getColumnDimension('D')->setWidth(50);
$sheet->getSheetView()->setZoomScale(90);
$sheet->getStyle('A:D') ->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
// Rename sheet
$sheet->setTitle('Directory Tool Full dump');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel2007)
$today=date("F.d.Y");
$filename = "Directory_Export-$today.xlsx";
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=$filename");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>

If you're using the latest develop branch from the PHPExcel github repo, there is actually an html to rich text helper class:
The file 42richText.php in the Examples folder demonstrates its use:
$html1='<font color="#0000ff">
<h1 align="center">My very first example of rich text<br />generated from html markup</h1>
<p>
<font size="14" COLOR="rgb(0,255,128)">
<b>This block</b> contains an <i>italicized</i> word;
while this block uses an <u>underline</u>.
</font>
</p>
<p align="right"><font size="9" color="red">
I want to eat <ins><del>healthy food</del><strong>pizza</strong></ins>.
</font>
';
$html2='<p>
<font color="#ff0000">
100°C is a hot temperature
</font>
<br>
<font color="#0080ff">
10°F is cold
</font>
</p>';
$html3='2<sup>3</sup> equals 8';
$html4='H<sub>2</sub>SO<sub>4</sub> is the chemical formula for Sulphuric acid';
$wizard = new PHPExcel_Helper_HTML;
$richText = $wizard->toRichTextObject($html1);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', $richText);
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(48);
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A1')
->getAlignment()
->setWrapText(true);
$richText = $wizard->toRichTextObject($html2);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A2', $richText);
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A2')
->getAlignment()
->setWrapText(true);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A3', $wizard->toRichTextObject($html3));
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A4', $wizard->toRichTextObject($html4));

Related

How to get the ChoiceField value using javascript

First of all sorry for my bad english i am french !
So i have a little problem. I use the django built-in class ChoiceField in my form :
class LogForm(forms.Form):
FormData = (('1', 'Code',), ('2', 'Normal',), ('3', 'Hexa',))
choixFormData = forms.ChoiceField(label=' Forme des donnees ', choices=FormData)
liaison = (('1', 'RS232_1_Port1',), ('2', 'RS232_1_Port2',), ('3', 'RS232_1_Port3',), ('4', 'RS232_1_Port4',),
('5', 'RS422_1_Port1',), ('6', 'RS422_1_Port2',), ('7', 'RS422_1_Port3',), ('8', 'RS422_1_Port4',),
('9', 'RS422_2_Port1',), ('10', 'RS422_2_Port2',), ('11', 'RS422_2_Port3',), ('12', 'RS422_2_Port4',),
('13', 'VoieNumAna',), ('14', 'CAN1',), ('15', '1553',))
choixLiaison = forms.ChoiceField(label='Liaison', choices=liaison)
Data = forms.CharField(required=False, label=' Data ', max_length=100, widget=forms.Textarea)
And i also use the Django Channels in order to implement websockets in my app.
The thing is, i want to be able to render the form thanks to the view ( this is working fine ) and then i want to get the value of the selected choice ( once the the form is rendered ) using javascript.
I tried this :
document.querySelector('#id_Start').onclick = function(e) {
const messageInputDom = document.querySelector('#id_choixLiaison');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
}
I am very new to javascript and i dont understand the reason why this is not working.
I want to be able to get the value of the selected choice field in a string.
Do not hesitate to tell me if the question is badly asked or if you need more details.
Thank you !

Quills JS: extracting formatted text, saving it on server, loading it and identifying specific parts

For a project I am trying to make a message / newsletter system to function on a website.
I am using Quill JS as my RTE that loads a template whenever the editor is opened.
Upon sending the message it saves an html copy of the message to the server with an ID
Saving the content of editor in a form on submit
<input type="hidden" name="doctext" id="doctext" value='<?php echo $doctext; ?>'>
Writing the content to file (PHP)
$doctext = trim($_POST["doctext"]);
$myfile = fopen("$postid.html", "w") or die("Unable to open file!");
$txt = $doctext;
fwrite($myfile, $txt);
Now I want to make a feed that lists all of the messages / newsletters with the headline and a sample of the content. Unfortunately Quill JS removes / doesn't use any ids for the HTML in the editor and it is therefore hard to identify the headline and content area.
The only solution that I can see is to put in some invisible text before and after the headline and content, that will be visible in the HTML, but I know that this would never be approved for a real system.
I know my way around HTML and CSS fine, but when it comes to PHP and JS I am not that comfortable.
There is probably a cool tool / solution out there that I don't know about and I would be happy to receive any insight to a more proper solution.
Edit: I can see that even in the delta(s) format, there aren't any identifiers.
Edit: JS QUILL code:
var Size = Quill.import('attributors/style/size');
Size.whitelist = ['0px', '12px','16px','20px','24px', '28px', '32px',
'36px'];
Quill.register(Size, true);
const Block = Quill.import('blots/block');
class Overskrift extends Block {}
Overskrift.blotName = 'overskrift';
Overskrift.tagName = 'p';
Overskrift.className = 'overskrift-class';
Quill.register(Overskrift, true);
var toolbarOptions = [
['bold', 'italic', 'underline', 'strike'],
[{ 'list': 'ordered'}, { 'list': 'bullet' }],
['image'],
[{ 'size': ['12px', '16px', '20px', '24px', '28px', '32px', '36px'] }],
[{ 'align': ''}, {'align': 'center'}, {'align': 'right'}],
];
var Delta = Quill.import('delta');
var quill = new Quill("#texteditor", {
theme: 'snow',
modules: {
toolbar: toolbarOptions
}
});
Best regards
Martin Pedersen
In order to make Quill keep/add a certain class for an element, you have to configure it manually through Quill instead of adding them yourself.
You can achieve that by:
const Block = Quill.import('blots/block');
class HeadLine extends Block {}
HeadLine.blotName = 'headline';
HeadLine.tagName = 'h1';
HeadLine.className = 'headline-class';
Quill.register(HeadLine, true);
This will add/remove the headline-class for the h1 class when you use the headline blot. and if you want to have more control on the headline element you can do:
class HeadLine extends Block {
static create(value) {
const node = super.create(value);
node.classList.add('headline-class');
return node;
}
}
And to set the contents of the editor you can do:
quill.setContents('{"ops":[{"insert":"Headline"},{"attributes":{"headline":true},"insert":"\n"},{"insert":"\n\ncontent"},{"attributes":{"content":true},"insert":"\n"}]}')
Now you have full control on the node itself.
Also, I created a jsFiddle that I hope it helps you:
https://jsfiddle.net/hassansalem/c5nvgfq1/6/

Scraping a site with PHP which has variables in double curly brackets instead of text [duplicate]

This question already has answers here:
Scrape web page data generated by javascript
(2 answers)
Closed 8 years ago.
I am stuck with a scraping task in my project.
i want to grab the data from the link in $html , all table content of tr and td , here i am trying to grab the link but it only shows javascript: self.close()
<?php
include("simple_html_dom.php");
$html = file_get_html('http://www.areacodelocations.info/allcities.php?ac=201');
foreach($html->find('a') as $element)
echo $element->href . '<br>';
?>
Usually, this kind of pages load a bunch of Javascript (jQuery, etc.), which then builds the interface and retrieves the data to be displayed from a data source.
So what you need to do is open that page in Firefox or similar, with a tool such as Firebug in order to see what requests are actually being done. If you're lucky, you will find it directly in the list of XHR requests. As in this case:
http://www.govliquidation.com/json/buyer_ux/salescalendar.js
Notice that this course of action may infringe on some license or terms of use. Clear this with the webmaster/data source/copyright owner before proceeding: detecting and forbidding this kind of scraping is very easy, and identifying you is probably only slightly less so.
Anyway, if you issue the same call in PHP, you can directly scrape the data (provided there is no session/authentication issue, as seems the case here) with very simple code:
<?php
$url = "http://www.govliquidation.com/json/buyer_ux/salescalendar.js";
$json = file_get_contents($url);
$data = json_decode($json);
?>
This yields a data object that you can inspect and convert in CSV by simple looping.
stdClass Object
(
[result] => stdClass Object
(
[events] => Array
(
[0] => stdClass Object
(
[yahoo_dur] => 11300
[closing_today] => 0
[language_code] => en
[mixed_id] => 9297
[event_id] => 9297
[close_meridian] => PM
[commercial_sale_flag] => 0
[close_time] => 01/06/2014
[award_time_unixtime] => 1389070800
[category] => Tires, Parts & Components
[open_time_unixtime] => 1388638800
[yahoo_date] => 20140102T000000Z
[open_time] => 01/02/2014
[event_close_time] => 2014-01-06 17:00:00
[display_event_id] => 9297
[type_code] => X3
[title] => Truck Drive Axles # Killeen, TX
[special_flag] => 1
[demil_flag] => 0
[google_close] => 20140106
[event_open_time] => 2014-01-02 00:00:00
[google_open] => 20140102
[third_party_url] =>
[bid_package_flag] => 0
[is_open] => 1
[fda_count] => 0
[close_time_unixtime] => 1389045600
You retrieve $data->result->events, use fputcsv() on its items converted to array form, and Bob's your uncle.
In the case of the second site, you have a table with several TR elements, and you want to catch the first two TD children of each TR.
By inspecting the source code you see something like this:
<tr>
<td> Allendale</td>
<td> Eastern Time
</td>
</tr>
<tr>
<td> Alpine</td>
<td> Eastern Time
</td>
So you just grab all the TR's
<?php
include("simple_html_dom.php");
$html = file_get_html('http://www.areacodelocations.info/allcities.php?ac=201');
$fp = fopen('output.csv', 'w');
if (!$fp) die("Cannot open output CSV - permission problems maybe?");
foreach($html->find('tr') as $tr) {
$csv = array(); // Start empty. A new CSV row for each TR.
// Now find the TD children of $tr. They will make up a row.
foreach($tr->find('td') as $td) {
// Get TD's innertext, but
$csv[] = $td->innertext;
}
fputcsv($fp, $csv);
}
fclose($fp);
?>
You will notice that the CSV text is "dirty". That is because the actual text is:
<td> Alpine</td>
<td> Eastern Time[CARRIAGE RETURN HERE]
</td>
So to have "Alpine" and "Eastern Time", you have to replace
$csv[] = $td->innertext;
with something like
$csv[] = strip(
html_entity_decode (
$td->innertext,
ENT_COMPAT | ENT_HTML401,
'UTF-8'
)
);
Check out the PHP man page for html_entity_decode() about character set encoding and entity handling. The above ought to work -- and an ought and fifty cents will get you a cup of coffee :-)

PHP POST for HTML Select using another POST

This ain't something not working but just I'm confusing about how to do it, I want to fetch the values from my DB based on users' preferences that been chosen earlier.
These are the steps will be taken for my process:
User will select from images (will add HTML images then will whip it upon another selection)
Will continue till reaching last stage
Last stage will have 3 Select (dropdown menus) and 2 of them will change the content according to what user's chooses (like country and state dd)
My PHP:
else if ($_POST["data_key"]=="last")
{
$final_arr;
$fetcher_theme = $_POST["themeid"];
$fetcher_category= $_POST["themecategory"];
$fetcher_product= $_POST["themeproduct"];
$fetcher_cover = $_POST["ctitle"];
$myquery="SELECT DISTINCT Layout.* FROM Layout,Products,Occasion, Cover, Theme
WHERE Layout.product=$fetcher_product
AND Layout.occasion=$fetcher_category
AND Layout.theme=$fetcher_theme
AND Layout.cover=$fetcher_cover;";
$results=$DB->fetchAll($myquery);
foreach ($results as $row) {
$row["current"]="size";
unset($row["pixfizzId"]);
$final_arr[]=$row;
}
echo json_encode($final_arr);
}
else if ($_POST["data_key"]=="size")
{
$final_arr;
$fetcher = $_POST["selected_id"];
$fetcher_theme = $_POST["themeid"];
$fetcher_category= $_POST["themecategory"];
$fetcher_product= $_POST["themeproduct"];
$fetcher_cover = $_POST["ctitle"];
$fetcher_size = $_POST["stitle"];
$myquery="SELECT DISTINCT Size.stitle FROM Layout,Products,Occasion, Size, Theme
WHERE Layout.product=$fetcher_product
AND Layout.occasion=$fetcher_category
AND Layout.theme=$fetcher_theme
AND Layout.size=$fetcher_size
AND Layout.size=Size.id";
$results=$DB->fetchAll($myquery);
foreach ($results as $row) {
$row["current"]="finishing";
unset($row["pixfizzId"]);
$final_arr[]=$row;
}
echo json_encode($final_arr);
}
else if ($_POST["data_key"]=="finishing")
{
$final_arr;
$fetcher = $_POST["selected_id"];
$fetcher_theme = $_POST["themeid"];
$fetcher_category= $_POST["themecategory"];
$fetcher_product= $_POST["themeproduct"];
$fetcher_cover = $_POST["ctitle"];
$fetcher_size = $_POST["stitle"];
$fetcher_finishing = $_POST["ftitle"];
$myquery="SELECT DISTINCT Finishing.ftitle FROM Layout,Products,Occasion, Size, Cover, finishing, Theme
WHERE Layout.product=$fetcher_product
AND Layout.occasion=$fetcher_category
AND Layout.theme=$fetcher_theme
AND Layout.size=$fetcher_size
AND Layout.cover=$fetcher_cover
AND Layout.finishing=$fetcher_finishing";
$results=$DB->fetchAll($myquery);
foreach ($results as $row) {
$row["current"]="finishing";
unset($row["pixfizzId"]);
$final_arr[]=$row;
}
echo json_encode($final_arr);
}}
My Engine JS (what I assign):
myItem.setId(jsonData[i].id);
myItem.setImg(jsonData[i].image);
myItem.setTitle(jsonData[i].title);
My Selects in JS (printing HTML):
myString +="<a>Sizes: </a><br><select id='sizesSelect' style=' width:200px'></select><br><br>";
myString +="<a>Cover: </a><br><select id='coverSelect' style=' width:200px'><br></select><br><br>";
myString +="<a>Finishing: </a><br><select id='finishingSelect' style=' width:200px'></select><br><br><br>";
Appending to Select in JS:
myString +="<script>$('#sizesSelect').append('<option val="+i+">"+this.getSize()+"</option>')</script>";
Now I need to know how can I post again to my PHP server to fetch the the values to other selects (refer for the img).
Select Size -> Update Covers -> Select Covers -> Update Finishing -> Select Finishing
Instead of using SQL to store and present previous user choices, you could keep the previous choices as $_POST data by re-adding the choises to the HTML Form as hidden input fields. Example: <input type="hidden" text="foo" name="<?=htmlspecialchars($_POST['foo'])?>">

radio button list with text option cakephp

I am new to CakePHP. I need to make a form with radio buttons and the last one is "other" where the user can type in an answer in a text box.
Is there any way FormHelper can do this that's built in?
One way I was going to do was create a radio list and a text field. When "other" is selected Javascript will show the text field. For this I don't understand how to use any other variables besides the fields in the database. How does one create a variable from a model that can be accessed from a view and the value returned for processing?
For the model I have:
class User extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'title';
var $sourceOther = ' ';
var $passwordRepeat = ' ';
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = sha1(
$this->data[$this->alias]['password']);
}
// $this->data[$this->alias]['created']= CakeTime::gmt();
// $this->data[$this->alias]['updated']= CakeTime::gmt();
$this->data[$this->alias]['username']= $this->data[$this->alias]['email'];
return true;
In the view I have
echo $this->Form->input('mobilePhone',array(
'label'=>'Mobile or fixed phone with no spaces'));
echo $this->Form->input('alternatePhone');
echo $this->Form->input('leadSource', array(
'options'=>array('Google'=>'Google','OnlineAd'=>'Online Ad',
'Printed Media'=>'Printed Media','LetterDrop'=>'Letter Drop',
'Other'=>'Other (specify text)'),
'empty'=>'(choose one)'));
echo $this->Form->input($this->sourceOther);
...but it doesn't like sourceOther, the variable in the model. How do I get data from the view (the text box) into the user model so beforeSave can do something with it?
Thanks.
Thanks.
Sorted it out after reading "Cake PHP Application Development". It works for Cake 2.x and 1.2 (as used in the book).
In your view put:
echo $this->Form->input('sourceOther');
Then in the model you can access your variable with:
$this->data['User']['sourceOther'];
For example, use it to save "other" text field in beforesave:
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = sha1(
$this->data[$this->alias]['password']);
}
$this->data[$this->alias]['username'] = $this->data[$this->alias]['email'];
$this->data[$this->alias]['activation'] = md5(uniqid(rand(), true));
if ($this->data[$this->alias]['leadSource'] == 'Other') {
$this->data[$this->alias]['leadSource'] =
$this->data['User']['sourceOther'];
}
return true;
}

Categories